@wtfalch/calendar 0.2.0 → 0.3.1

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 CHANGED
@@ -5,6 +5,10 @@ It reads and writes a person's own events, invites, sharing between colleagues a
5
5
  It exports `./calendar` (`createCalendarClient`), `./calendar/react` (the `Calendar` component), `./calendar/fake` (`fakeCalendar()`) and `./calendar/calendar.css`, mirroring `@wtfalch/email` and `@wtfalch/messaging`.
6
6
  See the [calendar plan](https://github.com/wtfalch/messaging/blob/main/.plans/2026-09-17-calendar.md) for the design and [wtfalch/messaging#156](https://github.com/wtfalch/messaging/issues/156) for this package's own ticket.
7
7
 
8
+ ## Status
9
+
10
+ Published: yes, v0.2.0, 2026-09-22
11
+
8
12
  ## Development
9
13
 
10
14
  ```bash
@@ -6,9 +6,10 @@
6
6
  import { CalendarConnection } from "./client.js";
7
7
  import { guard } from "./errors.js";
8
8
  import { findFreeSlots } from "./find-time.js";
9
+ import { icsToEventDrafts } from "./ics.js";
9
10
  import { push } from "./push.js";
10
11
  import { CalendarError } from "./types.js";
11
- import { CALENDAR_GET_PROPERTIES, EVENT_GET_PROPERTIES, availabilityFromWire, calendarFromWire, draftToWire, eventFromWire, patchToWire, principalFromWire, recurrenceRuleFromWire, rightsToWire, } from "./wire.js";
12
+ import { CALENDAR_GET_PROPERTIES, EVENT_GET_PROPERTIES, EVENT_PROJECTION_PROPERTIES, availabilityFromWire, calendarFromWire, changesFromWire, draftToWire, eventFromWire, eventProjectionFromWire, patchToWire, principalFromWire, recurrenceRuleFromWire, rightsToWire, } from "./wire.js";
12
13
  /** The first refusal in a `notCreated`/`notUpdated`/`notDestroyed` map, or
13
14
  * `undefined` when the operation actually succeeded. */
14
15
  function firstRefusal(errors) {
@@ -104,6 +105,66 @@ async function getEvent(connection, id) {
104
105
  return eventFromWire(wire);
105
106
  });
106
107
  }
108
+ /**
109
+ * `CalendarEvent` ids created, updated or destroyed since `options.sinceState`
110
+ * -- `CalendarEvent/changes` (RFC 8620 §5.2). `options.calendarId`, when
111
+ * given, filters `created`/`updated` down to events on that one calendar --
112
+ * `CalendarEvent/changes` itself carries no such argument, so this costs one
113
+ * extra minimal `CalendarEvent/get` (`id`, `calendarIds` only) over whatever
114
+ * ids the wire call returned. `destroyed` is never filtered this way: a
115
+ * destroyed event has no `calendarIds` left to check, so every destroyed id
116
+ * comes back regardless of `calendarId` -- see `types.ts`'s own doc comment
117
+ * on `CalendarClient.changes`.
118
+ *
119
+ * A server that cannot resolve `sinceState` answers a method-level
120
+ * `cannotCalculateChanges` error, which `guard`/`toCalendarError` already
121
+ * turn into an ordinary `CalendarError` with that `type` -- no special
122
+ * handling needed here, only the doc comment telling a caller what to do
123
+ * with it.
124
+ */
125
+ async function changes(connection, options) {
126
+ return guard('events.changes', async () => {
127
+ const accountId = await connection.accountId();
128
+ const result = await connection.request('CalendarEvent/changes', { accountId, sinceState: options.sinceState });
129
+ const parsed = changesFromWire(result);
130
+ const calendarId = options.calendarId;
131
+ if (!calendarId)
132
+ return parsed;
133
+ const scopedIds = [...parsed.created, ...parsed.updated];
134
+ if (scopedIds.length === 0)
135
+ return parsed;
136
+ const membership = await connection.request('CalendarEvent/get', { accountId, ids: scopedIds, properties: ['id', 'calendarIds'] });
137
+ const onCalendar = new Set(membership.list.filter((event) => event.calendarIds?.[calendarId]).map((event) => event.id));
138
+ return {
139
+ ...parsed,
140
+ created: parsed.created.filter((id) => onCalendar.has(id)),
141
+ updated: parsed.updated.filter((id) => onCalendar.has(id)),
142
+ };
143
+ });
144
+ }
145
+ /**
146
+ * The minimal `CalendarEventProjection` for each of `ids` -- `id`, `status`,
147
+ * `sequence` and each participant's `calendarAddress`, sent as an explicit
148
+ * `properties` list so a title, description or location is never part of
149
+ * the response (`EVENT_PROJECTION_PROPERTIES`'s own doc comment;
150
+ * wtfalch/calendar#65).
151
+ */
152
+ async function getEventProjections(connection, ids) {
153
+ return guard('events.getProjections', async () => {
154
+ if (ids.length === 0)
155
+ return { list: [], notFound: [] };
156
+ const accountId = await connection.accountId();
157
+ const result = await connection.request('CalendarEvent/get', {
158
+ accountId,
159
+ ids: [...ids],
160
+ properties: EVENT_PROJECTION_PROPERTIES,
161
+ });
162
+ return {
163
+ list: result.list.map(eventProjectionFromWire),
164
+ notFound: result.notFound ?? [],
165
+ };
166
+ });
167
+ }
107
168
  async function createEvent(connection, calendarId, event, options) {
108
169
  return guard('events.create', async () => {
109
170
  const accountId = await connection.accountId();
@@ -131,19 +192,40 @@ async function createEvent(connection, calendarId, event, options) {
131
192
  return getEvent(connection, created.id);
132
193
  });
133
194
  }
195
+ /** `importIcs`: parse with `icsToEventDrafts` and `createEvent` once per
196
+ * draft, onto `calendarId` -- sequentially, so one refused event does not
197
+ * leave the rest half-created in an order nobody can predict. A `VEVENT`
198
+ * `icsToEventDrafts` could not parse is already excluded from `drafts` by
199
+ * then; its own `skipped` entries ride straight through onto the result
200
+ * (wtfalch/calendar#46). */
201
+ async function importIcs(connection, calendarId, ics) {
202
+ return guard('events.import', async () => {
203
+ const { drafts, skipped } = icsToEventDrafts(ics);
204
+ const created = [];
205
+ for (const draft of drafts) {
206
+ created.push(await createEvent(connection, calendarId, { ...draft, calendarId }, undefined));
207
+ }
208
+ return { created, skipped };
209
+ });
210
+ }
134
211
  /**
135
212
  * `updateEvent`'s original body, unscoped: the patch lands on whatever `id`
136
213
  * was given. This is also what `scope: 'occurrence'` means (a synthetic
137
214
  * occurrence id already writes an occurrence-scoped override,
138
215
  * `wire.ts`'s `WireEvent.recurrenceOverrides` doc comment) and what an
139
216
  * omitted `scope` means, unchanged from before wtfalch/calendar#14.
217
+ *
218
+ * `extraWire` rides along in the same `CalendarEvent/set update` object as
219
+ * `patchToWire(patch)` -- `updateSeries`' own `recurrenceOverrides` re-key
220
+ * (wtfalch/calendar#43), sent in the one write that moves the master's
221
+ * `start`, rather than a second round trip that could land only half done.
140
222
  */
141
- async function updateEventDirect(connection, id, patch, options) {
223
+ async function updateEventDirect(connection, id, patch, options, extraWire) {
142
224
  return guard('events.update', async () => {
143
225
  const accountId = await connection.accountId();
144
226
  const result = await connection.request('CalendarEvent/set', {
145
227
  accountId,
146
- update: { [id]: patchToWire(patch) },
228
+ update: { [id]: { ...patchToWire(patch), ...extraWire } },
147
229
  sendSchedulingMessages: options?.sendSchedulingMessages ?? false,
148
230
  });
149
231
  const refused = firstRefusal(result.notUpdated);
@@ -319,15 +401,65 @@ function requireOccurrence(event, operation) {
319
401
  }
320
402
  return event.recurrenceId;
321
403
  }
404
+ /**
405
+ * `recurrenceOverrides` is keyed by an occurrence's own `recurrenceId` -- its
406
+ * originally-computed start, in the master's zone (JSCalendar, RFC 8984
407
+ * section 4.3.5) -- and moving the master's `start` moves every computed
408
+ * instant without moving those keys, stranding each override on a start that
409
+ * no longer matches anything (wtfalch/calendar#43). This re-keys every entry
410
+ * by the same shift the `start` patch applies to the master itself, as one
411
+ * JSON-Pointer delete-and-recreate pair per override: an override's own
412
+ * fields -- including an explicit `start` it set for itself -- are carried
413
+ * over unchanged, only the *key* moves.
414
+ *
415
+ * Both `oldMasterStart` and `newMasterStart` are local date-times with no
416
+ * offset (`types.ts`'s `CalendarEvent.start` doc comment), the same shape
417
+ * every override key already is -- so shifting by their difference, treated
418
+ * as a plain instant, moves a key by exactly the same wall-clock amount the
419
+ * master itself just moved by, with no timezone library needed for it.
420
+ */
421
+ function rekeyRecurrenceOverrides(oldMasterStart, newMasterStart, overrides) {
422
+ const wire = {};
423
+ if (!overrides)
424
+ return wire;
425
+ const shiftMs = new Date(`${newMasterStart}Z`).getTime() - new Date(`${oldMasterStart}Z`).getTime();
426
+ if (shiftMs === 0)
427
+ return wire;
428
+ for (const [key, override] of Object.entries(overrides)) {
429
+ const newKey = new Date(new Date(`${key}Z`).getTime() + shiftMs).toISOString().slice(0, 19);
430
+ if (newKey === key)
431
+ continue;
432
+ wire[`recurrenceOverrides/${key}`] = null;
433
+ wire[`recurrenceOverrides/${newKey}`] = override;
434
+ }
435
+ return wire;
436
+ }
322
437
  /** 'series': resolve `id` (an occurrence or already the master) to the
323
- * master, then patch that -- `updateEventDirect` already does exactly this
324
- * once given the right id, so there is no separate wire call to write
325
- * here. */
438
+ * master, then patch that. A `start` patch that actually moves the master
439
+ * also re-keys its `recurrenceOverrides` in the same write
440
+ * (`rekeyRecurrenceOverrides`, wtfalch/calendar#43) -- everything else
441
+ * `updateEventDirect` already does exactly right once given the master id,
442
+ * so there is no separate wire call to write for it.
443
+ *
444
+ * The master's own current `start` is read off a fresh raw fetch
445
+ * (`getRawEvent`), never off `event.start` above: `id` may already be an
446
+ * occurrence's own synthetic id, whose `start` is that occurrence's --
447
+ * possibly overridden -- own, not the master's, and re-keying against the
448
+ * wrong reference point would shift every override by the wrong amount. */
326
449
  async function updateSeries(connection, id, patch, options) {
327
450
  return guard('events.update', async () => {
328
451
  const event = await getEvent(connection, id);
329
452
  const masterId = event.baseEventId ?? id;
330
- return updateEventDirect(connection, masterId, patch, options);
453
+ if (patch.start === undefined) {
454
+ return updateEventDirect(connection, masterId, patch, options);
455
+ }
456
+ const accountId = await connection.accountId();
457
+ const masterWire = await getRawEvent(connection, accountId, masterId, 'events.update');
458
+ if (patch.start === masterWire.start) {
459
+ return updateEventDirect(connection, masterId, patch, options);
460
+ }
461
+ const rekeyed = rekeyRecurrenceOverrides(masterWire.start, patch.start, masterWire.recurrenceOverrides);
462
+ return updateEventDirect(connection, masterId, patch, options, rekeyed);
331
463
  });
332
464
  }
333
465
  async function deleteSeries(connection, id, options) {
@@ -392,12 +524,26 @@ async function updateFollowing(connection, id, patch, options) {
392
524
  }
393
525
  forwardRule = { ...forwardRule, count: remaining };
394
526
  }
527
+ // `patch.recurrenceRule: null` (wtfalch/calendar#45) has no meaning
528
+ // here: 'following' always produces a new recurring series, so there is
529
+ // no rule-less event for it to clear one on. Pulled out of `patch`
530
+ // before the spread below, rather than checked on `patch.recurrenceRule`
531
+ // directly there, because TypeScript does not narrow a property's type
532
+ // through an object spread -- only a direct access of it. An object
533
+ // still overrides `forwardRule` as it always has, letting a caller
534
+ // change the rule going forward in the same write that splits the
535
+ // series; `undefined` (the key omitted, same as before this ticket)
536
+ // keeps `forwardRule`.
537
+ const { recurrenceRule: patchedRule, ...restPatch } = patch;
538
+ if (patchedRule === null) {
539
+ throw new CalendarError("scope 'following' cannot clear a recurrence rule -- it always creates a new recurring series; clear the whole series' rule instead", { type: 'invalidArguments', operation: 'events.update' });
540
+ }
395
541
  const { id: _id, recurrenceId: _recurrenceId, baseEventId: _baseEventId, sequence: _sequence, ...occurrenceFields } = occurrence;
396
542
  const forwardDraft = {
397
543
  ...occurrenceFields,
398
544
  uid: crypto.randomUUID(),
399
- recurrenceRule: forwardRule,
400
- ...patch,
545
+ ...restPatch,
546
+ recurrenceRule: patchedRule ?? forwardRule,
401
547
  };
402
548
  const forwardCalendarId = patch.calendarId ?? occurrence.calendarId;
403
549
  return createEvent(connection, forwardCalendarId, forwardDraft, options);
@@ -634,6 +780,7 @@ export function createCalendarClient(options) {
634
780
  searchEvents: (query, options) => searchEvents(connection, query, options),
635
781
  getEvent: (id) => getEvent(connection, id),
636
782
  createEvent: (calendarId, event, options) => createEvent(connection, calendarId, event, options),
783
+ importIcs: (calendarId, ics) => importIcs(connection, calendarId, ics),
637
784
  updateEvent: (id, patch, options) => updateEvent(connection, id, patch, options),
638
785
  deleteEvent: (id, options) => deleteEvent(connection, id, options),
639
786
  respond: (eventId, status, options) => respond(connection, eventId, status, options),
@@ -644,5 +791,7 @@ export function createCalendarClient(options) {
644
791
  getAvailability: (principalIds, range) => getAvailability(connection, principalIds, range),
645
792
  findTime: (principalIds, range, duration, findOptions) => findTime(connection, principalIds, range, duration, findOptions),
646
793
  subscribe: (handler) => push(connection, handler),
794
+ changes: (changesOptions) => changes(connection, changesOptions),
795
+ getEventProjections: (ids) => getEventProjections(connection, ids),
647
796
  };
648
797
  }
@@ -32,6 +32,30 @@ export const CORE_CAPABILITY = 'urn:ietf:params:jmap:core';
32
32
  * ambient browser credentials keeps a refused token from popping the
33
33
  * browser's native Basic-auth prompt over the application's own error. */
34
34
  const NO_BROWSER_CREDENTIALS = { credentials: 'omit' };
35
+ /** Put an absolute URL from the session document onto `origin`, keeping its
36
+ * path, query and `{template}` parts byte for byte. A relative URL, or one
37
+ * already on `origin`, is returned as it came. */
38
+ function onOrigin(url, origin) {
39
+ const authority = /^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(url)?.[0];
40
+ return authority && authority !== origin ? origin + url.slice(authority.length) : url;
41
+ }
42
+ /** A server behind a proxy writes its own host into the session document.
43
+ * A browser that follows those URLs leaves the origin it fetched the session
44
+ * from, so every URL is moved back onto that origin. */
45
+ function keepOnOrigin(doc, sessionUrl) {
46
+ let origin;
47
+ try {
48
+ origin = new URL(sessionUrl).origin;
49
+ }
50
+ catch {
51
+ return doc;
52
+ }
53
+ return {
54
+ ...doc,
55
+ apiUrl: onOrigin(doc.apiUrl, origin),
56
+ eventSourceUrl: onOrigin(doc.eventSourceUrl, origin),
57
+ };
58
+ }
35
59
  function looksLikeSession(value) {
36
60
  return (typeof value === 'object' &&
37
61
  value !== null &&
@@ -116,7 +140,7 @@ export class CalendarConnection {
116
140
  if (!looksLikeSession(parsed)) {
117
141
  throw new CalendarError(`${this.#sessionUrl} did not answer with a JMAP session document (${response.status}): ${body.slice(0, 200)}`, { status: response.status, operation: 'client.connect' });
118
142
  }
119
- return parsed;
143
+ return keepOnOrigin(parsed, this.#sessionUrl);
120
144
  }
121
145
  /** The account id this connection reads and writes. */
122
146
  async accountId() {
@@ -90,7 +90,26 @@ export declare class FakeCalendarStore {
90
90
  uid: string;
91
91
  }[];
92
92
  constructor(options?: FakeOptions);
93
- /** The session document, as Stalwart writes it. */
93
+ /**
94
+ * The session document, as Stalwart writes it.
95
+ *
96
+ * **Every seeded principal is listed in `accounts`, not only `me`**
97
+ * (wtfalch/calendar#65): this fake never inspects the bearer token a
98
+ * caller actually presents (it is a fake calendar universe, not an auth
99
+ * simulator), so it cannot tell "the signed-in browser session" apart from
100
+ * "a service credential minted for someone else's account" the way a real
101
+ * Stalwart would -- a real server's session document lists only the
102
+ * account(s) the presented credential can reach. Listing every seeded
103
+ * account here is the honest reflection of that: this fake would answer
104
+ * *some* session document for a service credential regardless of whose
105
+ * account it names, so it answers one where that account is actually
106
+ * there, rather than failing every service-credential test on a check this
107
+ * fake has no way to enforce for real. `primaryAccounts` still names `me`
108
+ * -- unrelated to whether another account is reachable by naming it
109
+ * explicitly via `CalendarClientOptions.accountId`, the same way a real
110
+ * session's own primary account says nothing about which other accounts
111
+ * the credential can also reach.
112
+ */
94
113
  session(origin: string): Record<string, unknown>;
95
114
  /** Answer one method call. Exported for the transport, and for a test that
96
115
  * wants to drive one side of a scheduling exchange directly — the