@wtfalch/calendar 0.1.0 → 0.2.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
@@ -59,6 +83,15 @@ function fullRightsEcho(rights) {
59
83
  }
60
84
  const OCCURRENCE_SEPARATOR = '~';
61
85
  const MAX_OCCURRENCES = 1_000;
86
+ /** The shared campaign Stalwart's own `urn:ietf:params:jmap:core.
87
+ * maxCallsInRequest`, measured live for issue #13: a 16-call
88
+ * `Principal/getAvailability` batch answers 16 `methodResponses`, and a
89
+ * 17-call one is refused whole (`test/wire-live-transcript.test.ts`'s
90
+ * `LIVE_LIMIT_REFUSAL`). Advertised here and enforced in `fetch` below, so
91
+ * a client that stops chunking -- or that hardcodes some other number --
92
+ * fails a fake-backed test immediately, with no live server needed to
93
+ * catch it a second time. */
94
+ const MAX_CALLS_IN_REQUEST = 16;
62
95
  function occurrenceId(masterId, date) {
63
96
  return `${masterId}${OCCURRENCE_SEPARATOR}${date.toISOString()}`;
64
97
  }
@@ -137,6 +170,34 @@ function firstLocationName(locations) {
137
170
  function locationToWireMap(location) {
138
171
  return location === undefined ? null : { main: { '@type': 'Location', name: location } };
139
172
  }
173
+ /** `wire.ts`'s `virtualLocationsFromWire` shape: a map of `VirtualLocation`
174
+ * objects, keyed arbitrarily -- accepted from a raw JMAP write this fake's
175
+ * own client never made, so entries missing a string `uri` are dropped
176
+ * rather than crashing (#16). */
177
+ function virtualLocationsFromWireMap(value) {
178
+ if (!value || typeof value !== 'object')
179
+ return undefined;
180
+ const list = Object.values(value)
181
+ .map((entry) => entry)
182
+ .filter((entry) => typeof entry.uri === 'string')
183
+ .map((entry) => ({
184
+ uri: entry.uri,
185
+ name: typeof entry.name === 'string' ? entry.name : undefined,
186
+ }));
187
+ return list.length > 0 ? list : undefined;
188
+ }
189
+ function virtualLocationsToWireMap(locations) {
190
+ if (!locations)
191
+ return null;
192
+ return Object.fromEntries(locations.map((location, i) => [
193
+ `v${i}`,
194
+ {
195
+ '@type': 'VirtualLocation',
196
+ uri: location.uri,
197
+ ...(location.name === undefined ? {} : { name: location.name }),
198
+ },
199
+ ]));
200
+ }
140
201
  function rolesToMap(roles) {
141
202
  if (!roles)
142
203
  return undefined;
@@ -174,6 +235,33 @@ function normalizeParticipants(input) {
174
235
  }
175
236
  return out;
176
237
  }
238
+ /** The pattern `respond`'s own patch always writes: one participant's
239
+ * `participationStatus`, optionally alongside that same participant's
240
+ * `participationComment` (T11 live capture — the wire name a real server
241
+ * answers to, not JSCalendar's plain `comment`). */
242
+ const REPLY_PATCH_PATH = /^participants\/([^/]+)\/(participationStatus|participationComment)$/;
243
+ /** The participant id an update patch replies for, or `null` when the patch
244
+ * is not shaped like a reply at all — an organiser edit, which may touch
245
+ * anything, including the whole `participants` map in one go. Every key in
246
+ * a genuine reply patch names the *same* participant; a patch that mixes
247
+ * another field in, or touches two participants at once, is an organiser
248
+ * edit and must not be mistaken for one attendee's own answer. */
249
+ function replyParticipantId(patch) {
250
+ const keys = Object.keys(patch);
251
+ if (keys.length === 0)
252
+ return null;
253
+ let id = null;
254
+ for (const key of keys) {
255
+ const match = REPLY_PATCH_PATH.exec(key);
256
+ if (!match)
257
+ return null;
258
+ const participantId = match[1];
259
+ if (id !== null && id !== participantId)
260
+ return null;
261
+ id = participantId;
262
+ }
263
+ return id;
264
+ }
177
265
  /** RFC 6901 §3, for a result reference's path only — none of this fake's own
178
266
  * patch paths need unescaping, since none of its ids ever contain `~`. */
179
267
  function unpointer(segment) {
@@ -255,6 +343,7 @@ export class FakeCalendarStore {
255
343
  location: seedEvent.location,
256
344
  recurrenceRule: seedEvent.recurrenceRule,
257
345
  status: seedEvent.status ?? 'confirmed',
346
+ freeBusyStatus: seedEvent.freeBusyStatus,
258
347
  sequence: 0,
259
348
  });
260
349
  }
@@ -276,7 +365,7 @@ export class FakeCalendarStore {
276
365
  const meId = this.me.accountId;
277
366
  return {
278
367
  capabilities: {
279
- 'urn:ietf:params:jmap:core': {},
368
+ 'urn:ietf:params:jmap:core': { maxCallsInRequest: MAX_CALLS_IN_REQUEST },
280
369
  // Field names confirmed live against Stalwart v0.16.20 (#137).
281
370
  'urn:ietf:params:jmap:calendars': {
282
371
  maxCalendarsPerEvent: 1,
@@ -471,6 +560,17 @@ export class FakeCalendarStore {
471
560
  const expand = args.expandRecurrences === true || filter.expandRecurrences === true;
472
561
  const after = firstString(args.after, filter.after);
473
562
  const before = firstString(args.before, filter.before);
563
+ // `text` -- `searchEvents`'s own filter (issue #17) -- matches a
564
+ // case-insensitive substring of either `title` or `description` in one
565
+ // pass, live-confirmed against Stalwart v0.16.20 (2026-09-21): no
566
+ // `after`/`before` at all is a valid, unbounded query, exactly like the
567
+ // unfiltered listing below.
568
+ const text = typeof filter.text === 'string' ? filter.text.toLowerCase() : undefined;
569
+ const matchesText = (event) => text === undefined ||
570
+ event.title.toLowerCase().includes(text) ||
571
+ (event.description?.toLowerCase().includes(text) ?? false);
572
+ const limit = typeof args.limit === 'number' ? args.limit : undefined;
573
+ const limited = (ids) => (limit === undefined ? ids : ids.slice(0, limit));
474
574
  if (expand) {
475
575
  if (!after || !before) {
476
576
  return {
@@ -482,6 +582,8 @@ export class FakeCalendarStore {
482
582
  const rangeBefore = new Date(before);
483
583
  const ids = [];
484
584
  for (const event of account.events.values()) {
585
+ if (!matchesText(event))
586
+ continue;
485
587
  if (event.recurrenceRule) {
486
588
  for (const start of occurrenceStarts(new Date(`${event.start}Z`), event.recurrenceRule, rangeAfter, rangeBefore)) {
487
589
  // An excluded occurrence is gone from the expansion, which is how
@@ -497,19 +599,33 @@ export class FakeCalendarStore {
497
599
  ids.push(event.id);
498
600
  }
499
601
  }
500
- return { accountId, queryState: 'q1', canCalculateChanges: false, position: 0, ids };
602
+ return {
603
+ accountId,
604
+ queryState: 'q1',
605
+ canCalculateChanges: false,
606
+ position: 0,
607
+ ids: limited(ids),
608
+ };
501
609
  }
502
610
  // Unexpanded: every master event, including a recurring one's own single
503
611
  // id — never one of its occurrences (MSG-053 acceptance criteria).
504
612
  const ids = [...account.events.values()]
505
613
  .filter((event) => {
614
+ if (!matchesText(event))
615
+ return false;
506
616
  if (!after && !before)
507
617
  return true;
508
618
  const start = new Date(`${event.start}Z`);
509
619
  return (!after || start >= new Date(after)) && (!before || start < new Date(before));
510
620
  })
511
621
  .map((event) => event.id);
512
- return { accountId, queryState: 'q1', canCalculateChanges: false, position: 0, ids };
622
+ return {
623
+ accountId,
624
+ queryState: 'q1',
625
+ canCalculateChanges: false,
626
+ position: 0,
627
+ ids: limited(ids),
628
+ };
513
629
  }
514
630
  #eventGet(args) {
515
631
  const accountId = String(args.accountId ?? this.me.accountId);
@@ -533,7 +649,18 @@ export class FakeCalendarStore {
533
649
  notFound.push(id);
534
650
  continue;
535
651
  }
536
- list.push(this.#projectEvent(event));
652
+ list.push({
653
+ ...this.#projectEvent(event),
654
+ // Not part of the shape every caller reads -- only the
655
+ // 'following'-scope cleanup in `calendar-client.ts` asks a master
656
+ // directly for its own overrides, to exclude one a rule truncation
657
+ // just stranded past its new `until`. An occurrence's own get
658
+ // (`#projectOccurrence`, which never reaches this branch) has no
659
+ // business echoing the whole map back.
660
+ ...(event.recurrenceOverrides
661
+ ? { recurrenceOverrides: { ...event.recurrenceOverrides } }
662
+ : {}),
663
+ });
537
664
  }
538
665
  return { accountId, state: 'e1', list, notFound };
539
666
  }
@@ -553,12 +680,27 @@ export class FakeCalendarStore {
553
680
  // for MSG-055 to confirm live).
554
681
  showWithoutTime: event.isAllDay,
555
682
  locations: locationToWireMap(event.location),
683
+ virtualLocations: virtualLocationsToWireMap(event.virtualLocations),
556
684
  recurrenceRule: event.recurrenceRule ? { ...event.recurrenceRule } : null,
557
685
  participants: event.participants
558
686
  ? Object.fromEntries(Object.entries(event.participants).map(([id, participant]) => [id, { ...participant }]))
559
687
  : null,
688
+ alerts: event.alerts
689
+ ? Object.fromEntries(Object.entries(event.alerts).map(([id, alert]) => [id, { ...alert }]))
690
+ : null,
691
+ links: event.links
692
+ ? Object.fromEntries(Object.entries(event.links).map(([id, link]) => [id, { ...link }]))
693
+ : null,
560
694
  status: event.status,
695
+ freeBusyStatus: event.freeBusyStatus ?? null,
561
696
  sequence: event.sequence,
697
+ // Every event's own get carries this, equal to its own id when the
698
+ // event is not an occurrence -- live-confirmed against Stalwart
699
+ // v0.16.20 (wtfalch/calendar#14; corrects `types.ts`'s
700
+ // `CalendarEvent.baseEventId` doc comment, which had claimed it was
701
+ // absent on a master). `#projectOccurrence` overwrites this with the
702
+ // real master's id for an occurrence.
703
+ baseEventId: event.id,
562
704
  };
563
705
  }
564
706
  /** A synthetic per-occurrence id, distinct from the master's — real
@@ -572,12 +714,20 @@ export class FakeCalendarStore {
572
714
  #projectOccurrence(master, id, iso) {
573
715
  const override = master.recurrenceOverrides?.[this.#overrideKey(iso)] ?? {};
574
716
  const { excluded: _excluded, '@type': _type, ...fields } = override;
717
+ // Both in `start`'s own local, offset-free shape (no milliseconds, no
718
+ // trailing `Z`) -- live-confirmed against Stalwart v0.16.20
719
+ // (wtfalch/calendar#14). `recurrenceId` used to keep `iso`'s raw
720
+ // `Date#toISOString()` form (milliseconds and a trailing `Z`), which
721
+ // disagreed with `start` on the very same occurrence and, worse, wasn't
722
+ // even the shape `truncateSeriesBefore`'s own `until` arithmetic expects
723
+ // for the value it reads back through `getEvent`.
724
+ const local = iso.slice(0, 19);
575
725
  return {
576
726
  ...this.#projectEvent(master),
577
727
  id,
578
728
  baseEventId: master.id,
579
- recurrenceId: iso,
580
- start: iso.slice(0, 19),
729
+ recurrenceId: local,
730
+ start: local,
581
731
  recurrenceRule: null,
582
732
  ...fields,
583
733
  };
@@ -623,6 +773,20 @@ export class FakeCalendarStore {
623
773
  notUpdated[id] = { type: 'notFound' };
624
774
  continue;
625
775
  }
776
+ if (replyParticipantId(patch) !== null) {
777
+ // `respond` only ever targets a real event id, never an
778
+ // occurrence's synthetic one -- and a reply against one is refused
779
+ // outright, live-confirmed against Stalwart v0.16.20 for T11
780
+ // (https://github.com/wtfalch/calendar/issues/11). The fake used to
781
+ // silently write a `recurrenceOverrides` entry instead, which no
782
+ // live run ever produced.
783
+ notUpdated[id] = {
784
+ type: 'invalidProperties',
785
+ description: 'Multiple organizers found in iCalendar object',
786
+ properties: ['participants'],
787
+ };
788
+ continue;
789
+ }
626
790
  this.#writeOverride(master, split.iso, patch);
627
791
  updated[id] = null;
628
792
  continue;
@@ -632,7 +796,19 @@ export class FakeCalendarStore {
632
796
  notUpdated[id] = { type: 'notFound' };
633
797
  continue;
634
798
  }
799
+ // A reply -- `respond`'s own patch shape -- bumps nothing, on either
800
+ // side, but only when it comes from someone other than this copy's own
801
+ // organiser: T11 live re-capture found the organiser sending this exact
802
+ // shape on her own event is an ordinary organiser edit (`sequence`
803
+ // absent/0 -> 1 on every copy, the whole map mirrored), not a reply.
804
+ const replyId = replyParticipantId(patch);
635
805
  this.#applyPatch(event, patch);
806
+ if (replyId !== null && !this.#isOrganiser(accountId, event)) {
807
+ updated[id] = null;
808
+ if (sendScheduling)
809
+ this.#propagateReply(accountId, event, replyId);
810
+ continue;
811
+ }
636
812
  event.sequence += 1;
637
813
  updated[id] = null;
638
814
  if (sendScheduling)
@@ -690,9 +866,13 @@ export class FakeCalendarStore {
690
866
  isAllDay: Boolean(draft.showWithoutTime ?? draft.isAllDay),
691
867
  location: firstLocationName(draft.locations) ??
692
868
  (typeof draft.location === 'string' ? draft.location : undefined),
869
+ virtualLocations: virtualLocationsFromWireMap(draft.virtualLocations),
693
870
  recurrenceRule: draft.recurrenceRule,
694
871
  participants: normalizeParticipants(draft.participants),
872
+ alerts: draft.alerts,
873
+ links: draft.links,
695
874
  status: draft.status ?? 'confirmed',
875
+ freeBusyStatus: draft.freeBusyStatus,
696
876
  sequence: 0,
697
877
  };
698
878
  }
@@ -729,10 +909,29 @@ export class FakeCalendarStore {
729
909
  this.invitesSent.push({ accountId: inviteeId, eventId: copyId, uid: event.uid });
730
910
  }
731
911
  }
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"). */
912
+ /** Whether `accountId` holds this copy's own `owner` role -- the
913
+ * distinction between a reply and an organiser edit that merely looks
914
+ * like one. A `participants/<id>/participationStatus`-shaped patch is a
915
+ * reply only when it comes from someone other than the organiser:
916
+ * live re-confirmed for T11
917
+ * (https://github.com/wtfalch/calendar/issues/11) that the organiser
918
+ * sending that exact shape on her own event is an ordinary edit --
919
+ * `sequence` goes from absent/0 to `1` on every copy, and the whole
920
+ * `participants` map mirrors, the same as any other organiser write. */
921
+ #isOrganiser(accountId, event) {
922
+ const owner = Object.values(event.participants ?? {}).find((p) => p.roles?.owner === true);
923
+ if (!owner)
924
+ return false;
925
+ const ownerAccountId = this.#emailToAccountId.get(owner.calendarAddress.replace(/^mailto:/i, '').toLowerCase());
926
+ return ownerAccountId === accountId;
927
+ }
928
+ /** Mirror this copy's whole `participants` map onto every other copy
929
+ * sharing the same `uid`, in any account — the shared scheduling engine
930
+ * real Stalwart runs underneath both CalDAV and JMAP (#145: "the reply
931
+ * reached alice... with no action on her part"). Every organiser edit
932
+ * takes this path, including one shaped exactly like a reply
933
+ * (`#isOrganiser` above); `#propagateReply` below is the narrower path an
934
+ * attendee's own `respond` takes. */
736
935
  #propagateStatus(fromAccountId, event) {
737
936
  for (const [accountId, account] of this.#accounts) {
738
937
  if (accountId === fromAccountId)
@@ -746,6 +945,36 @@ export class FakeCalendarStore {
746
945
  }
747
946
  }
748
947
  }
948
+ /** A reply — `respond`'s own patch shape — carries only the one
949
+ * participant's new `participationStatus` to every other copy sharing the
950
+ * same `uid`, matched by address rather than by map key: a copy's own key
951
+ * for the same person need not match another's. Two things `#propagateStatus`
952
+ * above does that this deliberately does not: it never bumps `sequence`,
953
+ * anywhere, and it never carries `participationComment` along —
954
+ * live-confirmed for T11, a comment sent alongside a status change never
955
+ * reached the organiser's own copy, so it must stay this replier's alone. */
956
+ #propagateReply(fromAccountId, event, participantId) {
957
+ const mine = event.participants?.[participantId];
958
+ if (!mine)
959
+ return;
960
+ for (const [accountId, account] of this.#accounts) {
961
+ if (accountId === fromAccountId)
962
+ continue;
963
+ for (const other of account.events.values()) {
964
+ if (other.uid !== event.uid || !other.participants)
965
+ continue;
966
+ const entry = Object.entries(other.participants).find(([, p]) => p.calendarAddress === mine.calendarAddress);
967
+ if (!entry)
968
+ continue;
969
+ const [otherId, existing] = entry;
970
+ other.participants = {
971
+ ...other.participants,
972
+ [otherId]: { ...existing, participationStatus: mine.participationStatus },
973
+ };
974
+ this.repliesSent.push({ accountId, eventId: other.id, uid: event.uid });
975
+ }
976
+ }
977
+ }
749
978
  #applyPatch(event, patch) {
750
979
  for (const [path, value] of Object.entries(patch)) {
751
980
  if (path.startsWith('participants/')) {
@@ -794,6 +1023,9 @@ export class FakeCalendarStore {
794
1023
  else if (path === 'locations') {
795
1024
  event.location = firstLocationName(value);
796
1025
  }
1026
+ else if (path === 'virtualLocations') {
1027
+ event.virtualLocations = virtualLocationsFromWireMap(value);
1028
+ }
797
1029
  else if (path === 'duration') {
798
1030
  event.duration = String(value);
799
1031
  }
@@ -803,9 +1035,26 @@ export class FakeCalendarStore {
803
1035
  else if (path === 'recurrenceRule') {
804
1036
  event.recurrenceRule = value;
805
1037
  }
1038
+ else if (path.startsWith('recurrenceOverrides/')) {
1039
+ // A rule truncation for 'following' scope excludes a stranded future
1040
+ // override in the same write that shortens the rule
1041
+ // (`calendar-client.ts`'s `truncateSeriesBefore`) -- keys are always
1042
+ // a plain `recurrenceId` string, never containing `~` or `/`, so
1043
+ // this needs none of `shareWith`'s RFC 6901 unescaping.
1044
+ this.#writeOverride(event, path.slice('recurrenceOverrides/'.length), value);
1045
+ }
1046
+ else if (path === 'alerts') {
1047
+ event.alerts = value;
1048
+ }
1049
+ else if (path === 'links') {
1050
+ event.links = value;
1051
+ }
806
1052
  else if (path === 'status') {
807
1053
  event.status = value;
808
1054
  }
1055
+ else if (path === 'freeBusyStatus') {
1056
+ event.freeBusyStatus = value;
1057
+ }
809
1058
  // Anything else is accepted and ignored: this fake supports only the
810
1059
  // patch paths this package's own client sends.
811
1060
  }
@@ -815,18 +1064,22 @@ export class FakeCalendarStore {
815
1064
  * answers empty (#145 amendment, contradicting #137's original
816
1065
  * two-rights claim).
817
1066
  *
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`. */
1067
+ * The principal being asked about is a separate `id` argument, not the
1068
+ * method's own `accountId` — an earlier slice assumed the latter, on the
1069
+ * theory that `Principal/getAvailability` reads a *different* account the
1070
+ * way a shared-mailbox read does. Live testing for issue #13 found the
1071
+ * opposite: `accountId` is the *caller's* own account (this fake only
1072
+ * ever authenticates one session, so it is always `this.me.accountId`
1073
+ * and is not otherwise read here), and the range travels as
1074
+ * `utcStart`/`utcEnd` — `after`/`before` is kept as a fallback only
1075
+ * because nothing yet proves every caller has been updated to the real
1076
+ * names. The response, too, carries no `accountId` at all on the real
1077
+ * server (`test/availability-many.test.ts`'s pinned transcript). */
825
1078
  #getAvailability(args) {
826
1079
  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);
1080
+ const principalId = String(args.id ?? args.accountId ?? '');
1081
+ const after = firstString(args.utcStart, args.after);
1082
+ const before = firstString(args.utcEnd, args.before);
830
1083
  const rangeAfter = after ? new Date(after) : new Date(0);
831
1084
  const rangeBefore = before ? new Date(before) : new Date(8_640_000_000_000_000);
832
1085
  const account = this.#accounts.get(principalId);
@@ -841,10 +1094,15 @@ export class FakeCalendarStore {
841
1094
  }
842
1095
  }
843
1096
  periods.sort((a, b) => (a.utcStart < b.utcStart ? -1 : 1));
844
- return { accountId: principalId, list: periods };
1097
+ return { list: periods };
845
1098
  }
846
1099
  #periodsForEvent(event, rangeAfter, rangeBefore) {
847
- if (event.status === 'cancelled')
1100
+ // A cancelled event never counted as busy; an event explicitly marked
1101
+ // 'free' (wtfalch/calendar#29) is the same case for a different reason --
1102
+ // its owner said outright that it should never produce a false conflict
1103
+ // in findTime(). Absent reads as 'busy', matching `wire.ts`'s own
1104
+ // `eventFromWire` default.
1105
+ if (event.status === 'cancelled' || event.freeBusyStatus === 'free')
848
1106
  return [];
849
1107
  const busyStatus = event.status === 'tentative' ? 'tentative' : 'confirmed';
850
1108
  const durationMs = minutesFromDuration(event.duration) * 60_000;
@@ -894,6 +1152,19 @@ export class FakeCalendarStore {
894
1152
  return json(this.session(new URL(url).origin));
895
1153
  }
896
1154
  const body = JSON.parse(String(init.body));
1155
+ if (body.methodCalls.length > MAX_CALLS_IN_REQUEST) {
1156
+ // The whole request is refused, before a single call in it runs --
1157
+ // measured live for issue #13, pinned as `LIVE_LIMIT_REFUSAL` in
1158
+ // `test/wire-live-transcript.test.ts`. A client that stops chunking
1159
+ // (or chunks to the wrong number) hits this the moment a fake-backed
1160
+ // test asks for more than `MAX_CALLS_IN_REQUEST` principals at once.
1161
+ return new Response(JSON.stringify({
1162
+ type: 'urn:ietf:params:jmap:error:limit',
1163
+ status: 400,
1164
+ detail: 'The request exceeds the maximum number of calls in a single request.',
1165
+ limit: 'maxCallsInRequest',
1166
+ }), { status: 400, headers: { 'Content-Type': 'application/json' } });
1167
+ }
897
1168
  const responses = [];
898
1169
  for (const [method, callArgs, id] of body.methodCalls) {
899
1170
  const resolved = this.#resolveRefs(callArgs, responses);
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The pure slot search behind `CalendarClient.findTime` (issue #13). No
3
+ * network and no server-shaped types here — just merging busy periods and
4
+ * walking the gaps between them, so the search itself is testable without a
5
+ * connection at all.
6
+ */
7
+ import type { AvailabilityResult, CalendarRange, WorkingHours } from './types.ts';
8
+ /** Every slot at least `duration` long where every *known* principal in
9
+ * `answers` is free. An unparseable `duration` (`wire.ts`'s
10
+ * `parseDurationMs` returning `null`) answers no slots rather than
11
+ * throwing — the same "do not crash a whole read over one bad value"
12
+ * discipline `availabilityFromWire` already follows. `principalIds` is
13
+ * only consulted when `workingHours` is a per-principal map, to know which
14
+ * principals besides `answers`' own keys (an unknown principal still gets
15
+ * its own working day considered, even with no busy periods to merge in)
16
+ * need one (wtfalch/calendar#31). */
17
+ export declare function findFreeSlots(answers: ReadonlyMap<string, AvailabilityResult>, range: CalendarRange, duration: string, workingHours: boolean | ReadonlyMap<string, WorkingHours>, principalIds?: readonly string[]): readonly CalendarRange[];