# Calendar files

`icalendar.write(events, stamp:)` writes a calendar file, RFC 5545's
`VCALENDAR` in UTF-8, as `Bytes`: what a route sends as `text/calendar`
([Sending raw bytes](/docs/output-and-status.md#sending-raw-bytes)), or a store keeps for
an email to attach.

- **`events` is a map of `CalendarEvent`s whose keys are built on
  `Uuid`.** Each event is under the identity your app keeps it by, such
  as a booking's `id`, which the file writes as its `UID`. So an event is in a file once, and a
  calendar that reads the file again changes the events it already has
  rather than adding them twice. Nothing in the file is random.
- **`stamp:` is when your app last changed them,** which the file writes
  as each event's `DTSTAMP`, in UTC to the second: the latest
  `updated_at` of the records they come from, or `clock.now`, which a
  test fixes with `clock:`. The same events and stamp always give the
  same bytes.
- **The file is** `BEGIN:VCALENDAR`, `VERSION:2.0` and
  `PRODID:-//Jadpo//Jadpo//EN`; a `VTIMEZONE` for each zone a timed
  event is in, by its IANA name; each event's text, in the map's order,
  with its `UID` and `DTSTAMP` after `BEGIN:VEVENT`; and
  `END:VCALENDAR`. An empty map is a calendar with no events, which a
  feed with nothing in it serves.
- **Every line ends with a carriage return and a line feed,** and a line
  longer than 75 octets is folded, as RFC 5545 3.1 asks: broken before
  its 76th octet, or before the character that octet is part of, so a
  character's UTF-8 is never split, and carried on after one space on
  the next line.
- **A zone's `VTIMEZONE`** comes from the time zone database Jadpo
  bundles: the offset in effect when its first event starts, and each
  change of its clocks until its last event ends. For a recurrence that
  is its last occurrence's end, or, for one that never ends, the end of
  2037. Calendars that know a zone by its IANA name, as the common ones
  do, use their own rules for it; RFC 5545 asks for the `VTIMEZONE` for
  those that don't.

An event whose last day is 31 December 9999 has no day after it to
write, so the file is the fault `time_out_of_range`, as the event's text
is. The call fails no other way.

A diary's file holds a half-term walk and a weekly night shift. The
shift is in London, so the file has London's zone: British Summer Time,
in effect when the shift starts, and the clocks going back that night:

```jadpo
type BookingId = Uuid {}

type DiaryFile = Bytes {}

type DiaryChanged = Instant {}

/// A diary's calendar file: each slot under the booking it is, stamped
/// when the diary last changed.
function diary_file(
    diary_slots: Map<BookingId, CalendarEvent>,
    changed: DiaryChanged
) -> DiaryFile {
    return DiaryFile(icalendar.write(diary_slots, stamp: changed))
}
```

```jadpo
test "a calendar file has each event once, its zone's clocks and its stamp" {
    var half_term: CalendarEvent = CalendarEvent {
        summary: "Half-term walk"
        first_day: "2026-10-24"
        last_day: "2026-10-26"
        start: none
        end: none
        zone: none
        location: "Keswick, Cumbria"
        description: none
        recurrence: none
    }
    var night_shift: CalendarEvent = CalendarEvent {
        summary: "Night shift"
        first_day: none
        last_day: none
        start: LocalDateTime {
            date: "2026-10-24"
            time: LocalTime {
                hour: 22
                minute: 0
                second: 0
            }
        }
        end: LocalDateTime {
            date: "2026-10-25"
            time: LocalTime {
                hour: 2
                minute: 0
                second: 0
            }
        }
        zone: Zone.europe_london
        location: none
        description: "Keys at the front desk; sign in, then out"
        recurrence: "DTSTART;TZID=Europe/London:20261024T220000\nRRULE:FREQ=WEEKLY;COUNT=4"
    }
    var diary: DiaryFile = diary_file(
        [
            "6f2d9c84-1e3b-4a7d-8c55-9b0e7a2f3d18": night_shift,
            "0b7c6f1e-5d0a-4c39-9a52-3f1d2e8a4b61": half_term
        ],
        "2026-10-20T18:00:00.750Z"
    )
    assert diary == encoding.to_utf8(
        "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Jadpo//Jadpo//EN\r\nBEGIN:VTIMEZONE\r\nTZID:Europe/London\r\nBEGIN:DAYLIGHT\r\nDTSTART:20260329T010000\r\nTZOFFSETFROM:+0000\r\nTZOFFSETTO:+0100\r\nTZNAME:BST\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nDTSTART:20261025T020000\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0000\r\nTZNAME:GMT\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nUID:0b7c6f1e-5d0a-4c39-9a52-3f1d2e8a4b61\r\nDTSTAMP:20261020T180000Z\r\nDTSTART;VALUE=DATE:20261024\r\nDTEND;VALUE=DATE:20261027\r\nSUMMARY:Half-term walk\r\nLOCATION:Keswick\\, Cumbria\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:6f2d9c84-1e3b-4a7d-8c55-9b0e7a2f3d18\r\nDTSTAMP:20261020T180000Z\r\nDTSTART;TZID=Europe/London:20261024T220000\r\nDTEND;TZID=Europe/London:20261025T020000\r\nSUMMARY:Night shift\r\nDESCRIPTION:Keys at the front desk\\; sign in\\, then out\r\nRRULE:FREQ=WEEKLY;COUNT=4\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
    )
}

test "a long line is folded between characters, never inside one" {
    var lakeside_tea: CalendarEvent = CalendarEvent {
        summary: "Lakeside tea"
        first_day: "2026-08-01"
        last_day: "2026-08-01"
        start: none
        end: none
        zone: none
        location: none
        description: "Tea on the terrace, then round the lake to the little old café for crème brûlée and a long sit in the sun by the water"
        recurrence: none
    }
    var diary: DiaryFile = diary_file(
        ["9c1e2f3a-4b5c-4d6e-8f70-81a2b3c4d5e6": lakeside_tea],
        "2026-07-20T09:00:00Z"
    )
    // `é` is two octets, the 75th and 76th, so its line breaks before it.
    assert diary == encoding.to_utf8(
        "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Jadpo//Jadpo//EN\r\nBEGIN:VEVENT\r\nUID:9c1e2f3a-4b5c-4d6e-8f70-81a2b3c4d5e6\r\nDTSTAMP:20260720T090000Z\r\nDTSTART;VALUE=DATE:20260801\r\nDTEND;VALUE=DATE:20260802\r\nSUMMARY:Lakeside tea\r\nDESCRIPTION:Tea on the terrace\\, then round the lake to the little old caf\r\n é for crème brûlée and a long sit in the sun by the water\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
    )
}

test "a diary with nothing in it is a calendar with no events" {
    assert diary_file([], "2026-10-20T18:00:00Z") == encoding.to_utf8(
        "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Jadpo//Jadpo//EN\r\nEND:VCALENDAR\r\n"
    )
}
```

A booking's invite is its slot alone, under the booking's own `id`, and
stamped by the clock of the action that writes it:

```jadpo
/// A booking's invite, as a calendar file.
type InviteFile = Output {
    ics: Bytes
}
```

```jadpo
use diary/entities { Booking, BookingNotFound }
use diary/types { InviteFile }

/// A booking's invite: its slot under the booking's `id`, stamped now.
action invite(booking_id: Booking.id) fails BookingNotFound -> InviteFile {
    var booking: Booking = attempt Booking.get(booking_id)
    var no_slots: Map<Uuid, CalendarEvent> = []
    return InviteFile {
        ics: icalendar.write(map.with(no_slots, booking.id, booking.slot), stamp: clock.now)
    }
}
```

```jadpo
use diary/entities { Booking }
use diary/types { InviteFile }
use diary/actions { book }

test "an invite is stamped by the test's clock" {
    clock: "2026-10-20T18:00:00Z"

    var half_term: CalendarEvent = CalendarEvent {
        summary: "Half-term walk"
        first_day: "2026-10-24"
        last_day: "2026-10-26"
        start: none
        end: none
        zone: none
        location: "Keswick, Cumbria"
        description: none
        recurrence: none
    }
    var booked: Booking = book(half_term)
    var sent: InviteFile = attempt invite(booked.id)
    var before_uid: Text = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Jadpo//Jadpo//EN\r\nBEGIN:VEVENT\r\nUID:"
    var after_uid: Text = "\r\nDTSTAMP:20261020T180000Z\r\nDTSTART;VALUE=DATE:20261024\r\nDTEND;VALUE=DATE:20261027\r\nSUMMARY:Half-term walk\r\nLOCATION:Keswick\\, Cumbria\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
    assert sent.ics == encoding.to_utf8(before_uid + text.from(booked.id) + after_uid)
}
```
