@wtfalch/calendar 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/calendar/calendar-client.js +574 -19
- package/dist/calendar/calendar.css +13 -0
- package/dist/calendar/client.d.ts +27 -0
- package/dist/calendar/client.js +101 -0
- package/dist/calendar/fake/sample.d.ts +2 -1
- package/dist/calendar/fake/store.d.ts +51 -8
- package/dist/calendar/fake/store.js +539 -47
- package/dist/calendar/find-time.d.ts +17 -0
- package/dist/calendar/find-time.js +198 -0
- package/dist/calendar/ics.d.ts +73 -0
- package/dist/calendar/ics.js +586 -0
- package/dist/calendar/index.d.ts +3 -1
- package/dist/calendar/index.js +1 -0
- package/dist/calendar/react/Calendar.js +36 -27
- package/dist/calendar/react/EventDetail.js +22 -1
- package/dist/calendar/react/EventEditor.js +65 -3
- package/dist/calendar/types.d.ts +550 -17
- package/dist/calendar/wire.d.ts +161 -5
- package/dist/calendar/wire.js +304 -4
- package/package.json +2 -2
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Export a `CalendarEvent` (or several) as an RFC 5545 `.ics` document
|
|
3
|
+
* (wtfalch/calendar#28), and `icsToEventDrafts` to import one back
|
|
4
|
+
* (wtfalch/calendar#41, the other half of agora#159,
|
|
5
|
+
* https://github.com/wtfalch/agora/issues/159). Read-only subscription feeds
|
|
6
|
+
* are still a separate, deferred gap (`PRODUCT.md`) -- `icsToEventDrafts` is
|
|
7
|
+
* a one-time parse, not a poller, and has no opinion on where its output
|
|
8
|
+
* ends up (`CalendarClient.importIcs`, `types.ts`, calls `createEvent` once
|
|
9
|
+
* per draft).
|
|
10
|
+
*
|
|
11
|
+
* **Every date-time is written in UTC (`Z`-suffixed), naively.** `start` is
|
|
12
|
+
* a local date-time with no offset, and `timeZone` says which zone it is
|
|
13
|
+
* local to -- but this package already treats every `start` as if it were
|
|
14
|
+
* UTC for its own display arithmetic (`EventDetail.tsx`'s `formatWhen`,
|
|
15
|
+
* `Calendar.tsx`'s grid rendering both do `new Date(`${event.start}Z`)`).
|
|
16
|
+
* Doing anything more accurate here -- resolving a named zone's real UTC
|
|
17
|
+
* offset -- would make this file the one place in the package that treats
|
|
18
|
+
* `timeZone` differently from everywhere else, for an event whose zone is
|
|
19
|
+
* "UTC" or unset in every fixture and every sample this package ships.
|
|
20
|
+
* `RecurrenceRule.until` shares the same treatment, which is also what RFC
|
|
21
|
+
* 5545 §3.3.10 requires: `UNTIL` must carry the same value type (UTC or
|
|
22
|
+
* not) as `DTSTART`.
|
|
23
|
+
*
|
|
24
|
+
* **`rscale`/`skip` (RFC 8984 §3.3, non-Gregorian calendars) have no RFC
|
|
25
|
+
* 5545 `RRULE` equivalent** and are silently omitted -- there is no
|
|
26
|
+
* standard part to write them into. Every other `CalendarRecurrenceRule`
|
|
27
|
+
* part round-trips (wtfalch/calendar#27's own `byDay`/`byMonthDay`/`byMonth`/
|
|
28
|
+
* `bySetPosition`/`firstDayOfWeek`/... included).
|
|
29
|
+
*
|
|
30
|
+
* **`virtualLocations` and `alerts` are not carried into the export.**
|
|
31
|
+
* Neither RFC 5545 property (`VALARM` for alerts; nothing standard for a
|
|
32
|
+
* join link distinct from `LOCATION`) was part of this ticket's evidence
|
|
33
|
+
* (`EventDetail.tsx` has no export control at all, not "an export control
|
|
34
|
+
* that drops one field"), so adding them is left to a later ticket.
|
|
35
|
+
*/
|
|
36
|
+
import { parseDurationMs } from "./wire.js";
|
|
37
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
38
|
+
/** RFC 5545 §3.3.11 `TEXT` escaping. Order matters: the backslash escape
|
|
39
|
+
* must run first, or every other escape's own backslash gets escaped
|
|
40
|
+
* again. */
|
|
41
|
+
function escapeText(value) {
|
|
42
|
+
return value
|
|
43
|
+
.replace(/\\/g, '\\\\')
|
|
44
|
+
.replace(/;/g, '\\;')
|
|
45
|
+
.replace(/,/g, '\\,')
|
|
46
|
+
.replace(/\r\n|\r|\n/g, '\\n');
|
|
47
|
+
}
|
|
48
|
+
/** RFC 5545 §3.2's `param-value`: quoted when it carries a character the
|
|
49
|
+
* bare form cannot (`,`, `;`, `:`); a `"` is stripped rather than escaped,
|
|
50
|
+
* since a quoted param value has no escape for one (`QSAFE-CHAR` excludes
|
|
51
|
+
* `DQUOTE` outright). */
|
|
52
|
+
function paramValue(value) {
|
|
53
|
+
const cleaned = value.replace(/"/g, "'");
|
|
54
|
+
return /[,;:]/.test(cleaned) ? `"${cleaned}"` : cleaned;
|
|
55
|
+
}
|
|
56
|
+
/** RFC 5545 §3.1's line folding: no content line may exceed 75 octets: a
|
|
57
|
+
* longer one is split, each continuation introduced by CRLF and a single
|
|
58
|
+
* space (which itself counts as an octet on that continuation line, hence
|
|
59
|
+
* the narrower budget after the first chunk). Splits on octet boundaries,
|
|
60
|
+
* never mid-UTF-8-sequence -- backing off while the next byte is a
|
|
61
|
+
* continuation byte (`10xxxxxx`) -- so a title with an accented letter or
|
|
62
|
+
* an emoji folds without corrupting it. */
|
|
63
|
+
function foldLine(line) {
|
|
64
|
+
const bytes = new TextEncoder().encode(line);
|
|
65
|
+
if (bytes.length <= 75)
|
|
66
|
+
return line;
|
|
67
|
+
const decoder = new TextDecoder();
|
|
68
|
+
const chunks = [];
|
|
69
|
+
let start = 0;
|
|
70
|
+
let budget = 75;
|
|
71
|
+
while (start < bytes.length) {
|
|
72
|
+
let end = Math.min(start + budget, bytes.length);
|
|
73
|
+
while (end > start && ((bytes[end] ?? 0) & 0xc0) === 0x80)
|
|
74
|
+
end -= 1;
|
|
75
|
+
chunks.push(decoder.decode(bytes.slice(start, end)));
|
|
76
|
+
start = end;
|
|
77
|
+
budget = 74; // the continuation's own leading space is the 75th octet
|
|
78
|
+
}
|
|
79
|
+
return chunks.join('\r\n ');
|
|
80
|
+
}
|
|
81
|
+
/** `"2026-10-05T09:00:00"` -> `"20261005T090000Z"` (naive-UTC; see the file
|
|
82
|
+
* header). Slicing to 15 after stripping punctuation drops any fractional
|
|
83
|
+
* seconds this package never produces but should not choke on. */
|
|
84
|
+
function basicDateTime(local) {
|
|
85
|
+
return `${local.replace(/[-:]/g, '').slice(0, 15)}Z`;
|
|
86
|
+
}
|
|
87
|
+
/** `"2026-10-05T09:00:00"` -> `"20261005"`, for an all-day `DTSTART`/`DTEND`
|
|
88
|
+
* (`VALUE=DATE`, which carries no time or zone at all). */
|
|
89
|
+
function basicDate(local) {
|
|
90
|
+
return local.slice(0, 10).replace(/-/g, '');
|
|
91
|
+
}
|
|
92
|
+
function isoBasicUtc(date) {
|
|
93
|
+
return `${date.toISOString().replace(/[-:]/g, '').split('.')[0]}Z`;
|
|
94
|
+
}
|
|
95
|
+
/** The event's own end, in the same naive-UTC local shape `start` is in.
|
|
96
|
+
* `DTEND`/`VALUE=DATE`'s own end is exclusive (RFC 5545 §3.6.1), which an
|
|
97
|
+
* all-day event's whole-day duration already lands on: "2 days" starting
|
|
98
|
+
* the 5th ends, exclusive, the 7th -- the day after the last day. */
|
|
99
|
+
function computeEnd(event) {
|
|
100
|
+
const ms = parseDurationMs(event.duration) ?? (event.isAllDay ? DAY_MS : 0);
|
|
101
|
+
const end = new Date(new Date(`${event.start}Z`).getTime() + ms);
|
|
102
|
+
return end.toISOString().slice(0, 19);
|
|
103
|
+
}
|
|
104
|
+
const FREQ_ICS = {
|
|
105
|
+
daily: 'DAILY',
|
|
106
|
+
weekly: 'WEEKLY',
|
|
107
|
+
monthly: 'MONTHLY',
|
|
108
|
+
yearly: 'YEARLY',
|
|
109
|
+
};
|
|
110
|
+
const WEEKDAY_ICS = {
|
|
111
|
+
mo: 'MO',
|
|
112
|
+
tu: 'TU',
|
|
113
|
+
we: 'WE',
|
|
114
|
+
th: 'TH',
|
|
115
|
+
fr: 'FR',
|
|
116
|
+
sa: 'SA',
|
|
117
|
+
su: 'SU',
|
|
118
|
+
};
|
|
119
|
+
function ndayToIcs(day) {
|
|
120
|
+
return `${day.nthOfPeriod ?? ''}${WEEKDAY_ICS[day.day]}`;
|
|
121
|
+
}
|
|
122
|
+
/** RFC 5545 §3.3.10's `RRULE` value, parts in the order that section lists
|
|
123
|
+
* them. Every `CalendarRecurrenceRule` part but `rscale`/`skip` (the file
|
|
124
|
+
* header's own note) has a part here. */
|
|
125
|
+
function rruleValue(rule) {
|
|
126
|
+
const parts = [`FREQ=${FREQ_ICS[rule.frequency]}`];
|
|
127
|
+
if (rule.until !== undefined)
|
|
128
|
+
parts.push(`UNTIL=${basicDateTime(rule.until)}`);
|
|
129
|
+
if (rule.count !== undefined)
|
|
130
|
+
parts.push(`COUNT=${rule.count}`);
|
|
131
|
+
if (rule.interval !== undefined)
|
|
132
|
+
parts.push(`INTERVAL=${rule.interval}`);
|
|
133
|
+
if (rule.bySecond && rule.bySecond.length > 0)
|
|
134
|
+
parts.push(`BYSECOND=${rule.bySecond.join(',')}`);
|
|
135
|
+
if (rule.byMinute && rule.byMinute.length > 0)
|
|
136
|
+
parts.push(`BYMINUTE=${rule.byMinute.join(',')}`);
|
|
137
|
+
if (rule.byHour && rule.byHour.length > 0)
|
|
138
|
+
parts.push(`BYHOUR=${rule.byHour.join(',')}`);
|
|
139
|
+
if (rule.byDay && rule.byDay.length > 0) {
|
|
140
|
+
parts.push(`BYDAY=${rule.byDay.map(ndayToIcs).join(',')}`);
|
|
141
|
+
}
|
|
142
|
+
if (rule.byMonthDay && rule.byMonthDay.length > 0) {
|
|
143
|
+
parts.push(`BYMONTHDAY=${rule.byMonthDay.join(',')}`);
|
|
144
|
+
}
|
|
145
|
+
if (rule.byYearDay && rule.byYearDay.length > 0) {
|
|
146
|
+
parts.push(`BYYEARDAY=${rule.byYearDay.join(',')}`);
|
|
147
|
+
}
|
|
148
|
+
if (rule.byWeekNo && rule.byWeekNo.length > 0)
|
|
149
|
+
parts.push(`BYWEEKNO=${rule.byWeekNo.join(',')}`);
|
|
150
|
+
if (rule.byMonth && rule.byMonth.length > 0)
|
|
151
|
+
parts.push(`BYMONTH=${rule.byMonth.join(',')}`);
|
|
152
|
+
if (rule.bySetPosition && rule.bySetPosition.length > 0) {
|
|
153
|
+
parts.push(`BYSETPOS=${rule.bySetPosition.join(',')}`);
|
|
154
|
+
}
|
|
155
|
+
if (rule.firstDayOfWeek !== undefined)
|
|
156
|
+
parts.push(`WKST=${WEEKDAY_ICS[rule.firstDayOfWeek]}`);
|
|
157
|
+
return parts.join(';');
|
|
158
|
+
}
|
|
159
|
+
/** `calendarAddress` arrives off the wire (and out of `wire.ts`) already
|
|
160
|
+
* `mailto:`-prefixed (`react/participants.ts`'s own `addressOf` strips it
|
|
161
|
+
* for display) -- normalized rather than assumed, since a caller can build
|
|
162
|
+
* a `CalendarEventDraft` by hand with a bare address. Not imported from
|
|
163
|
+
* `react/participants.ts`: this file is the framework-free core, which
|
|
164
|
+
* never reaches into `./react` (mirrors `types.ts`'s own header comment on
|
|
165
|
+
* `wire.ts` staying behind the client). */
|
|
166
|
+
function normalizeMailto(address) {
|
|
167
|
+
return `mailto:${address.trim().replace(/^mailto:/i, '')}`;
|
|
168
|
+
}
|
|
169
|
+
const ROLE_ICS = {
|
|
170
|
+
owner: 'CHAIR',
|
|
171
|
+
chair: 'CHAIR',
|
|
172
|
+
attendee: 'REQ-PARTICIPANT',
|
|
173
|
+
optional: 'OPT-PARTICIPANT',
|
|
174
|
+
informational: 'NON-PARTICIPANT',
|
|
175
|
+
};
|
|
176
|
+
const PARTSTAT_ICS = {
|
|
177
|
+
'needs-action': 'NEEDS-ACTION',
|
|
178
|
+
accepted: 'ACCEPTED',
|
|
179
|
+
declined: 'DECLINED',
|
|
180
|
+
tentative: 'TENTATIVE',
|
|
181
|
+
};
|
|
182
|
+
/** `ORGANIZER` (the participant carrying the `owner` role, if any) and one
|
|
183
|
+
* `ATTENDEE` per participant besides them -- RFC 5545 §3.2.3/§3.8.4.1/
|
|
184
|
+
* §3.8.4.3. An owner still appears as `ORGANIZER` only, never doubled as
|
|
185
|
+
* their own `ATTENDEE`. */
|
|
186
|
+
function participantLines(participants) {
|
|
187
|
+
const organizer = participants.find((person) => (person.roles ?? []).includes('owner'));
|
|
188
|
+
const lines = [];
|
|
189
|
+
if (organizer !== undefined) {
|
|
190
|
+
const cn = organizer.name !== undefined ? `;CN=${paramValue(organizer.name)}` : '';
|
|
191
|
+
lines.push(`ORGANIZER${cn}:${normalizeMailto(organizer.calendarAddress)}`);
|
|
192
|
+
}
|
|
193
|
+
for (const person of participants) {
|
|
194
|
+
if (person === organizer)
|
|
195
|
+
continue;
|
|
196
|
+
const role = (person.roles ?? []).find((r) => r !== 'owner') ?? 'attendee';
|
|
197
|
+
const cn = person.name !== undefined ? `;CN=${paramValue(person.name)}` : '';
|
|
198
|
+
const partstat = person.participationStatus !== undefined
|
|
199
|
+
? `;PARTSTAT=${PARTSTAT_ICS[person.participationStatus]}`
|
|
200
|
+
: '';
|
|
201
|
+
lines.push(`ATTENDEE;ROLE=${ROLE_ICS[role]}${partstat}${cn}:${normalizeMailto(person.calendarAddress)}`);
|
|
202
|
+
}
|
|
203
|
+
return lines;
|
|
204
|
+
}
|
|
205
|
+
function veventLines(event, now) {
|
|
206
|
+
const lines = ['BEGIN:VEVENT', `UID:${event.uid}`, `DTSTAMP:${isoBasicUtc(now)}`];
|
|
207
|
+
const end = computeEnd(event);
|
|
208
|
+
if (event.isAllDay) {
|
|
209
|
+
lines.push(`DTSTART;VALUE=DATE:${basicDate(event.start)}`, `DTEND;VALUE=DATE:${basicDate(end)}`);
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
lines.push(`DTSTART:${basicDateTime(event.start)}`, `DTEND:${basicDateTime(end)}`);
|
|
213
|
+
}
|
|
214
|
+
lines.push(`SUMMARY:${escapeText(event.title)}`);
|
|
215
|
+
if (event.description !== undefined)
|
|
216
|
+
lines.push(`DESCRIPTION:${escapeText(event.description)}`);
|
|
217
|
+
if (event.location !== undefined)
|
|
218
|
+
lines.push(`LOCATION:${escapeText(event.location)}`);
|
|
219
|
+
lines.push(`STATUS:${event.status.toUpperCase()}`, `SEQUENCE:${event.sequence}`);
|
|
220
|
+
// RFC 5545 §3.8.2.7: OPAQUE is the default, so only a 'free' event
|
|
221
|
+
// (wtfalch/calendar#29) needs the line.
|
|
222
|
+
if (event.freeBusyStatus === 'free')
|
|
223
|
+
lines.push('TRANSP:TRANSPARENT');
|
|
224
|
+
if (event.recurrenceRule !== undefined)
|
|
225
|
+
lines.push(`RRULE:${rruleValue(event.recurrenceRule)}`);
|
|
226
|
+
lines.push(...participantLines(event.participants ?? []));
|
|
227
|
+
lines.push('END:VEVENT');
|
|
228
|
+
return lines;
|
|
229
|
+
}
|
|
230
|
+
/** One or more events as a single RFC 5545 `.ics` document (a `VCALENDAR`
|
|
231
|
+
* wrapping one `VEVENT` per event) -- CRLF line endings and folding
|
|
232
|
+
* included, so the string this returns is ready to write to a file or hand
|
|
233
|
+
* to a `Blob` exactly as is. */
|
|
234
|
+
export function eventsToIcs(events, options = {}) {
|
|
235
|
+
const now = options.now ?? new Date();
|
|
236
|
+
const lines = [
|
|
237
|
+
'BEGIN:VCALENDAR',
|
|
238
|
+
'VERSION:2.0',
|
|
239
|
+
'PRODID:-//wtfalch/calendar//EN',
|
|
240
|
+
'CALSCALE:GREGORIAN',
|
|
241
|
+
...events.flatMap((event) => veventLines(event, now)),
|
|
242
|
+
'END:VCALENDAR',
|
|
243
|
+
];
|
|
244
|
+
return `${lines.map(foldLine).join('\r\n')}\r\n`;
|
|
245
|
+
}
|
|
246
|
+
/** A single event's own `.ics` document -- `EventDetail`'s "Download .ics"
|
|
247
|
+
* control (wtfalch/calendar#28) is this, one event at a time. */
|
|
248
|
+
export function eventToIcs(event, options = {}) {
|
|
249
|
+
return eventsToIcs([event], options);
|
|
250
|
+
}
|
|
251
|
+
// ---------------------------------------------------------------------------
|
|
252
|
+
// Import (wtfalch/calendar#41): the inverse of the export above.
|
|
253
|
+
// ---------------------------------------------------------------------------
|
|
254
|
+
/** RFC 5545 §3.3.11's `TEXT` unescaping -- the inverse of `escapeText`. A
|
|
255
|
+
* trailing lone backslash (nothing valid to escape) is passed through
|
|
256
|
+
* as-is rather than dropped. */
|
|
257
|
+
function unescapeText(value) {
|
|
258
|
+
let out = '';
|
|
259
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
260
|
+
const char = value[i];
|
|
261
|
+
const next = value[i + 1];
|
|
262
|
+
if (char === '\\' && (next === 'n' || next === 'N')) {
|
|
263
|
+
out += '\n';
|
|
264
|
+
i += 1;
|
|
265
|
+
}
|
|
266
|
+
else if (char === '\\' && (next === '\\' || next === ';' || next === ',')) {
|
|
267
|
+
out += next;
|
|
268
|
+
i += 1;
|
|
269
|
+
}
|
|
270
|
+
else {
|
|
271
|
+
out += char;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
/** `"20261005T090000Z"` -> `{date: "20261005", time: "090000", utc: true}`,
|
|
277
|
+
* `"20261005"` -> `{date: "20261005", time: undefined, utc: false}`. */
|
|
278
|
+
function splitIcsValue(value) {
|
|
279
|
+
const [date = '', rawTime] = value.split('T');
|
|
280
|
+
if (rawTime === undefined)
|
|
281
|
+
return { date, utc: false };
|
|
282
|
+
const utc = rawTime.endsWith('Z');
|
|
283
|
+
return { date, time: utc ? rawTime.slice(0, -1) : rawTime, utc };
|
|
284
|
+
}
|
|
285
|
+
/** `"20261005"` -> `"2026-10-05"`, the inverse of `basicDate`. */
|
|
286
|
+
function isoDate(basic) {
|
|
287
|
+
return `${basic.slice(0, 4)}-${basic.slice(4, 6)}-${basic.slice(6, 8)}`;
|
|
288
|
+
}
|
|
289
|
+
/** `"090000"` -> `"09:00:00"`, the inverse of the time half of
|
|
290
|
+
* `basicDateTime`. */
|
|
291
|
+
function isoTime(basic) {
|
|
292
|
+
const padded = basic.padEnd(6, '0');
|
|
293
|
+
return `${padded.slice(0, 2)}:${padded.slice(2, 4)}:${padded.slice(4, 6)}`;
|
|
294
|
+
}
|
|
295
|
+
/** A `DTSTART`/`DTEND`/`UNTIL` basic value back to this package's own local
|
|
296
|
+
* date-time shape. `VALUE=DATE` (all-day) reads as local midnight with no
|
|
297
|
+
* zone; otherwise a trailing `Z` reads as `'UTC'` (the naive-UTC convention
|
|
298
|
+
* the file header describes -- every timed value this file's own export
|
|
299
|
+
* ever writes is `Z`-suffixed) and a bare local value carries whatever
|
|
300
|
+
* `TZID` param it came with, or `null` (floating) with none. */
|
|
301
|
+
function parseIcsDateTime(value, params) {
|
|
302
|
+
if (params.VALUE === 'DATE') {
|
|
303
|
+
return { local: `${isoDate(value)}T00:00:00`, timeZone: null, isAllDay: true };
|
|
304
|
+
}
|
|
305
|
+
const { date, time = '', utc } = splitIcsValue(value);
|
|
306
|
+
return {
|
|
307
|
+
local: `${isoDate(date)}T${isoTime(time)}`,
|
|
308
|
+
timeZone: utc ? 'UTC' : (params.TZID ?? null),
|
|
309
|
+
isAllDay: false,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
/** The inverse of `computeEnd`'s naive-UTC arithmetic: two local date-times
|
|
313
|
+
* in this package's own shape, diffed the same way `computeEnd` combines a
|
|
314
|
+
* start with a duration. */
|
|
315
|
+
function durationBetween(startLocal, endLocal) {
|
|
316
|
+
const ms = new Date(`${endLocal}Z`).getTime() - new Date(`${startLocal}Z`).getTime();
|
|
317
|
+
if (ms <= 0)
|
|
318
|
+
return 'PT0S';
|
|
319
|
+
if (ms % DAY_MS === 0)
|
|
320
|
+
return `P${ms / DAY_MS}D`;
|
|
321
|
+
let remainingSeconds = Math.round(ms / 1000);
|
|
322
|
+
const hours = Math.floor(remainingSeconds / 3600);
|
|
323
|
+
remainingSeconds -= hours * 3600;
|
|
324
|
+
const minutes = Math.floor(remainingSeconds / 60);
|
|
325
|
+
remainingSeconds -= minutes * 60;
|
|
326
|
+
let out = 'PT';
|
|
327
|
+
if (hours > 0)
|
|
328
|
+
out += `${hours}H`;
|
|
329
|
+
if (minutes > 0)
|
|
330
|
+
out += `${minutes}M`;
|
|
331
|
+
if (remainingSeconds > 0 || out === 'PT')
|
|
332
|
+
out += `${remainingSeconds}S`;
|
|
333
|
+
return out;
|
|
334
|
+
}
|
|
335
|
+
const ICS_FREQ = {
|
|
336
|
+
DAILY: 'daily',
|
|
337
|
+
WEEKLY: 'weekly',
|
|
338
|
+
MONTHLY: 'monthly',
|
|
339
|
+
YEARLY: 'yearly',
|
|
340
|
+
};
|
|
341
|
+
const ICS_WEEKDAY = Object.fromEntries(Object.entries(WEEKDAY_ICS).map(([day, code]) => [code, day]));
|
|
342
|
+
/** `"2TU"` -> `{day: 'tu', nthOfPeriod: 2}`, `"-1FR"` -> `{day: 'fr',
|
|
343
|
+
* nthOfPeriod: -1}`, `"MO"` -> `{day: 'mo'}` -- the inverse of
|
|
344
|
+
* `ndayToIcs`. */
|
|
345
|
+
function icsToNday(value) {
|
|
346
|
+
const match = /^([+-]?\d+)?([A-Za-z]{2})$/.exec(value);
|
|
347
|
+
const day = match ? ICS_WEEKDAY[(match[2] ?? '').toUpperCase()] : undefined;
|
|
348
|
+
if (!match || day === undefined)
|
|
349
|
+
throw new Error(`unrecognised BYDAY value in .ics: ${value}`);
|
|
350
|
+
const n = match[1];
|
|
351
|
+
return n !== undefined ? { day, nthOfPeriod: Number(n) } : { day };
|
|
352
|
+
}
|
|
353
|
+
/** An `RRULE`'s value back to a `CalendarRecurrenceRule`, part by part -- the
|
|
354
|
+
* inverse of `rruleValue`. `rscale`/`skip` have no RFC 5545 part to read
|
|
355
|
+
* back from (the file header's own note on the export side). */
|
|
356
|
+
function parseRrule(value) {
|
|
357
|
+
const rule = {};
|
|
358
|
+
for (const part of value.split(';')) {
|
|
359
|
+
const eq = part.indexOf('=');
|
|
360
|
+
if (eq === -1)
|
|
361
|
+
continue;
|
|
362
|
+
const name = part.slice(0, eq);
|
|
363
|
+
const raw = part.slice(eq + 1);
|
|
364
|
+
switch (name) {
|
|
365
|
+
case 'FREQ':
|
|
366
|
+
rule.frequency = ICS_FREQ[raw];
|
|
367
|
+
break;
|
|
368
|
+
case 'UNTIL':
|
|
369
|
+
rule.until = parseIcsDateTime(raw, {}).local;
|
|
370
|
+
break;
|
|
371
|
+
case 'COUNT':
|
|
372
|
+
rule.count = Number(raw);
|
|
373
|
+
break;
|
|
374
|
+
case 'INTERVAL':
|
|
375
|
+
rule.interval = Number(raw);
|
|
376
|
+
break;
|
|
377
|
+
case 'BYSECOND':
|
|
378
|
+
rule.bySecond = raw.split(',').map(Number);
|
|
379
|
+
break;
|
|
380
|
+
case 'BYMINUTE':
|
|
381
|
+
rule.byMinute = raw.split(',').map(Number);
|
|
382
|
+
break;
|
|
383
|
+
case 'BYHOUR':
|
|
384
|
+
rule.byHour = raw.split(',').map(Number);
|
|
385
|
+
break;
|
|
386
|
+
case 'BYDAY':
|
|
387
|
+
rule.byDay = raw.split(',').map(icsToNday);
|
|
388
|
+
break;
|
|
389
|
+
case 'BYMONTHDAY':
|
|
390
|
+
rule.byMonthDay = raw.split(',').map(Number);
|
|
391
|
+
break;
|
|
392
|
+
case 'BYYEARDAY':
|
|
393
|
+
rule.byYearDay = raw.split(',').map(Number);
|
|
394
|
+
break;
|
|
395
|
+
case 'BYWEEKNO':
|
|
396
|
+
rule.byWeekNo = raw.split(',').map(Number);
|
|
397
|
+
break;
|
|
398
|
+
case 'BYMONTH':
|
|
399
|
+
rule.byMonth = raw.split(',');
|
|
400
|
+
break;
|
|
401
|
+
case 'BYSETPOS':
|
|
402
|
+
rule.bySetPosition = raw.split(',').map(Number);
|
|
403
|
+
break;
|
|
404
|
+
case 'WKST':
|
|
405
|
+
rule.firstDayOfWeek = ICS_WEEKDAY[raw];
|
|
406
|
+
break;
|
|
407
|
+
default:
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
if (rule.frequency === undefined)
|
|
412
|
+
throw new Error(`RRULE has no recognised FREQ: ${value}`);
|
|
413
|
+
return rule;
|
|
414
|
+
}
|
|
415
|
+
const ICS_ROLE = {
|
|
416
|
+
CHAIR: 'chair',
|
|
417
|
+
'REQ-PARTICIPANT': 'attendee',
|
|
418
|
+
'OPT-PARTICIPANT': 'optional',
|
|
419
|
+
'NON-PARTICIPANT': 'informational',
|
|
420
|
+
};
|
|
421
|
+
const ICS_PARTSTAT = {
|
|
422
|
+
'NEEDS-ACTION': 'needs-action',
|
|
423
|
+
ACCEPTED: 'accepted',
|
|
424
|
+
DECLINED: 'declined',
|
|
425
|
+
TENTATIVE: 'tentative',
|
|
426
|
+
};
|
|
427
|
+
const EVENT_STATUSES = ['confirmed', 'cancelled', 'tentative'];
|
|
428
|
+
/** RFC 5545 §3.1's line unfolding, the inverse of `foldLine`: any line
|
|
429
|
+
* starting with a space or a tab continues the previous one, the leading
|
|
430
|
+
* whitespace itself dropped. Accepts CRLF, bare LF or bare CR between
|
|
431
|
+
* lines, since not every producer of a `.ics` file folds strictly. */
|
|
432
|
+
function unfoldLines(ics) {
|
|
433
|
+
const raw = ics.split(/\r\n|\r|\n/);
|
|
434
|
+
const lines = [];
|
|
435
|
+
for (const line of raw) {
|
|
436
|
+
if ((line.startsWith(' ') || line.startsWith('\t')) && lines.length > 0) {
|
|
437
|
+
lines[lines.length - 1] += line.slice(1);
|
|
438
|
+
}
|
|
439
|
+
else if (line.length > 0) {
|
|
440
|
+
lines.push(line);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return lines;
|
|
444
|
+
}
|
|
445
|
+
/** `"ATTENDEE;ROLE=REQ-PARTICIPANT;CN=Bob:mailto:bob@example.org"` -> `{name:
|
|
446
|
+
* "ATTENDEE", params: {ROLE: "REQ-PARTICIPANT", CN: "Bob"}, value:
|
|
447
|
+
* "mailto:bob@example.org"}`. The colon search skips over a quoted param
|
|
448
|
+
* value, since `paramValue` quotes one that itself contains a colon. */
|
|
449
|
+
function parseIcsLine(line) {
|
|
450
|
+
let end = 0;
|
|
451
|
+
let quoted = false;
|
|
452
|
+
while (end < line.length) {
|
|
453
|
+
const char = line[end];
|
|
454
|
+
if (char === '"')
|
|
455
|
+
quoted = !quoted;
|
|
456
|
+
else if (char === ':' && !quoted)
|
|
457
|
+
break;
|
|
458
|
+
end += 1;
|
|
459
|
+
}
|
|
460
|
+
const [name = '', ...paramParts] = line.slice(0, end).split(';');
|
|
461
|
+
const params = {};
|
|
462
|
+
for (const part of paramParts) {
|
|
463
|
+
const eq = part.indexOf('=');
|
|
464
|
+
if (eq === -1)
|
|
465
|
+
continue;
|
|
466
|
+
const key = part.slice(0, eq).toUpperCase();
|
|
467
|
+
const raw = part.slice(eq + 1);
|
|
468
|
+
params[key] = raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1) : raw;
|
|
469
|
+
}
|
|
470
|
+
return { name: name.toUpperCase(), params, value: line.slice(end + 1) };
|
|
471
|
+
}
|
|
472
|
+
/** `ORGANIZER`/`ATTENDEE` lines back to `CalendarParticipant`s -- the
|
|
473
|
+
* inverse of `participantLines`. The organizer's own `roles` is fixed at
|
|
474
|
+
* `['owner']`, mirroring how `participantLines` never doubles them as an
|
|
475
|
+
* attendee. */
|
|
476
|
+
function parseParticipants(lines) {
|
|
477
|
+
const participants = [];
|
|
478
|
+
for (const line of lines) {
|
|
479
|
+
const name = line.params.CN;
|
|
480
|
+
if (line.name === 'ORGANIZER') {
|
|
481
|
+
participants.push({
|
|
482
|
+
calendarAddress: line.value,
|
|
483
|
+
...(name !== undefined ? { name } : {}),
|
|
484
|
+
roles: ['owner'],
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
else if (line.name === 'ATTENDEE') {
|
|
488
|
+
const role = line.params.ROLE !== undefined ? ICS_ROLE[line.params.ROLE] : undefined;
|
|
489
|
+
const partstat = line.params.PARTSTAT !== undefined ? ICS_PARTSTAT[line.params.PARTSTAT] : undefined;
|
|
490
|
+
participants.push({
|
|
491
|
+
calendarAddress: line.value,
|
|
492
|
+
...(name !== undefined ? { name } : {}),
|
|
493
|
+
roles: [role ?? 'attendee'],
|
|
494
|
+
...(partstat !== undefined ? { participationStatus: partstat } : {}),
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return participants;
|
|
499
|
+
}
|
|
500
|
+
/** One `VEVENT`'s already-unfolded, already-parsed lines back to a
|
|
501
|
+
* `CalendarEventDraft` -- the inverse of `veventLines`. `calendarId` is a
|
|
502
|
+
* placeholder: this function has no calendar to target, only the event
|
|
503
|
+
* data, so its caller (`CalendarClient.importIcs`) fills in the real one
|
|
504
|
+
* before handing the draft to `createEvent`. */
|
|
505
|
+
function veventToDraft(lines) {
|
|
506
|
+
const get = (name) => lines.find((line) => line.name === name);
|
|
507
|
+
const dtstart = get('DTSTART');
|
|
508
|
+
if (!dtstart)
|
|
509
|
+
throw new Error('a VEVENT in this .ics document has no DTSTART');
|
|
510
|
+
const { local: start, timeZone, isAllDay } = parseIcsDateTime(dtstart.value, dtstart.params);
|
|
511
|
+
const dtend = get('DTEND');
|
|
512
|
+
const duration = dtend !== undefined
|
|
513
|
+
? durationBetween(start, parseIcsDateTime(dtend.value, dtend.params).local)
|
|
514
|
+
: 'PT0S';
|
|
515
|
+
const summary = get('SUMMARY');
|
|
516
|
+
const description = get('DESCRIPTION');
|
|
517
|
+
const location = get('LOCATION');
|
|
518
|
+
const status = get('STATUS')?.value.toLowerCase();
|
|
519
|
+
const transp = get('TRANSP');
|
|
520
|
+
const rrule = get('RRULE');
|
|
521
|
+
const participants = parseParticipants(lines.filter((line) => line.name === 'ORGANIZER' || line.name === 'ATTENDEE'));
|
|
522
|
+
return {
|
|
523
|
+
calendarId: '',
|
|
524
|
+
uid: get('UID')?.value ?? crypto.randomUUID(),
|
|
525
|
+
title: summary ? unescapeText(summary.value) : '',
|
|
526
|
+
...(description ? { description: unescapeText(description.value) } : {}),
|
|
527
|
+
start,
|
|
528
|
+
timeZone,
|
|
529
|
+
duration,
|
|
530
|
+
isAllDay,
|
|
531
|
+
...(location ? { location: unescapeText(location.value) } : {}),
|
|
532
|
+
status: EVENT_STATUSES.includes(status ?? '')
|
|
533
|
+
? status
|
|
534
|
+
: 'confirmed',
|
|
535
|
+
...(transp?.value === 'TRANSPARENT' ? { freeBusyStatus: 'free' } : {}),
|
|
536
|
+
...(rrule ? { recurrenceRule: parseRrule(rrule.value) } : {}),
|
|
537
|
+
...(participants.length > 0 ? { participants } : {}),
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* One `CalendarEventDraft` per `VEVENT` in an RFC 5545 `.ics` document --
|
|
542
|
+
* the inverse of `eventsToIcs` (wtfalch/calendar#41). `calendarId` on each
|
|
543
|
+
* draft is a placeholder empty string: this function only ever sees the
|
|
544
|
+
* document, never the calendar it is being imported into, so
|
|
545
|
+
* `CalendarClient.importIcs` (`calendar-client.ts`) overwrites it before
|
|
546
|
+
* calling `createEvent`.
|
|
547
|
+
*
|
|
548
|
+
* A `VEVENT` outside a `BEGIN:VCALENDAR`/`END:VCALENDAR` pair, or with no
|
|
549
|
+
* matching `END:VEVENT`, is silently not collected -- the same tolerance a
|
|
550
|
+
* hand-written or partially-truncated `.ics` file needs, since this is a
|
|
551
|
+
* one-time import rather than a validator.
|
|
552
|
+
*
|
|
553
|
+
* A `VEVENT` that parses structurally but that `veventToDraft` cannot turn
|
|
554
|
+
* into a draft (no `DTSTART`, an `RRULE` `FREQ` this package does not
|
|
555
|
+
* recognise) is caught per event and reported in `skipped` rather than
|
|
556
|
+
* thrown -- one malformed `VEVENT` used to abort the whole document and
|
|
557
|
+
* discard every other, otherwise-valid one in it (wtfalch/calendar#46).
|
|
558
|
+
*/
|
|
559
|
+
export function icsToEventDrafts(ics) {
|
|
560
|
+
const drafts = [];
|
|
561
|
+
const skipped = [];
|
|
562
|
+
let current = null;
|
|
563
|
+
for (const line of unfoldLines(ics).map(parseIcsLine)) {
|
|
564
|
+
if (line.name === 'BEGIN' && line.value === 'VEVENT') {
|
|
565
|
+
current = [];
|
|
566
|
+
}
|
|
567
|
+
else if (line.name === 'END' && line.value === 'VEVENT') {
|
|
568
|
+
if (current) {
|
|
569
|
+
try {
|
|
570
|
+
drafts.push(veventToDraft(current));
|
|
571
|
+
}
|
|
572
|
+
catch (error) {
|
|
573
|
+
skipped.push({
|
|
574
|
+
uid: current.find((eventLine) => eventLine.name === 'UID')?.value,
|
|
575
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
current = null;
|
|
580
|
+
}
|
|
581
|
+
else if (current) {
|
|
582
|
+
current.push(line);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return { drafts, skipped };
|
|
586
|
+
}
|
package/dist/calendar/index.d.ts
CHANGED
|
@@ -8,5 +8,7 @@
|
|
|
8
8
|
* acceptance criteria). The JMAP wire stays behind the client.
|
|
9
9
|
*/
|
|
10
10
|
export { createCalendarClient } from './calendar-client.ts';
|
|
11
|
+
export { eventToIcs, eventsToIcs } from './ics.ts';
|
|
12
|
+
export type { IcsExportOptions } from './ics.ts';
|
|
11
13
|
export { CalendarError } from './types.ts';
|
|
12
|
-
export type { AvailabilityInclusion, AvailabilityPeriod, Calendar, CalendarBusyStatus, CalendarChangedState, CalendarClient, CalendarClientOptions, CalendarEvent, CalendarEventDraft, CalendarEventStatus, CalendarParticipant, CalendarParticipantRole, CalendarParticipationStatus, CalendarRange, CalendarRecurrenceRule, CalendarRight, CalendarSubscription, Principal, SchedulingOptions, ShareGrant, } from './types.ts';
|
|
14
|
+
export type { AvailabilityInclusion, AvailabilityPeriod, AvailabilityResult, Calendar, CalendarAlert, CalendarAlertAction, CalendarAlertRelativeTo, CalendarBusyStatus, CalendarChangedState, CalendarChanges, CalendarChangesOptions, CalendarClient, CalendarClientOptions, CalendarEvent, CalendarEventDraft, CalendarEventPatch, CalendarEventProjection, CalendarEventProjectionsResult, CalendarEventStatus, CalendarFreeBusyStatus, CalendarLink, CalendarNDay, CalendarParticipant, CalendarParticipantRole, CalendarParticipationStatus, CalendarRange, CalendarRecurrenceRule, CalendarRight, CalendarSubscription, CalendarVirtualLocation, CalendarWeekday, FindTimeResult, ImportIcsResult, ImportIcsSkippedEvent, Principal, RecurrenceScope, RecurrenceScopeOptions, SchedulingOptions, SearchOptions, ShareGrant, WorkingHours, } from './types.ts';
|
package/dist/calendar/index.js
CHANGED