@wtfalch/calendar 0.2.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.
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * Export a `CalendarEvent` (or several) as an RFC 5545 `.ics` document
3
- * (wtfalch/calendar#28). Read-only feeds and `.ics` import are the other
4
- * half of this gap, tracked separately (agora#159,
5
- * https://github.com/wtfalch/agora/issues/159) and deferred with a named
6
- * home (`PRODUCT.md`); this file is export only.
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).
7
10
  *
8
11
  * **Every date-time is written in UTC (`Z`-suffixed), naively.** `start` is
9
12
  * a local date-time with no offset, and `timeZone` says which zone it is
@@ -245,3 +248,339 @@ export function eventsToIcs(events, options = {}) {
245
248
  export function eventToIcs(event, options = {}) {
246
249
  return eventsToIcs([event], options);
247
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
+ }
@@ -11,4 +11,4 @@ export { createCalendarClient } from './calendar-client.ts';
11
11
  export { eventToIcs, eventsToIcs } from './ics.ts';
12
12
  export type { IcsExportOptions } from './ics.ts';
13
13
  export { CalendarError } from './types.ts';
14
- export type { AvailabilityInclusion, AvailabilityPeriod, AvailabilityResult, Calendar, CalendarAlert, CalendarAlertAction, CalendarAlertRelativeTo, CalendarBusyStatus, CalendarChangedState, CalendarClient, CalendarClientOptions, CalendarEvent, CalendarEventDraft, CalendarEventStatus, CalendarFreeBusyStatus, CalendarLink, CalendarNDay, CalendarParticipant, CalendarParticipantRole, CalendarParticipationStatus, CalendarRange, CalendarRecurrenceRule, CalendarRight, CalendarSubscription, CalendarVirtualLocation, CalendarWeekday, FindTimeResult, Principal, RecurrenceScope, RecurrenceScopeOptions, SchedulingOptions, SearchOptions, ShareGrant, WorkingHours, } 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';
@@ -29,17 +29,30 @@ export type CalendarClientOptions = {
29
29
  * assembles. Mirrors `MailClientOptions.sessionUrl` (plan §7; #143 §2). */
30
30
  sessionUrl: string;
31
31
  /**
32
- * A callback returning the current ZITADEL token, mirroring
33
- * `createChatClient`'s `getAccessToken` rather than `MailClientOptions`'s
34
- * static `bearerToken` — every first-ship feature is a live
35
- * browser-to-Stalwart call (plan §7; #143 §2), and only a callback
36
- * survives a mid-session token refresh with no host-app code.
32
+ * A callback returning the current token, mirroring `createChatClient`'s
33
+ * `getAccessToken` rather than `MailClientOptions`'s static `bearerToken`
34
+ * — every first-ship feature is a live browser-to-Stalwart call (plan §7;
35
+ * #143 §2), and only a callback survives a mid-session token refresh with
36
+ * no host-app code.
37
+ *
38
+ * **This is also how a host constructs a client against a service
39
+ * credential for someone else's account** (wtfalch/calendar#65,
40
+ * https://github.com/wtfalch/activity's own `jmap.ts` and its per-account
41
+ * Stalwart credential map, issue #34 decision 1): the callback needs no
42
+ * refresh logic to be valid here, a plain `() => credential` closing over
43
+ * one held string is enough, paired with `accountId` below naming whose
44
+ * account it reads. This package holds no credential of its own — the
45
+ * caller's is a browser access token, a service credential, or anything
46
+ * else that answers the session's bearer check — and never caches one
47
+ * past a single call (`CalendarConnection`'s own doc comment).
37
48
  */
38
49
  getAccessToken: () => string | Promise<string>;
39
50
  /** Override the session's primary account. Needed because a JMAP session
40
51
  * can carry more than one account; the client must pick the one with the
41
52
  * `calendars` capability (plan §7; #143 §2, mirroring
42
- * `MailClientOptions.accountId`). */
53
+ * `MailClientOptions.accountId`). Also what points a service-credential
54
+ * connection at another person's account rather than the credential's
55
+ * own, when one is held at all (wtfalch/calendar#65). */
43
56
  accountId?: string;
44
57
  };
45
58
  /** One JMAP ACL right a calendar's `shareWith` grant can carry (#138 §1,
@@ -338,6 +351,14 @@ export type CalendarEvent = {
338
351
  links?: readonly CalendarLink[];
339
352
  recurrenceRule?: CalendarRecurrenceRule;
340
353
  participants?: readonly CalendarParticipant[];
354
+ /** JSCalendar `mayInviteSelf` (draft-ietf-jmap-calendars §5.1.1): whether a
355
+ * participant may add themselves to the event. Off by default -- the
356
+ * owner's 2026-09-27 decision (wtfalch/calendar#51). */
357
+ mayInviteSelf?: boolean;
358
+ /** JSCalendar `mayInviteOthers` (draft-ietf-jmap-calendars §5.1.2): the
359
+ * "Guests can invite others" setting -- whether a participant may add
360
+ * further participants. Off by default (wtfalch/calendar#51). */
361
+ mayInviteOthers?: boolean;
341
362
  /** Reminders on this event -- a JSCalendar `alerts` map, flattened to a
342
363
  * list the way `participants` already is (`wire.ts`'s `alertsToWire`
343
364
  * assigns the wire's arbitrary map keys, mirroring `participantsToWire`).
@@ -371,6 +392,20 @@ export type CalendarEvent = {
371
392
  * server-assigned on create (`id`, `sequence`) or query-assigned
372
393
  * (`recurrenceId`). */
373
394
  export type CalendarEventDraft = Omit<CalendarEvent, 'id' | 'sequence' | 'recurrenceId'>;
395
+ /**
396
+ * `updateEvent`'s patch. Every field omits its key entirely to mean "leave
397
+ * this alone" -- the usual `Partial<CalendarEventDraft>` meaning -- with one
398
+ * exception: `recurrenceRule` also accepts an explicit `null`, which removes
399
+ * an existing rule server-side and turns a recurring event back into a
400
+ * one-off. Nothing built that clearing before this type existed
401
+ * (wtfalch/calendar#45) -- `recurrenceRule`'s own field on `CalendarEvent`
402
+ * only ever reads back as the rule or `undefined`, never `null`, so a plain
403
+ * `Partial<CalendarEventDraft>` had no way to say "unset" rather than "not
404
+ * mentioned".
405
+ */
406
+ export type CalendarEventPatch = Omit<Partial<CalendarEventDraft>, 'recurrenceRule'> & {
407
+ recurrenceRule?: CalendarRecurrenceRule | null;
408
+ };
374
409
  /** RFC 5545 `FREEBUSY` `FBTYPE`, as JSCalendar's busy-period shape names
375
410
  * it. */
376
411
  export type CalendarBusyStatus = 'confirmed' | 'tentative' | 'unavailable';
@@ -418,6 +453,28 @@ export type FindTimeResult = {
418
453
  readonly slots: readonly CalendarRange[];
419
454
  readonly unknown: readonly string[];
420
455
  };
456
+ /**
457
+ * One `VEVENT` `importIcs` could not turn into an event -- kept apart from
458
+ * the ones it created rather than discarding the whole import over it
459
+ * (wtfalch/calendar#46: one malformed `VEVENT` used to abort the import and
460
+ * lose every otherwise-valid one alongside it).
461
+ */
462
+ export type ImportIcsSkippedEvent = {
463
+ /** The failed `VEVENT`'s own `UID`, when it had one to read before parsing
464
+ * gave up -- e.g. a missing `DTSTART` is caught before `UID` is even
465
+ * read. */
466
+ readonly uid: string | undefined;
467
+ /** Why this one could not become an event, e.g. an `RRULE` `FREQ` this
468
+ * package does not recognise. */
469
+ readonly reason: string;
470
+ };
471
+ /** `importIcs`'s answer: the events it created, and the ones it had to skip
472
+ * and why. Mirrors `FindTimeResult`'s shape -- the answer travels alongside
473
+ * the partial failure rather than either one hiding the other. */
474
+ export type ImportIcsResult = {
475
+ readonly created: readonly CalendarEvent[];
476
+ readonly skipped: readonly ImportIcsSkippedEvent[];
477
+ };
421
478
  /**
422
479
  * One principal's own working day, for `findTime`'s per-attendee
423
480
  * `options.workingHours` (wtfalch/calendar#31). `timeZone` is an IANA name
@@ -519,6 +576,64 @@ export type SearchOptions = {
519
576
  range?: CalendarRange;
520
577
  limit?: number;
521
578
  };
579
+ /**
580
+ * `changes()`'s own input (wtfalch/calendar#65): `sinceState` is a state
581
+ * string a previous `changes()` call's own `newState` handed back — there is
582
+ * no way to ask "what changed since the beginning," the same rule
583
+ * `Calendar/get`'s or `CalendarEvent/get`'s `state` and `CalendarEvent/changes`'s
584
+ * `sinceState` already share in RFC 8620 §5.2. `calendarId`, when given, scopes
585
+ * `created`/`updated` to that one calendar — `changes()`'s own doc comment
586
+ * explains why `destroyed` cannot be scoped the same way.
587
+ */
588
+ export type CalendarChangesOptions = {
589
+ calendarId?: string;
590
+ sinceState: string;
591
+ };
592
+ /**
593
+ * `changes()`'s answer: which `CalendarEvent` ids were created, updated or
594
+ * destroyed since `sinceState`, and the state to remember for next time
595
+ * (RFC 8620 §5.2). Ids only — never event data — so a caller that only needs
596
+ * to know *what* moved is never handed a title or body it has no use for;
597
+ * `getEventProjections` is the separate, minimal fetch for a caller that does
598
+ * need to look at what changed.
599
+ */
600
+ export type CalendarChanges = {
601
+ readonly newState: string;
602
+ readonly created: readonly string[];
603
+ readonly updated: readonly string[];
604
+ readonly destroyed: readonly string[];
605
+ /** More changes exist past `newState` than this one call returned — call
606
+ * `changes()` again with `newState` as the next `sinceState` before
607
+ * treating the sync as caught up (RFC 8620 §5.2). */
608
+ readonly hasMoreChanges: boolean;
609
+ };
610
+ /**
611
+ * The minimal slice of a `CalendarEvent` a change-feed consumer needs to
612
+ * decide what happened, and nothing it must not hold (wtfalch/calendar#65,
613
+ * modelled on Activity's own `JmapCalendarEventRecord`,
614
+ * `activity/packages/service/src/calendar/jmap.ts`): no title, description,
615
+ * location or start time. `getEventProjections` fetches exactly this shape,
616
+ * naming every property it wants rather than asking the server for
617
+ * "everything," so a title or body is never sent over the wire in the first
618
+ * place.
619
+ */
620
+ export type CalendarEventProjection = {
621
+ readonly id: string;
622
+ readonly status: CalendarEventStatus;
623
+ /** RFC 5545 `SEQUENCE`; bumped on every organizer edit. */
624
+ readonly sequence: number;
625
+ readonly participants: readonly {
626
+ readonly calendarAddress: string;
627
+ }[];
628
+ };
629
+ /** `getEventProjections`'s answer: the projections it found, and the ids it
630
+ * did not — an id a caller's own index still holds but the server no
631
+ * longer does, the same `notFound` shape `CalendarEvent/get` always
632
+ * carries. */
633
+ export type CalendarEventProjectionsResult = {
634
+ readonly list: readonly CalendarEventProjection[];
635
+ readonly notFound: readonly string[];
636
+ };
522
637
  /**
523
638
  * A connection to one JMAP calendars account.
524
639
  *
@@ -566,6 +681,24 @@ export interface CalendarClient {
566
681
  searchEvents(query: string, options?: SearchOptions): Promise<readonly CalendarEvent[]>;
567
682
  getEvent(id: string): Promise<CalendarEvent>;
568
683
  createEvent(calendarId: string, event: CalendarEventDraft, options?: SchedulingOptions): Promise<CalendarEvent>;
684
+ /**
685
+ * Parse an RFC 5545 `.ics` document and create one event per `VEVENT` it
686
+ * contains, on `calendarId` (wtfalch/calendar#41; agora#159,
687
+ * https://github.com/wtfalch/agora/issues/159). One-way: the source the
688
+ * `.ics` came from is never written back to, and this is a distinct method
689
+ * from `subscribe`'s standing webcal poller -- a one-time copy onto an
690
+ * owned calendar, not a live link to the original. Each created event
691
+ * rides the same `CalendarEvent/set` `createEvent` already uses, under the
692
+ * importing person's own credential, so it is editable afterward like any
693
+ * other owned event.
694
+ *
695
+ * A `VEVENT` this package cannot turn into an event -- an unrecognised
696
+ * `RRULE`, a missing `DTSTART` -- is skipped rather than aborting the whole
697
+ * import: every otherwise-valid `VEVENT` in the same document still gets
698
+ * created, and `ImportIcsResult.skipped` says which ones did not and why
699
+ * (wtfalch/calendar#46).
700
+ */
701
+ importIcs(calendarId: string, ics: string): Promise<ImportIcsResult>;
569
702
  /**
570
703
  * `options.scope` picks which occurrences of a recurring event this
571
704
  * reaches -- see `RecurrenceScope`. `'following'` returns the new series'
@@ -581,8 +714,14 @@ export interface CalendarClient {
581
714
  * own id on the next expansion. An id held across two writes can silently
582
715
  * name a different occurrence on the second one. Re-list (`listEvents`)
583
716
  * before reusing an id this method, or `deleteEvent`, has just touched.
717
+ *
718
+ * `patch.recurrenceRule: null` clears an existing rule server-side,
719
+ * turning a recurring event back into a one-off -- distinct from
720
+ * omitting `recurrenceRule` entirely, which leaves whatever rule the
721
+ * event already has untouched (`CalendarEventPatch`'s own doc comment,
722
+ * wtfalch/calendar#45).
584
723
  */
585
- updateEvent(id: string, patch: Partial<CalendarEventDraft>, options?: SchedulingOptions & RecurrenceScopeOptions): Promise<CalendarEvent>;
724
+ updateEvent(id: string, patch: CalendarEventPatch, options?: SchedulingOptions & RecurrenceScopeOptions): Promise<CalendarEvent>;
586
725
  /** `options.scope` picks which occurrences of a recurring event this
587
726
  * reaches -- see `RecurrenceScope`. `'following'` deletes nothing on its
588
727
  * own id; it only truncates the series before it (`RecurrenceScope`'s own
@@ -664,6 +803,50 @@ export interface CalendarClient {
664
803
  * with a backoff; only `close()` needs calling when done, mirroring
665
804
  * `@wtfalch/email/mailbox/push.ts`'s `push()`. */
666
805
  subscribe(handler: (changed: CalendarChangedState) => void): CalendarSubscription;
806
+ /**
807
+ * `CalendarEvent` ids created, updated or destroyed since `options.sinceState`
808
+ * — JMAP `CalendarEvent/changes` (RFC 8620 §5.2), for a consumer that
809
+ * follows a calendar without holding a live browser session (Agora's Today
810
+ * digest, a push-notification worker, or Activity's own feed source;
811
+ * wtfalch/calendar#65). Bounded, like every JMAP `/changes` method: a call
812
+ * with a lot to report may come back with `hasMoreChanges: true` and a
813
+ * `newState` short of "caught up" — call again with that state before
814
+ * assuming the sync finished.
815
+ *
816
+ * **`options.calendarId`, when given, scopes `created`/`updated`** to
817
+ * events on that one calendar — `CalendarEvent/changes` itself carries no
818
+ * such filter (RFC 8620 §5.2 defines no arguments beyond `sinceState`/
819
+ * `maxChanges`), so this is done by checking each changed id's own
820
+ * `calendarIds` after the fact, one extra minimal fetch. **`destroyed` is
821
+ * never scoped this way**, deliberately: a destroyed event carries no data
822
+ * to check membership against any more, so filtering it would mean
823
+ * silently dropping an id a `calendarId`-scoped caller's own index still
824
+ * has to retire. A caller that asked for one calendar gets every destroyed
825
+ * id regardless, and is expected to only act on the ones its own index
826
+ * already knows belonged there.
827
+ *
828
+ * **Throws a `CalendarError` with `type: 'cannotCalculateChanges'`** when
829
+ * the server cannot resolve `sinceState` at all — stale, unknown, or
830
+ * foreign to this account (RFC 8620 §5.2's own error for a `/changes`
831
+ * call). That is the caller's signal to resync: `sinceState` is gone for
832
+ * good, so `getEventProjections` (or a bounded `listEvents`/`searchEvents`
833
+ * query) is the only way forward, exactly the resync Activity's own
834
+ * `sync.ts` drives off `JmapCalendarError`'s `cannotCalculateChanges`
835
+ * (`activity/packages/service/src/calendar/sync.ts`).
836
+ */
837
+ changes(options: CalendarChangesOptions): Promise<CalendarChanges>;
838
+ /**
839
+ * The minimal `CalendarEventProjection` for each of `ids` — `id`, `status`,
840
+ * `sequence` and each participant's `calendarAddress`, nothing else
841
+ * (wtfalch/calendar#65). Sent as an explicit `properties` list on
842
+ * `CalendarEvent/get`, the same discipline `EVENT_GET_PROPERTIES` already
843
+ * follows for `getEvent`/`listEvents` — naming exactly what is wanted,
844
+ * rather than filtering a full `CalendarEvent` client-side after asking the
845
+ * server for everything, so a title, description or location is never sent
846
+ * over the wire to a caller (a feed source holding identifiers only, per
847
+ * Activity's own `jmap.ts` doc comment) that must not receive one.
848
+ */
849
+ getEventProjections(ids: readonly string[]): Promise<CalendarEventProjectionsResult>;
667
850
  }
668
851
  /**
669
852
  * Where the reader is: which view, which date, which event is open.