@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.
@@ -5,21 +5,45 @@
5
5
  * **A fake transport, not a fake API.** This answers JMAP calls the same way
6
6
  * a running Stalwart does, so a component or a client method drawn against
7
7
  * this fake is drawn through exactly the code that will face a real server —
8
- * including the four load-bearing behaviours confirmed live against Stalwart
9
- * v0.16.20 (https://github.com/wtfalch/messaging/issues/145):
8
+ * including the six load-bearing behaviours confirmed live against Stalwart
9
+ * v0.16.20 (https://github.com/wtfalch/messaging/issues/145 for 1-4, issue
10
+ * #17 for 5, issue #15 for 6, https://github.com/wtfalch/calendar/issues):
10
11
  *
11
12
  * 1. `CalendarEvent/query` without `expandRecurrences` returns master
12
13
  * events only; with it, and both `after`/`before`, dated occurrences —
13
- * and with it but no bounds, `invalidArguments`.
14
+ * and with it but no bounds, `invalidArguments`
15
+ * (https://github.com/wtfalch/messaging/issues/145).
14
16
  * 2. An invite (`CalendarEvent/set create` with `sendSchedulingMessages`)
15
- * lands a copy straight in the invitee's own calendar; the invitee's own
16
- * reply (`update` with `sendSchedulingMessages`) updates every other
17
- * copy sharing the same `uid`, including the organiser's.
17
+ * lands a copy straight in the invitee's own calendar. An organiser edit
18
+ * (`update` with `sendSchedulingMessages`) bumps `sequence` and mirrors
19
+ * the whole `participants` map onto every other copy sharing the same
20
+ * `uid`. A reply from someone who is *not* this copy's organiser -- a
21
+ * patch touching only one participant's
22
+ * `participationStatus`/`participationComment`, `respond`'s own shape --
23
+ * is different: it bumps `sequence` nowhere, and it carries only the
24
+ * status, never the comment, to the other copies. The organiser sending
25
+ * that identical shape on her own event is still an ordinary edit, not a
26
+ * reply (T11 live capture and re-capture,
27
+ * https://github.com/wtfalch/calendar/issues/11) -- and a reply against a
28
+ * synthetic occurrence id is refused outright
29
+ * (`"Multiple organizers found in iCalendar object"`), never silently
30
+ * written into `recurrenceOverrides`.
18
31
  * 3. A grant written to `Calendar/set update {shareWith}` reads back on the
19
- * next `Calendar/get`.
32
+ * next `Calendar/get` (https://github.com/wtfalch/messaging/issues/145).
20
33
  * 4. `Principal/getAvailability` returns busy periods for a calendar shared
21
34
  * with at least `mayReadItems` — no second opt-in needed — and an empty
22
35
  * list for one shared with nothing at all.
36
+ * 5. `CalendarEvent/query`'s `text` filter matches a case-insensitive
37
+ * substring of either `title` or `description` in one pass, and needs no
38
+ * `after`/`before` at all unless `expandRecurrences` is also set, in
39
+ * which case both are still required regardless of `text`.
40
+ * 6. An `alerts` map -- offset or absolute trigger, display action,
41
+ * `acknowledged` -- round-trips through `CalendarEvent/set create` and
42
+ * `get` unchanged (T15, issue #15). A trigger with neither `offset` nor
43
+ * `when` is accepted on write but comes back with no `trigger` key at
44
+ * all (T15 amendment); `CalendarEvent/set` on `alerts` replaces the
45
+ * whole map, so a write that does not carry `acknowledged` forward
46
+ * wipes it.
23
47
  *
24
48
  * It implements only the methods `@wtfalch/calendar` sends. Anything else
25
49
  * answers `unknownMethod`, which is what a real server does and what the
@@ -57,8 +81,31 @@ const ALL_RIGHTS = Object.fromEntries(RIGHTS.map((right) => [right, true]));
57
81
  function fullRightsEcho(rights) {
58
82
  return Object.fromEntries(RIGHTS.map((right) => [right, rights[right] === true]));
59
83
  }
84
+ /** How two touches on the same id in one `.../set` call net out, before the
85
+ * log even sees them: `destroy` always wins (nothing later can matter once
86
+ * an id is gone), otherwise the later op wins except that `create` survives
87
+ * a later `update` -- an id created and then edited in the same call is
88
+ * still, from a change feed's point of view, simply `created`. */
89
+ function mergeOp(previous, next) {
90
+ if (previous === undefined)
91
+ return next;
92
+ if (next === 'destroy')
93
+ return 'destroy';
94
+ if (previous === 'create')
95
+ return 'create';
96
+ return next;
97
+ }
60
98
  const OCCURRENCE_SEPARATOR = '~';
61
99
  const MAX_OCCURRENCES = 1_000;
100
+ /** The shared campaign Stalwart's own `urn:ietf:params:jmap:core.
101
+ * maxCallsInRequest`, measured live for issue #13: a 16-call
102
+ * `Principal/getAvailability` batch answers 16 `methodResponses`, and a
103
+ * 17-call one is refused whole (`test/wire-live-transcript.test.ts`'s
104
+ * `LIVE_LIMIT_REFUSAL`). Advertised here and enforced in `fetch` below, so
105
+ * a client that stops chunking -- or that hardcodes some other number --
106
+ * fails a fake-backed test immediately, with no live server needed to
107
+ * catch it a second time. */
108
+ const MAX_CALLS_IN_REQUEST = 16;
62
109
  function occurrenceId(masterId, date) {
63
110
  return `${masterId}${OCCURRENCE_SEPARATOR}${date.toISOString()}`;
64
111
  }
@@ -137,6 +184,34 @@ function firstLocationName(locations) {
137
184
  function locationToWireMap(location) {
138
185
  return location === undefined ? null : { main: { '@type': 'Location', name: location } };
139
186
  }
187
+ /** `wire.ts`'s `virtualLocationsFromWire` shape: a map of `VirtualLocation`
188
+ * objects, keyed arbitrarily -- accepted from a raw JMAP write this fake's
189
+ * own client never made, so entries missing a string `uri` are dropped
190
+ * rather than crashing (#16). */
191
+ function virtualLocationsFromWireMap(value) {
192
+ if (!value || typeof value !== 'object')
193
+ return undefined;
194
+ const list = Object.values(value)
195
+ .map((entry) => entry)
196
+ .filter((entry) => typeof entry.uri === 'string')
197
+ .map((entry) => ({
198
+ uri: entry.uri,
199
+ name: typeof entry.name === 'string' ? entry.name : undefined,
200
+ }));
201
+ return list.length > 0 ? list : undefined;
202
+ }
203
+ function virtualLocationsToWireMap(locations) {
204
+ if (!locations)
205
+ return null;
206
+ return Object.fromEntries(locations.map((location, i) => [
207
+ `v${i}`,
208
+ {
209
+ '@type': 'VirtualLocation',
210
+ uri: location.uri,
211
+ ...(location.name === undefined ? {} : { name: location.name }),
212
+ },
213
+ ]));
214
+ }
140
215
  function rolesToMap(roles) {
141
216
  if (!roles)
142
217
  return undefined;
@@ -174,6 +249,33 @@ function normalizeParticipants(input) {
174
249
  }
175
250
  return out;
176
251
  }
252
+ /** The pattern `respond`'s own patch always writes: one participant's
253
+ * `participationStatus`, optionally alongside that same participant's
254
+ * `participationComment` (T11 live capture — the wire name a real server
255
+ * answers to, not JSCalendar's plain `comment`). */
256
+ const REPLY_PATCH_PATH = /^participants\/([^/]+)\/(participationStatus|participationComment)$/;
257
+ /** The participant id an update patch replies for, or `null` when the patch
258
+ * is not shaped like a reply at all — an organiser edit, which may touch
259
+ * anything, including the whole `participants` map in one go. Every key in
260
+ * a genuine reply patch names the *same* participant; a patch that mixes
261
+ * another field in, or touches two participants at once, is an organiser
262
+ * edit and must not be mistaken for one attendee's own answer. */
263
+ function replyParticipantId(patch) {
264
+ const keys = Object.keys(patch);
265
+ if (keys.length === 0)
266
+ return null;
267
+ let id = null;
268
+ for (const key of keys) {
269
+ const match = REPLY_PATCH_PATH.exec(key);
270
+ if (!match)
271
+ return null;
272
+ const participantId = match[1];
273
+ if (id !== null && id !== participantId)
274
+ return null;
275
+ id = participantId;
276
+ }
277
+ return id;
278
+ }
177
279
  /** RFC 6901 §3, for a result reference's path only — none of this fake's own
178
280
  * patch paths need unescaping, since none of its ids ever contain `~`. */
179
281
  function unpointer(segment) {
@@ -198,7 +300,7 @@ function pointer(value, path) {
198
300
  }
199
301
  return current;
200
302
  }
201
- const ERROR_TYPES = new Set(['invalidArguments', 'unknownMethod']);
303
+ const ERROR_TYPES = new Set(['invalidArguments', 'unknownMethod', 'cannotCalculateChanges']);
202
304
  export class FakeCalendarStore {
203
305
  me;
204
306
  #now;
@@ -225,7 +327,14 @@ export class FakeCalendarStore {
225
327
  }
226
328
  }
227
329
  #seed(principal) {
228
- const bucket = { calendars: new Map(), events: new Map() };
330
+ const bucket = {
331
+ calendars: new Map(),
332
+ events: new Map(),
333
+ eventState: 0,
334
+ eventLog: [],
335
+ calendarState: 0,
336
+ calendarLog: [],
337
+ };
229
338
  for (const seedCalendar of principal.calendars) {
230
339
  bucket.calendars.set(seedCalendar.id, {
231
340
  id: seedCalendar.id,
@@ -255,6 +364,7 @@ export class FakeCalendarStore {
255
364
  location: seedEvent.location,
256
365
  recurrenceRule: seedEvent.recurrenceRule,
257
366
  status: seedEvent.status ?? 'confirmed',
367
+ freeBusyStatus: seedEvent.freeBusyStatus,
258
368
  sequence: 0,
259
369
  });
260
370
  }
@@ -266,17 +376,171 @@ export class FakeCalendarStore {
266
376
  #account(accountId) {
267
377
  let bucket = this.#accounts.get(accountId);
268
378
  if (!bucket) {
269
- bucket = { calendars: new Map(), events: new Map() };
379
+ bucket = {
380
+ calendars: new Map(),
381
+ events: new Map(),
382
+ eventState: 0,
383
+ eventLog: [],
384
+ calendarState: 0,
385
+ calendarLog: [],
386
+ };
270
387
  this.#accounts.set(accountId, bucket);
271
388
  }
272
389
  return bucket;
273
390
  }
274
- /** The session document, as Stalwart writes it. */
391
+ /** Record one `.../set` call's worth of touches at a fresh state, once --
392
+ * every id touched in the same call shares one new state number, matching
393
+ * how this fake already answers one `oldState`/`newState` pair per call
394
+ * rather than one per object (wtfalch/calendar#65). A no-op call (`touched`
395
+ * empty) never advances the state at all. */
396
+ #bumpEventLog(account, touched) {
397
+ if (touched.size === 0)
398
+ return;
399
+ account.eventState += 1;
400
+ for (const [id, op] of touched)
401
+ account.eventLog.push({ state: account.eventState, id, op });
402
+ }
403
+ /** `Calendar/set`'s own counterpart to `#bumpEventLog`, over the separate
404
+ * `calendarState`/`calendarLog` pair -- the two `/changes` streams never
405
+ * share a state space (matching `sync.ts`'s own `calendar_event_state`/
406
+ * `calendar_state` split). */
407
+ #bumpCalendarLog(account, touched) {
408
+ if (touched.size === 0)
409
+ return;
410
+ account.calendarState += 1;
411
+ for (const [id, op] of touched) {
412
+ account.calendarLog.push({ state: account.calendarState, id, op });
413
+ }
414
+ }
415
+ /**
416
+ * `CalendarEvent/changes`/`Calendar/changes`'s shared answer shape (RFC
417
+ * 8620 §5.2), computed from one type's own log. `maxChanges` truncates on a
418
+ * whole-state boundary, never splitting one `.../set` call's ids across two
419
+ * `changes()` answers -- this fake never logs a state with zero ids in it,
420
+ * so "the next state would exceed maxChanges" and "stop before it" are the
421
+ * same decision.
422
+ */
423
+ #computeChanges(log, sinceState, maxChanges) {
424
+ // Every id that existed the instant before `sinceState`'s own boundary --
425
+ // replayed from the start of the log, which this fake keeps in full
426
+ // (never pruned), so "unknown to this fake" (checked by the caller) only
427
+ // ever means malformed or in-the-future, never "too old to still have a
428
+ // record of".
429
+ const existedAtSince = new Set();
430
+ for (const entry of log) {
431
+ if (entry.state > sinceState)
432
+ break;
433
+ if (entry.op === 'destroy')
434
+ existedAtSince.delete(entry.id);
435
+ else
436
+ existedAtSince.add(entry.id);
437
+ }
438
+ const window = log.filter((entry) => entry.state > sinceState);
439
+ const states = [...new Set(window.map((entry) => entry.state))].sort((a, b) => a - b);
440
+ const includedStates = [];
441
+ let idsSoFar = new Set();
442
+ for (const state of states) {
443
+ const idsAtState = new Set(window.filter((entry) => entry.state === state).map((entry) => entry.id));
444
+ const union = new Set([...idsSoFar, ...idsAtState]);
445
+ if (includedStates.length > 0 && union.size > maxChanges)
446
+ break;
447
+ includedStates.push(state);
448
+ idsSoFar = union;
449
+ }
450
+ const hasMoreChanges = includedStates.length < states.length;
451
+ const newState = includedStates.length > 0 ? includedStates[includedStates.length - 1] : sinceState;
452
+ const includedEntries = window.filter((entry) => includedStates.includes(entry.state));
453
+ const perId = new Map();
454
+ for (const entry of includedEntries) {
455
+ const ops = perId.get(entry.id) ?? [];
456
+ ops.push(entry.op);
457
+ perId.set(entry.id, ops);
458
+ }
459
+ const created = [];
460
+ const updated = [];
461
+ const destroyed = [];
462
+ for (const [id, ops] of perId) {
463
+ const existedBefore = existedAtSince.has(id);
464
+ const lastOp = ops[ops.length - 1];
465
+ if (!existedBefore) {
466
+ // Created and destroyed within the same window: never seen at all,
467
+ // the same netting RFC 8620 §5.2's own `/changes` semantics expect.
468
+ if (lastOp !== 'destroy')
469
+ created.push(id);
470
+ }
471
+ else if (lastOp === 'destroy') {
472
+ destroyed.push(id);
473
+ }
474
+ else {
475
+ updated.push(id);
476
+ }
477
+ }
478
+ return { created, updated, destroyed, newState: String(newState), hasMoreChanges };
479
+ }
480
+ /** `sinceState` unparseable, negative, or naming a state this account has
481
+ * never reached is answered as `cannotCalculateChanges` -- RFC 8620 §5.2's
482
+ * own error for a `/changes` call the server cannot resolve
483
+ * (wtfalch/calendar#65). */
484
+ #changesFor(accountId, log, currentState, args) {
485
+ const sinceStateRaw = String(args.sinceState ?? '');
486
+ const sinceState = Number(sinceStateRaw);
487
+ if (!Number.isInteger(sinceState) || sinceState < 0 || sinceState > currentState) {
488
+ return {
489
+ type: 'cannotCalculateChanges',
490
+ description: `sinceState ${JSON.stringify(sinceStateRaw)} is unknown to this fake calendar`,
491
+ };
492
+ }
493
+ const maxChanges = typeof args.maxChanges === 'number' && args.maxChanges > 0 ? args.maxChanges : 1_000;
494
+ const result = this.#computeChanges(log, sinceState, maxChanges);
495
+ return { accountId, oldState: sinceStateRaw, ...result };
496
+ }
497
+ #eventChanges(args) {
498
+ const accountId = String(args.accountId ?? this.me.accountId);
499
+ const account = this.#account(accountId);
500
+ return this.#changesFor(accountId, account.eventLog, account.eventState, args);
501
+ }
502
+ #calendarChanges(args) {
503
+ const accountId = String(args.accountId ?? this.me.accountId);
504
+ const account = this.#account(accountId);
505
+ return this.#changesFor(accountId, account.calendarLog, account.calendarState, args);
506
+ }
507
+ /**
508
+ * The session document, as Stalwart writes it.
509
+ *
510
+ * **Every seeded principal is listed in `accounts`, not only `me`**
511
+ * (wtfalch/calendar#65): this fake never inspects the bearer token a
512
+ * caller actually presents (it is a fake calendar universe, not an auth
513
+ * simulator), so it cannot tell "the signed-in browser session" apart from
514
+ * "a service credential minted for someone else's account" the way a real
515
+ * Stalwart would -- a real server's session document lists only the
516
+ * account(s) the presented credential can reach. Listing every seeded
517
+ * account here is the honest reflection of that: this fake would answer
518
+ * *some* session document for a service credential regardless of whose
519
+ * account it names, so it answers one where that account is actually
520
+ * there, rather than failing every service-credential test on a check this
521
+ * fake has no way to enforce for real. `primaryAccounts` still names `me`
522
+ * -- unrelated to whether another account is reachable by naming it
523
+ * explicitly via `CalendarClientOptions.accountId`, the same way a real
524
+ * session's own primary account says nothing about which other accounts
525
+ * the credential can also reach.
526
+ */
275
527
  session(origin) {
276
528
  const meId = this.me.accountId;
529
+ const accounts = {};
530
+ for (const [accountId, principal] of this.#principals) {
531
+ accounts[accountId] = {
532
+ name: principal.email,
533
+ isPersonal: accountId === meId,
534
+ isReadOnly: false,
535
+ accountCapabilities: {
536
+ 'urn:ietf:params:jmap:calendars': {},
537
+ 'urn:ietf:params:jmap:calendars:parse': {},
538
+ },
539
+ };
540
+ }
277
541
  return {
278
542
  capabilities: {
279
- 'urn:ietf:params:jmap:core': {},
543
+ 'urn:ietf:params:jmap:core': { maxCallsInRequest: MAX_CALLS_IN_REQUEST },
280
544
  // Field names confirmed live against Stalwart v0.16.20 (#137).
281
545
  'urn:ietf:params:jmap:calendars': {
282
546
  maxCalendarsPerEvent: 1,
@@ -288,17 +552,7 @@ export class FakeCalendarStore {
288
552
  },
289
553
  'urn:ietf:params:jmap:calendars:parse': {},
290
554
  },
291
- accounts: {
292
- [meId]: {
293
- name: this.me.email,
294
- isPersonal: true,
295
- isReadOnly: false,
296
- accountCapabilities: {
297
- 'urn:ietf:params:jmap:calendars': {},
298
- 'urn:ietf:params:jmap:calendars:parse': {},
299
- },
300
- },
301
- },
555
+ accounts,
302
556
  primaryAccounts: {
303
557
  'urn:ietf:params:jmap:calendars': meId,
304
558
  'urn:ietf:params:jmap:calendars:parse': meId,
@@ -327,6 +581,10 @@ export class FakeCalendarStore {
327
581
  return this.#eventGet(args);
328
582
  case 'CalendarEvent/set':
329
583
  return this.#eventSet(args);
584
+ case 'CalendarEvent/changes':
585
+ return this.#eventChanges(args);
586
+ case 'Calendar/changes':
587
+ return this.#calendarChanges(args);
330
588
  case 'Principal/getAvailability':
331
589
  return this.#getAvailability(args);
332
590
  case 'Principal/query':
@@ -413,6 +671,7 @@ export class FakeCalendarStore {
413
671
  const update = (args.update ?? {});
414
672
  const updated = {};
415
673
  const notUpdated = {};
674
+ const touched = new Map();
416
675
  for (const [id, patch] of Object.entries(update)) {
417
676
  const calendar = account.calendars.get(id);
418
677
  if (!calendar) {
@@ -451,9 +710,12 @@ export class FakeCalendarStore {
451
710
  notUpdated[id] = { type: 'invalidPatch', description: `cannot patch ${path}` };
452
711
  }
453
712
  }
454
- if (!notUpdated[id])
713
+ if (!notUpdated[id]) {
455
714
  updated[id] = null;
715
+ touched.set(id, 'update');
716
+ }
456
717
  }
718
+ this.#bumpCalendarLog(account, touched);
457
719
  return {
458
720
  accountId,
459
721
  oldState: '1',
@@ -471,6 +733,17 @@ export class FakeCalendarStore {
471
733
  const expand = args.expandRecurrences === true || filter.expandRecurrences === true;
472
734
  const after = firstString(args.after, filter.after);
473
735
  const before = firstString(args.before, filter.before);
736
+ // `text` -- `searchEvents`'s own filter (issue #17) -- matches a
737
+ // case-insensitive substring of either `title` or `description` in one
738
+ // pass, live-confirmed against Stalwart v0.16.20 (2026-09-21): no
739
+ // `after`/`before` at all is a valid, unbounded query, exactly like the
740
+ // unfiltered listing below.
741
+ const text = typeof filter.text === 'string' ? filter.text.toLowerCase() : undefined;
742
+ const matchesText = (event) => text === undefined ||
743
+ event.title.toLowerCase().includes(text) ||
744
+ (event.description?.toLowerCase().includes(text) ?? false);
745
+ const limit = typeof args.limit === 'number' ? args.limit : undefined;
746
+ const limited = (ids) => (limit === undefined ? ids : ids.slice(0, limit));
474
747
  if (expand) {
475
748
  if (!after || !before) {
476
749
  return {
@@ -482,6 +755,8 @@ export class FakeCalendarStore {
482
755
  const rangeBefore = new Date(before);
483
756
  const ids = [];
484
757
  for (const event of account.events.values()) {
758
+ if (!matchesText(event))
759
+ continue;
485
760
  if (event.recurrenceRule) {
486
761
  for (const start of occurrenceStarts(new Date(`${event.start}Z`), event.recurrenceRule, rangeAfter, rangeBefore)) {
487
762
  // An excluded occurrence is gone from the expansion, which is how
@@ -497,19 +772,33 @@ export class FakeCalendarStore {
497
772
  ids.push(event.id);
498
773
  }
499
774
  }
500
- return { accountId, queryState: 'q1', canCalculateChanges: false, position: 0, ids };
775
+ return {
776
+ accountId,
777
+ queryState: 'q1',
778
+ canCalculateChanges: false,
779
+ position: 0,
780
+ ids: limited(ids),
781
+ };
501
782
  }
502
783
  // Unexpanded: every master event, including a recurring one's own single
503
784
  // id — never one of its occurrences (MSG-053 acceptance criteria).
504
785
  const ids = [...account.events.values()]
505
786
  .filter((event) => {
787
+ if (!matchesText(event))
788
+ return false;
506
789
  if (!after && !before)
507
790
  return true;
508
791
  const start = new Date(`${event.start}Z`);
509
792
  return (!after || start >= new Date(after)) && (!before || start < new Date(before));
510
793
  })
511
794
  .map((event) => event.id);
512
- return { accountId, queryState: 'q1', canCalculateChanges: false, position: 0, ids };
795
+ return {
796
+ accountId,
797
+ queryState: 'q1',
798
+ canCalculateChanges: false,
799
+ position: 0,
800
+ ids: limited(ids),
801
+ };
513
802
  }
514
803
  #eventGet(args) {
515
804
  const accountId = String(args.accountId ?? this.me.accountId);
@@ -533,7 +822,18 @@ export class FakeCalendarStore {
533
822
  notFound.push(id);
534
823
  continue;
535
824
  }
536
- list.push(this.#projectEvent(event));
825
+ list.push({
826
+ ...this.#projectEvent(event),
827
+ // Not part of the shape every caller reads -- only the
828
+ // 'following'-scope cleanup in `calendar-client.ts` asks a master
829
+ // directly for its own overrides, to exclude one a rule truncation
830
+ // just stranded past its new `until`. An occurrence's own get
831
+ // (`#projectOccurrence`, which never reaches this branch) has no
832
+ // business echoing the whole map back.
833
+ ...(event.recurrenceOverrides
834
+ ? { recurrenceOverrides: { ...event.recurrenceOverrides } }
835
+ : {}),
836
+ });
537
837
  }
538
838
  return { accountId, state: 'e1', list, notFound };
539
839
  }
@@ -553,12 +853,29 @@ export class FakeCalendarStore {
553
853
  // for MSG-055 to confirm live).
554
854
  showWithoutTime: event.isAllDay,
555
855
  locations: locationToWireMap(event.location),
856
+ virtualLocations: virtualLocationsToWireMap(event.virtualLocations),
556
857
  recurrenceRule: event.recurrenceRule ? { ...event.recurrenceRule } : null,
557
858
  participants: event.participants
558
859
  ? Object.fromEntries(Object.entries(event.participants).map(([id, participant]) => [id, { ...participant }]))
559
860
  : null,
861
+ alerts: event.alerts
862
+ ? Object.fromEntries(Object.entries(event.alerts).map(([id, alert]) => [id, { ...alert }]))
863
+ : null,
864
+ links: event.links
865
+ ? Object.fromEntries(Object.entries(event.links).map(([id, link]) => [id, { ...link }]))
866
+ : null,
560
867
  status: event.status,
868
+ mayInviteSelf: event.mayInviteSelf ?? null,
869
+ mayInviteOthers: event.mayInviteOthers ?? null,
870
+ freeBusyStatus: event.freeBusyStatus ?? null,
561
871
  sequence: event.sequence,
872
+ // Every event's own get carries this, equal to its own id when the
873
+ // event is not an occurrence -- live-confirmed against Stalwart
874
+ // v0.16.20 (wtfalch/calendar#14; corrects `types.ts`'s
875
+ // `CalendarEvent.baseEventId` doc comment, which had claimed it was
876
+ // absent on a master). `#projectOccurrence` overwrites this with the
877
+ // real master's id for an occurrence.
878
+ baseEventId: event.id,
562
879
  };
563
880
  }
564
881
  /** A synthetic per-occurrence id, distinct from the master's — real
@@ -572,12 +889,20 @@ export class FakeCalendarStore {
572
889
  #projectOccurrence(master, id, iso) {
573
890
  const override = master.recurrenceOverrides?.[this.#overrideKey(iso)] ?? {};
574
891
  const { excluded: _excluded, '@type': _type, ...fields } = override;
892
+ // Both in `start`'s own local, offset-free shape (no milliseconds, no
893
+ // trailing `Z`) -- live-confirmed against Stalwart v0.16.20
894
+ // (wtfalch/calendar#14). `recurrenceId` used to keep `iso`'s raw
895
+ // `Date#toISOString()` form (milliseconds and a trailing `Z`), which
896
+ // disagreed with `start` on the very same occurrence and, worse, wasn't
897
+ // even the shape `truncateSeriesBefore`'s own `until` arithmetic expects
898
+ // for the value it reads back through `getEvent`.
899
+ const local = iso.slice(0, 19);
575
900
  return {
576
901
  ...this.#projectEvent(master),
577
902
  id,
578
903
  baseEventId: master.id,
579
- recurrenceId: iso,
580
- start: iso.slice(0, 19),
904
+ recurrenceId: local,
905
+ start: local,
581
906
  recurrenceRule: null,
582
907
  ...fields,
583
908
  };
@@ -598,12 +923,19 @@ export class FakeCalendarStore {
598
923
  // that forgets this sends no invites (types.ts's `SchedulingOptions`;
599
924
  // #137 "Scheduling").
600
925
  const sendScheduling = args.sendSchedulingMessages === true;
926
+ // What `CalendarEvent/changes` reads back from, once this call finishes
927
+ // (wtfalch/calendar#65) -- every id below names a real, top-level event
928
+ // (a synthetic occurrence id's own touch is logged against its master,
929
+ // since only the master's data actually changed).
930
+ const touched = new Map();
931
+ const touch = (id, op) => touched.set(id, mergeOp(touched.get(id), op));
601
932
  const create = (args.create ?? {});
602
933
  const created = {};
603
934
  for (const [key, draft] of Object.entries(create)) {
604
935
  const event = this.#toWireEvent(draft);
605
936
  account.events.set(event.id, event);
606
937
  created[key] = { id: event.id, uid: event.uid, sequence: event.sequence };
938
+ touch(event.id, 'create');
607
939
  if (sendScheduling)
608
940
  this.#sendInvites(event);
609
941
  }
@@ -623,8 +955,23 @@ export class FakeCalendarStore {
623
955
  notUpdated[id] = { type: 'notFound' };
624
956
  continue;
625
957
  }
958
+ if (replyParticipantId(patch) !== null) {
959
+ // `respond` only ever targets a real event id, never an
960
+ // occurrence's synthetic one -- and a reply against one is refused
961
+ // outright, live-confirmed against Stalwart v0.16.20 for T11
962
+ // (https://github.com/wtfalch/calendar/issues/11). The fake used to
963
+ // silently write a `recurrenceOverrides` entry instead, which no
964
+ // live run ever produced.
965
+ notUpdated[id] = {
966
+ type: 'invalidProperties',
967
+ description: 'Multiple organizers found in iCalendar object',
968
+ properties: ['participants'],
969
+ };
970
+ continue;
971
+ }
626
972
  this.#writeOverride(master, split.iso, patch);
627
973
  updated[id] = null;
974
+ touch(master.id, 'update');
628
975
  continue;
629
976
  }
630
977
  const event = account.events.get(id);
@@ -632,9 +979,23 @@ export class FakeCalendarStore {
632
979
  notUpdated[id] = { type: 'notFound' };
633
980
  continue;
634
981
  }
982
+ // A reply -- `respond`'s own patch shape -- bumps nothing, on either
983
+ // side, but only when it comes from someone other than this copy's own
984
+ // organiser: T11 live re-capture found the organiser sending this exact
985
+ // shape on her own event is an ordinary organiser edit (`sequence`
986
+ // absent/0 -> 1 on every copy, the whole map mirrored), not a reply.
987
+ const replyId = replyParticipantId(patch);
635
988
  this.#applyPatch(event, patch);
989
+ if (replyId !== null && !this.#isOrganiser(accountId, event)) {
990
+ updated[id] = null;
991
+ touch(event.id, 'update');
992
+ if (sendScheduling)
993
+ this.#propagateReply(accountId, event, replyId);
994
+ continue;
995
+ }
636
996
  event.sequence += 1;
637
997
  updated[id] = null;
998
+ touch(event.id, 'update');
638
999
  if (sendScheduling)
639
1000
  this.#propagateStatus(accountId, event);
640
1001
  }
@@ -646,12 +1007,16 @@ export class FakeCalendarStore {
646
1007
  const split = splitOccurrenceId(id);
647
1008
  if (split) {
648
1009
  const master = account.events.get(split.masterId);
649
- if (master?.recurrenceRule)
1010
+ if (master?.recurrenceRule) {
650
1011
  this.#writeOverride(master, split.iso, { excluded: true });
1012
+ touch(master.id, 'update');
1013
+ }
651
1014
  continue;
652
1015
  }
653
1016
  account.events.delete(id);
1017
+ touch(id, 'destroy');
654
1018
  }
1019
+ this.#bumpEventLog(account, touched);
655
1020
  return {
656
1021
  accountId,
657
1022
  oldState: '1',
@@ -690,9 +1055,15 @@ export class FakeCalendarStore {
690
1055
  isAllDay: Boolean(draft.showWithoutTime ?? draft.isAllDay),
691
1056
  location: firstLocationName(draft.locations) ??
692
1057
  (typeof draft.location === 'string' ? draft.location : undefined),
1058
+ virtualLocations: virtualLocationsFromWireMap(draft.virtualLocations),
693
1059
  recurrenceRule: draft.recurrenceRule,
694
1060
  participants: normalizeParticipants(draft.participants),
1061
+ mayInviteSelf: draft.mayInviteSelf,
1062
+ mayInviteOthers: draft.mayInviteOthers,
1063
+ alerts: draft.alerts,
1064
+ links: draft.links,
695
1065
  status: draft.status ?? 'confirmed',
1066
+ freeBusyStatus: draft.freeBusyStatus,
696
1067
  sequence: 0,
697
1068
  };
698
1069
  }
@@ -727,23 +1098,79 @@ export class FakeCalendarStore {
727
1098
  calendarIds: { [defaultCalendarId]: true },
728
1099
  });
729
1100
  this.invitesSent.push({ accountId: inviteeId, eventId: copyId, uid: event.uid });
1101
+ this.#bumpEventLog(account, new Map([[copyId, 'create']]));
730
1102
  }
731
1103
  }
732
- /** Mirror this copy's participants onto every other copy sharing the same
733
- * `uid`, in any account — the shared scheduling engine real Stalwart runs
734
- * underneath both CalDAV and JMAP (#145: "the reply reached alice... with
735
- * no action on her part"). */
1104
+ /** Whether `accountId` holds this copy's own `owner` role -- the
1105
+ * distinction between a reply and an organiser edit that merely looks
1106
+ * like one. A `participants/<id>/participationStatus`-shaped patch is a
1107
+ * reply only when it comes from someone other than the organiser:
1108
+ * live re-confirmed for T11
1109
+ * (https://github.com/wtfalch/calendar/issues/11) that the organiser
1110
+ * sending that exact shape on her own event is an ordinary edit --
1111
+ * `sequence` goes from absent/0 to `1` on every copy, and the whole
1112
+ * `participants` map mirrors, the same as any other organiser write. */
1113
+ #isOrganiser(accountId, event) {
1114
+ const owner = Object.values(event.participants ?? {}).find((p) => p.roles?.owner === true);
1115
+ if (!owner)
1116
+ return false;
1117
+ const ownerAccountId = this.#emailToAccountId.get(owner.calendarAddress.replace(/^mailto:/i, '').toLowerCase());
1118
+ return ownerAccountId === accountId;
1119
+ }
1120
+ /** Mirror this copy's whole `participants` map onto every other copy
1121
+ * sharing the same `uid`, in any account — the shared scheduling engine
1122
+ * real Stalwart runs underneath both CalDAV and JMAP (#145: "the reply
1123
+ * reached alice... with no action on her part"). Every organiser edit
1124
+ * takes this path, including one shaped exactly like a reply
1125
+ * (`#isOrganiser` above); `#propagateReply` below is the narrower path an
1126
+ * attendee's own `respond` takes. */
736
1127
  #propagateStatus(fromAccountId, event) {
737
1128
  for (const [accountId, account] of this.#accounts) {
738
1129
  if (accountId === fromAccountId)
739
1130
  continue;
1131
+ const touched = new Map();
740
1132
  for (const other of account.events.values()) {
741
1133
  if (other.uid !== event.uid)
742
1134
  continue;
743
1135
  other.participants = event.participants;
744
1136
  other.sequence += 1;
745
1137
  this.repliesSent.push({ accountId, eventId: other.id, uid: event.uid });
1138
+ touched.set(other.id, 'update');
746
1139
  }
1140
+ this.#bumpEventLog(account, touched);
1141
+ }
1142
+ }
1143
+ /** A reply — `respond`'s own patch shape — carries only the one
1144
+ * participant's new `participationStatus` to every other copy sharing the
1145
+ * same `uid`, matched by address rather than by map key: a copy's own key
1146
+ * for the same person need not match another's. Two things `#propagateStatus`
1147
+ * above does that this deliberately does not: it never bumps `sequence`,
1148
+ * anywhere, and it never carries `participationComment` along —
1149
+ * live-confirmed for T11, a comment sent alongside a status change never
1150
+ * reached the organiser's own copy, so it must stay this replier's alone. */
1151
+ #propagateReply(fromAccountId, event, participantId) {
1152
+ const mine = event.participants?.[participantId];
1153
+ if (!mine)
1154
+ return;
1155
+ for (const [accountId, account] of this.#accounts) {
1156
+ if (accountId === fromAccountId)
1157
+ continue;
1158
+ const touched = new Map();
1159
+ for (const other of account.events.values()) {
1160
+ if (other.uid !== event.uid || !other.participants)
1161
+ continue;
1162
+ const entry = Object.entries(other.participants).find(([, p]) => p.calendarAddress === mine.calendarAddress);
1163
+ if (!entry)
1164
+ continue;
1165
+ const [otherId, existing] = entry;
1166
+ other.participants = {
1167
+ ...other.participants,
1168
+ [otherId]: { ...existing, participationStatus: mine.participationStatus },
1169
+ };
1170
+ this.repliesSent.push({ accountId, eventId: other.id, uid: event.uid });
1171
+ touched.set(other.id, 'update');
1172
+ }
1173
+ this.#bumpEventLog(account, touched);
747
1174
  }
748
1175
  }
749
1176
  #applyPatch(event, patch) {
@@ -768,6 +1195,12 @@ export class FakeCalendarStore {
768
1195
  else if (path === 'participants') {
769
1196
  event.participants = normalizeParticipants(value);
770
1197
  }
1198
+ else if (path === 'mayInviteSelf') {
1199
+ event.mayInviteSelf = value;
1200
+ }
1201
+ else if (path === 'mayInviteOthers') {
1202
+ event.mayInviteOthers = value;
1203
+ }
771
1204
  else if (path === 'calendarIds') {
772
1205
  const calendarId = Object.keys(value ?? {})[0];
773
1206
  if (calendarId)
@@ -794,6 +1227,9 @@ export class FakeCalendarStore {
794
1227
  else if (path === 'locations') {
795
1228
  event.location = firstLocationName(value);
796
1229
  }
1230
+ else if (path === 'virtualLocations') {
1231
+ event.virtualLocations = virtualLocationsFromWireMap(value);
1232
+ }
797
1233
  else if (path === 'duration') {
798
1234
  event.duration = String(value);
799
1235
  }
@@ -801,11 +1237,45 @@ export class FakeCalendarStore {
801
1237
  event.isAllDay = Boolean(value);
802
1238
  }
803
1239
  else if (path === 'recurrenceRule') {
804
- event.recurrenceRule = value;
1240
+ // `wire.ts`'s `patchToWire` sends a real wire `null` for
1241
+ // `recurrenceRule: null` (wtfalch/calendar#45), distinct from the
1242
+ // key being absent entirely -- this fake must unset the rule the
1243
+ // same way a live server does, not store a literal `null` where
1244
+ // every reader (`#projectEvent`, `#eventQuery`, `#periodsForEvent`)
1245
+ // expects either the rule object or `undefined`.
1246
+ event.recurrenceRule = value === null ? undefined : value;
1247
+ }
1248
+ else if (path.startsWith('recurrenceOverrides/')) {
1249
+ // A rule truncation for 'following' scope excludes a stranded future
1250
+ // override in the same write that shortens the rule
1251
+ // (`calendar-client.ts`'s `truncateSeriesBefore`) -- keys are always
1252
+ // a plain `recurrenceId` string, never containing `~` or `/`, so
1253
+ // this needs none of `shareWith`'s RFC 6901 unescaping.
1254
+ const key = path.slice('recurrenceOverrides/'.length);
1255
+ if (value === null) {
1256
+ // `updateSeries`' own re-key on a `start` move (wtfalch/calendar#43)
1257
+ // deletes the stale key in the same write it creates the shifted
1258
+ // one -- the same null-means-remove convention `#calendarSet`
1259
+ // already uses for a revoked `shareWith` grantee, above.
1260
+ if (event.recurrenceOverrides)
1261
+ delete event.recurrenceOverrides[key];
1262
+ }
1263
+ else {
1264
+ this.#writeOverride(event, key, value);
1265
+ }
1266
+ }
1267
+ else if (path === 'alerts') {
1268
+ event.alerts = value;
1269
+ }
1270
+ else if (path === 'links') {
1271
+ event.links = value;
805
1272
  }
806
1273
  else if (path === 'status') {
807
1274
  event.status = value;
808
1275
  }
1276
+ else if (path === 'freeBusyStatus') {
1277
+ event.freeBusyStatus = value;
1278
+ }
809
1279
  // Anything else is accepted and ignored: this fake supports only the
810
1280
  // patch paths this package's own client sends.
811
1281
  }
@@ -815,18 +1285,22 @@ export class FakeCalendarStore {
815
1285
  * answers empty (#145 amendment, contradicting #137's original
816
1286
  * two-rights claim).
817
1287
  *
818
- * The principal being asked about is the method's own `accountId`
819
- * argument, not a separate `id` field: `Principal/getAvailability` reads
820
- * a *different* account's calendars, authorized by the caller's own
821
- * token, the same secondary-account pattern JMAP mail already uses for a
822
- * shared mailbox (`calendar-client.ts`'s `getAvailability`). This fake
823
- * only ever authenticates one session, so the caller granted rights
824
- * against is always `this.me.accountId`. */
1288
+ * The principal being asked about is a separate `id` argument, not the
1289
+ * method's own `accountId` — an earlier slice assumed the latter, on the
1290
+ * theory that `Principal/getAvailability` reads a *different* account the
1291
+ * way a shared-mailbox read does. Live testing for issue #13 found the
1292
+ * opposite: `accountId` is the *caller's* own account (this fake only
1293
+ * ever authenticates one session, so it is always `this.me.accountId`
1294
+ * and is not otherwise read here), and the range travels as
1295
+ * `utcStart`/`utcEnd` — `after`/`before` is kept as a fallback only
1296
+ * because nothing yet proves every caller has been updated to the real
1297
+ * names. The response, too, carries no `accountId` at all on the real
1298
+ * server (`test/availability-many.test.ts`'s pinned transcript). */
825
1299
  #getAvailability(args) {
826
1300
  const callerId = this.me.accountId;
827
- const principalId = String(args.accountId ?? args.id ?? '');
828
- const after = firstString(args.after, args.utcStart);
829
- const before = firstString(args.before, args.utcEnd);
1301
+ const principalId = String(args.id ?? args.accountId ?? '');
1302
+ const after = firstString(args.utcStart, args.after);
1303
+ const before = firstString(args.utcEnd, args.before);
830
1304
  const rangeAfter = after ? new Date(after) : new Date(0);
831
1305
  const rangeBefore = before ? new Date(before) : new Date(8_640_000_000_000_000);
832
1306
  const account = this.#accounts.get(principalId);
@@ -841,10 +1315,15 @@ export class FakeCalendarStore {
841
1315
  }
842
1316
  }
843
1317
  periods.sort((a, b) => (a.utcStart < b.utcStart ? -1 : 1));
844
- return { accountId: principalId, list: periods };
1318
+ return { list: periods };
845
1319
  }
846
1320
  #periodsForEvent(event, rangeAfter, rangeBefore) {
847
- if (event.status === 'cancelled')
1321
+ // A cancelled event never counted as busy; an event explicitly marked
1322
+ // 'free' (wtfalch/calendar#29) is the same case for a different reason --
1323
+ // its owner said outright that it should never produce a false conflict
1324
+ // in findTime(). Absent reads as 'busy', matching `wire.ts`'s own
1325
+ // `eventFromWire` default.
1326
+ if (event.status === 'cancelled' || event.freeBusyStatus === 'free')
848
1327
  return [];
849
1328
  const busyStatus = event.status === 'tentative' ? 'tentative' : 'confirmed';
850
1329
  const durationMs = minutesFromDuration(event.duration) * 60_000;
@@ -894,6 +1373,19 @@ export class FakeCalendarStore {
894
1373
  return json(this.session(new URL(url).origin));
895
1374
  }
896
1375
  const body = JSON.parse(String(init.body));
1376
+ if (body.methodCalls.length > MAX_CALLS_IN_REQUEST) {
1377
+ // The whole request is refused, before a single call in it runs --
1378
+ // measured live for issue #13, pinned as `LIVE_LIMIT_REFUSAL` in
1379
+ // `test/wire-live-transcript.test.ts`. A client that stops chunking
1380
+ // (or chunks to the wrong number) hits this the moment a fake-backed
1381
+ // test asks for more than `MAX_CALLS_IN_REQUEST` principals at once.
1382
+ return new Response(JSON.stringify({
1383
+ type: 'urn:ietf:params:jmap:error:limit',
1384
+ status: 400,
1385
+ detail: 'The request exceeds the maximum number of calls in a single request.',
1386
+ limit: 'maxCallsInRequest',
1387
+ }), { status: 400, headers: { 'Content-Type': 'application/json' } });
1388
+ }
897
1389
  const responses = [];
898
1390
  for (const [method, callArgs, id] of body.methodCalls) {
899
1391
  const resolved = this.#resolveRefs(callArgs, responses);