@wtfalch/calendar 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/calendar/calendar-client.js +574 -19
- package/dist/calendar/calendar.css +13 -0
- package/dist/calendar/client.d.ts +27 -0
- package/dist/calendar/client.js +101 -0
- package/dist/calendar/fake/sample.d.ts +2 -1
- package/dist/calendar/fake/store.d.ts +51 -8
- package/dist/calendar/fake/store.js +539 -47
- package/dist/calendar/find-time.d.ts +17 -0
- package/dist/calendar/find-time.js +198 -0
- package/dist/calendar/ics.d.ts +73 -0
- package/dist/calendar/ics.js +586 -0
- package/dist/calendar/index.d.ts +3 -1
- package/dist/calendar/index.js +1 -0
- package/dist/calendar/react/Calendar.js +36 -27
- package/dist/calendar/react/EventDetail.js +22 -1
- package/dist/calendar/react/EventEditor.js +65 -3
- package/dist/calendar/types.d.ts +550 -17
- package/dist/calendar/wire.d.ts +161 -5
- package/dist/calendar/wire.js +304 -4
- package/package.json +2 -2
|
@@ -5,9 +5,11 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { CalendarConnection } from "./client.js";
|
|
7
7
|
import { guard } from "./errors.js";
|
|
8
|
+
import { findFreeSlots } from "./find-time.js";
|
|
9
|
+
import { icsToEventDrafts } from "./ics.js";
|
|
8
10
|
import { push } from "./push.js";
|
|
9
11
|
import { CalendarError } from "./types.js";
|
|
10
|
-
import { CALENDAR_GET_PROPERTIES, EVENT_GET_PROPERTIES, availabilityFromWire, calendarFromWire, draftToWire, eventFromWire, patchToWire, principalFromWire, 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";
|
|
11
13
|
/** The first refusal in a `notCreated`/`notUpdated`/`notDestroyed` map, or
|
|
12
14
|
* `undefined` when the operation actually succeeded. */
|
|
13
15
|
function firstRefusal(errors) {
|
|
@@ -52,6 +54,43 @@ async function listEvents(connection, range) {
|
|
|
52
54
|
return result.list.map((wire) => eventFromWire(wire));
|
|
53
55
|
});
|
|
54
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* One `query` across every calendar this account holds, `options.range`
|
|
59
|
+
* optional -- the fix for Agora issue #216 (one search box over Mail, Chat
|
|
60
|
+
* and Calendar; https://github.com/wtfalch/agora/issues/216), which
|
|
61
|
+
* `listEvents(range)` alone could not answer without the caller guessing a
|
|
62
|
+
* range and filtering client-side.
|
|
63
|
+
*
|
|
64
|
+
* Sends a single `filter: {text: query}` -- live-confirmed against Stalwart
|
|
65
|
+
* v0.16.20 (2026-09-21) to match a case-insensitive substring of either
|
|
66
|
+
* `title` or `description` in one pass, so this never has to OR two filters
|
|
67
|
+
* together. `after`/`before` are added, with `expandRecurrences: true`,
|
|
68
|
+
* only when the caller names `options.range` -- mirroring `listEvents`
|
|
69
|
+
* exactly, because the server refuses to expand recurrences with no bounds
|
|
70
|
+
* at all (`invalidArguments`, live-confirmed). With no range, a matching
|
|
71
|
+
* recurring event's own master id comes back unexpanded, the same fallback
|
|
72
|
+
* `CalendarEvent/query` uses for any other unexpanded query -- there is no
|
|
73
|
+
* bound to expand against, so this is the only answer the server can give.
|
|
74
|
+
*/
|
|
75
|
+
async function searchEvents(connection, query, options) {
|
|
76
|
+
return guard('events.search', async () => {
|
|
77
|
+
const accountId = await connection.accountId();
|
|
78
|
+
const range = options?.range;
|
|
79
|
+
const args = {
|
|
80
|
+
accountId,
|
|
81
|
+
filter: range ? { text: query, after: range.after, before: range.before } : { text: query },
|
|
82
|
+
};
|
|
83
|
+
if (range)
|
|
84
|
+
args.expandRecurrences = true;
|
|
85
|
+
if (options?.limit !== undefined)
|
|
86
|
+
args.limit = options.limit;
|
|
87
|
+
const queryResult = await connection.request('CalendarEvent/query', args);
|
|
88
|
+
if (queryResult.ids.length === 0)
|
|
89
|
+
return [];
|
|
90
|
+
const result = await connection.request('CalendarEvent/get', { accountId, ids: queryResult.ids, properties: EVENT_GET_PROPERTIES });
|
|
91
|
+
return result.list.map((wire) => eventFromWire(wire));
|
|
92
|
+
});
|
|
93
|
+
}
|
|
55
94
|
async function getEvent(connection, id) {
|
|
56
95
|
return guard('events.get', async () => {
|
|
57
96
|
const accountId = await connection.accountId();
|
|
@@ -66,6 +105,66 @@ async function getEvent(connection, id) {
|
|
|
66
105
|
return eventFromWire(wire);
|
|
67
106
|
});
|
|
68
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
|
+
}
|
|
69
168
|
async function createEvent(connection, calendarId, event, options) {
|
|
70
169
|
return guard('events.create', async () => {
|
|
71
170
|
const accountId = await connection.accountId();
|
|
@@ -93,12 +192,40 @@ async function createEvent(connection, calendarId, event, options) {
|
|
|
93
192
|
return getEvent(connection, created.id);
|
|
94
193
|
});
|
|
95
194
|
}
|
|
96
|
-
|
|
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
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* `updateEvent`'s original body, unscoped: the patch lands on whatever `id`
|
|
213
|
+
* was given. This is also what `scope: 'occurrence'` means (a synthetic
|
|
214
|
+
* occurrence id already writes an occurrence-scoped override,
|
|
215
|
+
* `wire.ts`'s `WireEvent.recurrenceOverrides` doc comment) and what an
|
|
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.
|
|
222
|
+
*/
|
|
223
|
+
async function updateEventDirect(connection, id, patch, options, extraWire) {
|
|
97
224
|
return guard('events.update', async () => {
|
|
98
225
|
const accountId = await connection.accountId();
|
|
99
226
|
const result = await connection.request('CalendarEvent/set', {
|
|
100
227
|
accountId,
|
|
101
|
-
update: { [id]: patchToWire(patch) },
|
|
228
|
+
update: { [id]: { ...patchToWire(patch), ...extraWire } },
|
|
102
229
|
sendSchedulingMessages: options?.sendSchedulingMessages ?? false,
|
|
103
230
|
});
|
|
104
231
|
const refused = firstRefusal(result.notUpdated);
|
|
@@ -111,7 +238,8 @@ async function updateEvent(connection, id, patch, options) {
|
|
|
111
238
|
return getEvent(connection, id);
|
|
112
239
|
});
|
|
113
240
|
}
|
|
114
|
-
|
|
241
|
+
/** `deleteEvent`'s original body, unscoped -- see `updateEventDirect`. */
|
|
242
|
+
async function deleteEventDirect(connection, id, options) {
|
|
115
243
|
return guard('events.delete', async () => {
|
|
116
244
|
const accountId = await connection.accountId();
|
|
117
245
|
const result = await connection.request('CalendarEvent/set', {
|
|
@@ -128,6 +256,383 @@ async function deleteEvent(connection, id, options) {
|
|
|
128
256
|
}
|
|
129
257
|
});
|
|
130
258
|
}
|
|
259
|
+
// ---------------------------------------------------------------------------
|
|
260
|
+
// RecurrenceScope: 'series' and 'following'
|
|
261
|
+
// ---------------------------------------------------------------------------
|
|
262
|
+
//
|
|
263
|
+
// Live-confirmed against Stalwart v0.16.20 for wtfalch/calendar#14. Every
|
|
264
|
+
// event's own `CalendarEvent/get` -- master, non-recurring, or occurrence --
|
|
265
|
+
// carries `baseEventId`; on anything that is not an occurrence it equals the
|
|
266
|
+
// event's own `id` (`types.ts`'s `CalendarEvent.baseEventId` doc comment, the
|
|
267
|
+
// comment this ticket corrected). So `event.baseEventId ?? id` always names
|
|
268
|
+
// the top-level event to address for 'series', whether `id` was already that
|
|
269
|
+
// event or a synthetic occurrence id. `recurrenceId`'s presence, not
|
|
270
|
+
// `baseEventId`'s, is what tells an occurrence from a master.
|
|
271
|
+
//
|
|
272
|
+
// 'following' has no server verb at all. The standard way -- and the only
|
|
273
|
+
// one two live captures (`.plans/issue-14.md`) found -- is a rule truncation
|
|
274
|
+
// on the old master plus a new event carrying the change, both ordinary
|
|
275
|
+
// `CalendarEvent/set` calls.
|
|
276
|
+
/** The event `EVENT_GET_PROPERTIES` fetches, plus the one property only
|
|
277
|
+
* 'following' needs: the master's own per-occurrence overrides, so one
|
|
278
|
+
* stranded past a truncated rule can be excluded in the same write that
|
|
279
|
+
* truncates it (`truncateSeriesBefore`). Not part of the public contract --
|
|
280
|
+
* `recurrenceOverrides` never reaches `eventFromWire`. */
|
|
281
|
+
const MASTER_GET_PROPERTIES = [...EVENT_GET_PROPERTIES, 'recurrenceOverrides'];
|
|
282
|
+
async function getRawEvent(connection, accountId, id, operation) {
|
|
283
|
+
const result = await connection.request('CalendarEvent/get', { accountId, ids: [id], properties: MASTER_GET_PROPERTIES });
|
|
284
|
+
const wire = result.list[0];
|
|
285
|
+
if (!wire) {
|
|
286
|
+
throw new CalendarError(`no event ${id} on this account`, { type: 'notFound', operation });
|
|
287
|
+
}
|
|
288
|
+
return wire;
|
|
289
|
+
}
|
|
290
|
+
/** More than any IANA zone's real offset from UTC (the widest today is
|
|
291
|
+
* UTC-12 to UTC+14), so padding a query window by this much on both sides,
|
|
292
|
+
* after naively treating a local wall-clock string as UTC, can never leave
|
|
293
|
+
* the true occurrence at either edge outside the window -- whatever the
|
|
294
|
+
* event's actual `timeZone` shifts it by, DST included. */
|
|
295
|
+
const MAX_ZONE_OFFSET_MS = 26 * 60 * 60 * 1_000;
|
|
296
|
+
/**
|
|
297
|
+
* How many of `masterId`'s own occurrences fall strictly before `before`
|
|
298
|
+
* (`seriesStart`'s and `before`'s own shape: a local wall-clock
|
|
299
|
+
* `recurrenceId`, no offset) -- asked of `CalendarEvent/query`'s own
|
|
300
|
+
* expansion rather than counted by re-running the rule here, which would be
|
|
301
|
+
* exactly the RRULE expansion this package's client carries none of
|
|
302
|
+
* (`PRODUCT.md` "Stack"; `no-rrule-dependency.test.ts`). Only
|
|
303
|
+
* `updateFollowing`'s `count` case needs this -- an `until` bound or an
|
|
304
|
+
* unbounded rule carries over to the forward series untouched.
|
|
305
|
+
*
|
|
306
|
+
* **The query's own `after`/`before` only pick a wide net, not the answer.**
|
|
307
|
+
* They are built by treating `seriesStart`/`before` as if they were already
|
|
308
|
+
* UTC and padding by `MAX_ZONE_OFFSET_MS`, which is correct only as a
|
|
309
|
+
* "definitely wide enough" bound -- this package has no timezone library to
|
|
310
|
+
* turn a local wall-clock string plus an IANA name into the real UTC instant
|
|
311
|
+
* the server itself uses to filter (wtfalch/calendar#14 follow-up: a fixed
|
|
312
|
+
* one-second pad here, naively treated as UTC, silently dropped the true
|
|
313
|
+
* first occurrence in any zone but UTC, and dropped or added a whole
|
|
314
|
+
* occurrence across a DST change -- live-confirmed in `Europe/Oslo`,
|
|
315
|
+
* `.plans/issue-14.md`). What actually decides "elapsed" is a plain string
|
|
316
|
+
* comparison of each candidate's own `recurrenceId` against `before` -- both
|
|
317
|
+
* are wall-clock strings in the *same* zone, since they are occurrences of
|
|
318
|
+
* the same series, so lexicographic order on the fixed-width
|
|
319
|
+
* `YYYY-MM-DDTHH:mm:ss` shape already is chronological order, with no Date
|
|
320
|
+
* arithmetic and so no zone to get wrong.
|
|
321
|
+
*/
|
|
322
|
+
async function countElapsedOccurrences(connection, accountId, masterId, seriesStart, before) {
|
|
323
|
+
const after = new Date(new Date(`${seriesStart}Z`).getTime() - MAX_ZONE_OFFSET_MS).toISOString();
|
|
324
|
+
const wideBefore = new Date(new Date(`${before}Z`).getTime() + MAX_ZONE_OFFSET_MS).toISOString();
|
|
325
|
+
const query = await connection.request('CalendarEvent/query', { accountId, filter: { after, before: wideBefore }, expandRecurrences: true });
|
|
326
|
+
if (query.ids.length === 0)
|
|
327
|
+
return 0;
|
|
328
|
+
const result = await connection.request('CalendarEvent/get', {
|
|
329
|
+
accountId,
|
|
330
|
+
ids: [...query.ids],
|
|
331
|
+
properties: ['id', 'baseEventId', 'recurrenceId'],
|
|
332
|
+
});
|
|
333
|
+
return result.list.filter((event) => event.baseEventId === masterId && (event.recurrenceId ?? '') < before).length;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* End `masterId`'s rule the instant before `splitIso` (`occurrence.start`'s
|
|
337
|
+
* own local shape, no offset) -- one second earlier, rather than the exact
|
|
338
|
+
* previous occurrence's own date, because the server accepts any boundary,
|
|
339
|
+
* not only one that lands on a real occurrence, and that spares this
|
|
340
|
+
* package working an interval backwards itself (live-confirmed).
|
|
341
|
+
*
|
|
342
|
+
* Any override `masterWire` already carries at or after `splitIso` is
|
|
343
|
+
* excluded in the same write. Left alone, Stalwart keeps answering it past
|
|
344
|
+
* the rule's own new `until` (live-confirmed, `.plans/issue-14.md`) -- an
|
|
345
|
+
* "ended" series that still has an occurrence on it, which would break the
|
|
346
|
+
* one thing 'following' promises. This is the Decision the ticket asks for
|
|
347
|
+
* on an override past the split: dropped, not carried to the new series,
|
|
348
|
+
* because carrying it over would mean this package reading back every
|
|
349
|
+
* future occurrence to notice which ones differ from the plain rule, then
|
|
350
|
+
* re-keying each one against the new master -- a second `recurrenceRule`
|
|
351
|
+
* problem stacked on the one this function already solves.
|
|
352
|
+
*/
|
|
353
|
+
async function truncateSeriesBefore(connection, accountId, masterId, masterWire, splitIso, sendSchedulingMessages, operation) {
|
|
354
|
+
const rule = masterWire.recurrenceRule;
|
|
355
|
+
if (!rule) {
|
|
356
|
+
throw new CalendarError(`event ${masterId} carries no recurrence rule`, {
|
|
357
|
+
type: 'invalidArguments',
|
|
358
|
+
operation,
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
const boundary = new Date(new Date(`${splitIso}Z`).getTime() - 1_000).toISOString().slice(0, 19);
|
|
362
|
+
// Every descriptive part of the rule (byDay, byMonthDay, bySetPosition,
|
|
363
|
+
// firstDayOfWeek, ...) carries over unchanged; only the bound changes,
|
|
364
|
+
// from whatever `count`/`until` the rule had to the new `until` boundary
|
|
365
|
+
// (wtfalch/calendar#27 -- carrying only frequency/interval here is what
|
|
366
|
+
// dropped every other part on a split).
|
|
367
|
+
const parsed = recurrenceRuleFromWire(rule);
|
|
368
|
+
if (!parsed) {
|
|
369
|
+
throw new CalendarError(`event ${masterId} carries no recurrence rule`, {
|
|
370
|
+
type: 'invalidArguments',
|
|
371
|
+
operation,
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
const { count: _count, until: _until, ...truncatedParts } = parsed;
|
|
375
|
+
const truncated = { ...truncatedParts, until: boundary };
|
|
376
|
+
const wire = patchToWire({ recurrenceRule: truncated });
|
|
377
|
+
for (const [key, override] of Object.entries(masterWire.recurrenceOverrides ?? {})) {
|
|
378
|
+
if (key >= splitIso && override?.excluded !== true) {
|
|
379
|
+
wire[`recurrenceOverrides/${key}`] = { excluded: true };
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
const result = await connection.request('CalendarEvent/set', { accountId, update: { [masterId]: wire }, sendSchedulingMessages });
|
|
383
|
+
const refused = firstRefusal(result.notUpdated);
|
|
384
|
+
if (refused) {
|
|
385
|
+
throw new CalendarError(refused.description ?? 'the server refused to end the series there', {
|
|
386
|
+
type: refused.type ?? 'unknown',
|
|
387
|
+
operation,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
/** `occurrence`'s own `recurrenceId`, or a thrown `CalendarError` --
|
|
392
|
+
* 'following' needs a date to split the series at, which only an
|
|
393
|
+
* occurrence has; 'series' has no such requirement (`updateSeries`,
|
|
394
|
+
* `deleteSeries` take a master id just as happily as an occurrence's). */
|
|
395
|
+
function requireOccurrence(event, operation) {
|
|
396
|
+
if (event.recurrenceId === undefined) {
|
|
397
|
+
throw new CalendarError("scope 'following' needs an occurrence id, not a master's", {
|
|
398
|
+
type: 'invalidArguments',
|
|
399
|
+
operation,
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return event.recurrenceId;
|
|
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
|
+
}
|
|
437
|
+
/** 'series': resolve `id` (an occurrence or already the master) to the
|
|
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. */
|
|
449
|
+
async function updateSeries(connection, id, patch, options) {
|
|
450
|
+
return guard('events.update', async () => {
|
|
451
|
+
const event = await getEvent(connection, id);
|
|
452
|
+
const masterId = event.baseEventId ?? id;
|
|
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);
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
async function deleteSeries(connection, id, options) {
|
|
466
|
+
return guard('events.delete', async () => {
|
|
467
|
+
const event = await getEvent(connection, id);
|
|
468
|
+
const masterId = event.baseEventId ?? id;
|
|
469
|
+
return deleteEventDirect(connection, masterId, options);
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* The truncation `updateFollowing` and `deleteFollowing` share: find the
|
|
474
|
+
* occurrence's master, end the master's rule right before it, and hand back
|
|
475
|
+
* everything `updateFollowing` additionally needs to build the forward
|
|
476
|
+
* event -- the master (for its `calendarId`/`recurrenceRule`) and the
|
|
477
|
+
* occurrence itself (for its own, possibly overridden, fields).
|
|
478
|
+
*/
|
|
479
|
+
async function splitBeforeOccurrence(connection, id, sendSchedulingMessages, operation) {
|
|
480
|
+
const accountId = await connection.accountId();
|
|
481
|
+
const occurrence = await getEvent(connection, id);
|
|
482
|
+
const splitIso = requireOccurrence(occurrence, operation);
|
|
483
|
+
const masterId = occurrence.baseEventId ?? id;
|
|
484
|
+
const masterWire = await getRawEvent(connection, accountId, masterId, operation);
|
|
485
|
+
await truncateSeriesBefore(connection, accountId, masterId, masterWire, splitIso, sendSchedulingMessages, operation);
|
|
486
|
+
return { occurrence, master: eventFromWire(masterWire) };
|
|
487
|
+
}
|
|
488
|
+
async function updateFollowing(connection, id, patch, options) {
|
|
489
|
+
return guard('events.update', async () => {
|
|
490
|
+
const sendScheduling = options?.sendSchedulingMessages ?? false;
|
|
491
|
+
const { occurrence, master } = await splitBeforeOccurrence(connection, id, sendScheduling, 'events.update');
|
|
492
|
+
const rule = master.recurrenceRule;
|
|
493
|
+
if (!rule) {
|
|
494
|
+
throw new CalendarError(`event ${master.id} carries no recurrence rule`, {
|
|
495
|
+
type: 'invalidArguments',
|
|
496
|
+
operation: 'events.update',
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
// The new series' own end: an absolute `until` carries over untouched,
|
|
500
|
+
// an unbounded rule stays unbounded, and a relative `count` needs the
|
|
501
|
+
// occurrences already elapsed subtracted off (`countElapsedOccurrences`).
|
|
502
|
+
// Every other part of the rule (byDay, byMonthDay, bySetPosition,
|
|
503
|
+
// firstDayOfWeek, ...) carries over unchanged -- only the bound is
|
|
504
|
+
// recomputed (wtfalch/calendar#27 -- rebuilding from frequency/interval
|
|
505
|
+
// alone here is what dropped every other part on a split).
|
|
506
|
+
const { count: _forwardCount, until: _forwardUntil, ...forwardParts } = rule;
|
|
507
|
+
let forwardRule = { ...forwardParts };
|
|
508
|
+
if (rule.until !== undefined) {
|
|
509
|
+
forwardRule = { ...forwardRule, until: rule.until };
|
|
510
|
+
}
|
|
511
|
+
else if (rule.count !== undefined) {
|
|
512
|
+
const accountId = await connection.accountId();
|
|
513
|
+
// `occurrence.recurrenceId`, not `occurrence.start`: the split point
|
|
514
|
+
// is the occurrence's own scheduled slot in the rule's sequence, which
|
|
515
|
+
// an earlier per-occurrence override could have moved `start` away
|
|
516
|
+
// from without changing which slot it still is.
|
|
517
|
+
const elapsed = await countElapsedOccurrences(connection, accountId, master.id, master.start, occurrence.recurrenceId ?? occurrence.start);
|
|
518
|
+
const remaining = rule.count - elapsed;
|
|
519
|
+
if (remaining <= 0) {
|
|
520
|
+
throw new CalendarError('the chosen occurrence is at or past the end of the series', {
|
|
521
|
+
type: 'invalidArguments',
|
|
522
|
+
operation: 'events.update',
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
forwardRule = { ...forwardRule, count: remaining };
|
|
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
|
+
}
|
|
541
|
+
const { id: _id, recurrenceId: _recurrenceId, baseEventId: _baseEventId, sequence: _sequence, ...occurrenceFields } = occurrence;
|
|
542
|
+
const forwardDraft = {
|
|
543
|
+
...occurrenceFields,
|
|
544
|
+
uid: crypto.randomUUID(),
|
|
545
|
+
...restPatch,
|
|
546
|
+
recurrenceRule: patchedRule ?? forwardRule,
|
|
547
|
+
};
|
|
548
|
+
const forwardCalendarId = patch.calendarId ?? occurrence.calendarId;
|
|
549
|
+
return createEvent(connection, forwardCalendarId, forwardDraft, options);
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
async function deleteFollowing(connection, id, options) {
|
|
553
|
+
return guard('events.delete', async () => {
|
|
554
|
+
// Delete-following is just the truncation (the ticket's own wording) --
|
|
555
|
+
// no new event, so `splitBeforeOccurrence`'s master/occurrence are both
|
|
556
|
+
// unused here beyond the truncation it already performed.
|
|
557
|
+
await splitBeforeOccurrence(connection, id, options?.sendSchedulingMessages ?? false, 'events.delete');
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
async function updateEvent(connection, id, patch, options) {
|
|
561
|
+
const scope = options?.scope;
|
|
562
|
+
if (scope === 'series')
|
|
563
|
+
return updateSeries(connection, id, patch, options);
|
|
564
|
+
if (scope === 'following')
|
|
565
|
+
return updateFollowing(connection, id, patch, options);
|
|
566
|
+
return updateEventDirect(connection, id, patch, options);
|
|
567
|
+
}
|
|
568
|
+
async function deleteEvent(connection, id, options) {
|
|
569
|
+
const scope = options?.scope;
|
|
570
|
+
if (scope === 'series')
|
|
571
|
+
return deleteSeries(connection, id, options);
|
|
572
|
+
if (scope === 'following')
|
|
573
|
+
return deleteFollowing(connection, id, options);
|
|
574
|
+
return deleteEventDirect(connection, id, options);
|
|
575
|
+
}
|
|
576
|
+
/** Whether two calendar addresses name the same person, `mailto:` scheme
|
|
577
|
+
* and case aside -- mirrors `react/participants.ts`'s `sameAddress`, kept
|
|
578
|
+
* as its own copy because the framework-free client must not import from
|
|
579
|
+
* `./react`. */
|
|
580
|
+
function addressMatches(a, b) {
|
|
581
|
+
return a.replace(/^mailto:/i, '').toLowerCase() === b.replace(/^mailto:/i, '').toLowerCase();
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Reply to an invite, as an iTIP REPLY against the caller's own copy -- never
|
|
585
|
+
* `updateEvent`, the organiser's verb (#11). The wire's participant map key
|
|
586
|
+
* is assigned by whoever created the event and is never part of the contract
|
|
587
|
+
* (`wire.ts`'s `participantsToWire` note), so the caller's own entry is found
|
|
588
|
+
* by address, the same way `Calendar.tsx`'s RSVP row already has to. Only
|
|
589
|
+
* that entry's `participationStatus` -- and `participationComment`, when a
|
|
590
|
+
* comment was given, the wire name a live server actually answers to, not
|
|
591
|
+
* JSCalendar's plain `comment` (T11 live capture) -- is patched by JSON
|
|
592
|
+
* Pointer, never the whole `participants` map: live-confirmed against
|
|
593
|
+
* Stalwart v0.16.20 that this changes nothing else, `sequence` included, on
|
|
594
|
+
* the replier's own copy, while the organiser's copy of `participationStatus`
|
|
595
|
+
* updates on its own with no separate write on the organiser's side (T11 live
|
|
596
|
+
* capture, `wire-live-transcript.test.ts`).
|
|
597
|
+
*/
|
|
598
|
+
async function respond(connection, eventId, status, options) {
|
|
599
|
+
return guard('events.respond', async () => {
|
|
600
|
+
const accountId = await connection.accountId();
|
|
601
|
+
const identity = await connection.identity();
|
|
602
|
+
const result = await connection.request('CalendarEvent/get', { accountId, ids: [eventId], properties: ['id', 'participants'] });
|
|
603
|
+
const wire = result.list[0];
|
|
604
|
+
if (!wire) {
|
|
605
|
+
throw new CalendarError(`no event ${eventId} on this account`, {
|
|
606
|
+
type: 'notFound',
|
|
607
|
+
operation: 'events.respond',
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
const entry = Object.entries(wire.participants ?? {}).find(([, participant]) => addressMatches(participant.calendarAddress, identity.calendarAddress));
|
|
611
|
+
if (!entry) {
|
|
612
|
+
throw new CalendarError(`${identity.calendarAddress} is not a participant on event ${eventId}`, {
|
|
613
|
+
type: 'notFound',
|
|
614
|
+
operation: 'events.respond',
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
const [key] = entry;
|
|
618
|
+
const pointer = `participants/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`;
|
|
619
|
+
const patch = { [`${pointer}/participationStatus`]: status };
|
|
620
|
+
if (options?.comment !== undefined)
|
|
621
|
+
patch[`${pointer}/participationComment`] = options.comment;
|
|
622
|
+
const set = await connection.request('CalendarEvent/set', {
|
|
623
|
+
accountId,
|
|
624
|
+
update: { [eventId]: patch },
|
|
625
|
+
sendSchedulingMessages: options?.sendSchedulingMessages ?? false,
|
|
626
|
+
});
|
|
627
|
+
const refused = firstRefusal(set.notUpdated);
|
|
628
|
+
if (refused) {
|
|
629
|
+
throw new CalendarError(refused.description ?? 'the server refused the reply', {
|
|
630
|
+
type: refused.type ?? 'unknown',
|
|
631
|
+
operation: 'events.respond',
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
});
|
|
635
|
+
}
|
|
131
636
|
/**
|
|
132
637
|
* Add or replace one grant in a calendar's `shareWith` ACL, via a JSON
|
|
133
638
|
* Pointer patch on that one grantee rather than replacing the whole map --
|
|
@@ -204,22 +709,66 @@ async function unshareCalendar(connection, calendarId, grantAccountId) {
|
|
|
204
709
|
});
|
|
205
710
|
}
|
|
206
711
|
/**
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
*
|
|
712
|
+
* Every named principal's busy periods over `range`, one JMAP request no
|
|
713
|
+
* matter how many principals — `Principal/getAvailability` batches like any
|
|
714
|
+
* other JMAP method call (RFC 8620 §3.3, measured live for issue #13).
|
|
715
|
+
*
|
|
716
|
+
* **The request shape an earlier slice guessed was wrong.** It sent
|
|
717
|
+
* `{accountId: principalId, after, before}`, on the theory that the method
|
|
718
|
+
* reads a *different* account the way a shared-mailbox read does. Live
|
|
719
|
+
* Stalwart answered `invalidArguments: "Missing principal id"` to that shape
|
|
720
|
+
* on every call. The real shape, measured against the same server: `accountId`
|
|
721
|
+
* is the *caller's own* account, the principal is a separate `id` argument,
|
|
722
|
+
* and the range travels as `utcStart`/`utcEnd`, never `after`/`before` — see
|
|
723
|
+
* `test/availability-many.test.ts` for the pinned transcript.
|
|
724
|
+
*
|
|
725
|
+
* A principal's own refusal (a malformed id, a transient server error) reads
|
|
726
|
+
* the same as no share at all: `'unknown'`, not a thrown error that would
|
|
727
|
+
* take every other principal in the batch down with it — one more way of not
|
|
728
|
+
* being able to see somebody, the same discipline
|
|
729
|
+
* `AvailabilityRibbon`/`Calendar.tsx` already apply to a failed read.
|
|
214
730
|
*/
|
|
215
|
-
async function getAvailability(connection,
|
|
731
|
+
async function getAvailability(connection, principalIds, range) {
|
|
216
732
|
return guard('availability.get', async () => {
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
733
|
+
const answers = new Map();
|
|
734
|
+
const uniqueIds = [...new Set(principalIds)];
|
|
735
|
+
if (uniqueIds.length === 0)
|
|
736
|
+
return answers;
|
|
737
|
+
const callerAccountId = await connection.accountId();
|
|
738
|
+
const results = await connection.requestMany(uniqueIds.map((id) => ({
|
|
739
|
+
id,
|
|
740
|
+
method: 'Principal/getAvailability',
|
|
741
|
+
args: { accountId: callerAccountId, id, utcStart: range.after, utcEnd: range.before },
|
|
742
|
+
})));
|
|
743
|
+
for (const principalId of uniqueIds) {
|
|
744
|
+
const outcome = results.get(principalId);
|
|
745
|
+
const list = outcome && 'data' in outcome
|
|
746
|
+
? (outcome.data.list ?? [])
|
|
747
|
+
: [];
|
|
748
|
+
const periods = availabilityFromWire(list);
|
|
749
|
+
// An empty list is the server's one answer to three different truths
|
|
750
|
+
// (never shared, shared then revoked, shared and genuinely free) --
|
|
751
|
+
// `AvailabilityResult`'s doc comment. It is never read as "known and
|
|
752
|
+
// free".
|
|
753
|
+
answers.set(principalId, periods.length > 0 ? { kind: 'known', periods } : { kind: 'unknown' });
|
|
754
|
+
}
|
|
755
|
+
return answers;
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Slots at least `duration` long where every principal in `principalIds`
|
|
760
|
+
* that `getAvailability` could read is free. The search itself
|
|
761
|
+
* (`find-time.ts`'s `findFreeSlots`) is pure and only ever sees `'known'`
|
|
762
|
+
* answers — an unknown principal is reported in `FindTimeResult.unknown`,
|
|
763
|
+
* never treated as free (issue #13).
|
|
764
|
+
*/
|
|
765
|
+
async function findTime(connection, principalIds, range, duration, options) {
|
|
766
|
+
return guard('availability.findTime', async () => {
|
|
767
|
+
const uniqueIds = [...new Set(principalIds)];
|
|
768
|
+
const answers = await getAvailability(connection, uniqueIds, range);
|
|
769
|
+
const unknown = uniqueIds.filter((id) => answers.get(id)?.kind !== 'known');
|
|
770
|
+
const slots = findFreeSlots(answers, range, duration, options?.workingHours ?? false, uniqueIds);
|
|
771
|
+
return { slots, unknown };
|
|
223
772
|
});
|
|
224
773
|
}
|
|
225
774
|
export function createCalendarClient(options) {
|
|
@@ -228,15 +777,21 @@ export function createCalendarClient(options) {
|
|
|
228
777
|
identity: () => guard('client.identity', () => connection.identity()),
|
|
229
778
|
listCalendars: () => listCalendars(connection),
|
|
230
779
|
listEvents: (range) => listEvents(connection, range),
|
|
780
|
+
searchEvents: (query, options) => searchEvents(connection, query, options),
|
|
231
781
|
getEvent: (id) => getEvent(connection, id),
|
|
232
782
|
createEvent: (calendarId, event, options) => createEvent(connection, calendarId, event, options),
|
|
783
|
+
importIcs: (calendarId, ics) => importIcs(connection, calendarId, ics),
|
|
233
784
|
updateEvent: (id, patch, options) => updateEvent(connection, id, patch, options),
|
|
234
785
|
deleteEvent: (id, options) => deleteEvent(connection, id, options),
|
|
786
|
+
respond: (eventId, status, options) => respond(connection, eventId, status, options),
|
|
235
787
|
shareCalendar: (calendarId, grant) => shareCalendar(connection, calendarId, grant),
|
|
236
788
|
resolvePrincipal: (email) => resolvePrincipal(connection, email),
|
|
237
789
|
lookupPrincipals: (accountIds) => lookupPrincipals(connection, accountIds),
|
|
238
790
|
unshareCalendar: (calendarId, accountId) => unshareCalendar(connection, calendarId, accountId),
|
|
239
|
-
getAvailability: (
|
|
791
|
+
getAvailability: (principalIds, range) => getAvailability(connection, principalIds, range),
|
|
792
|
+
findTime: (principalIds, range, duration, findOptions) => findTime(connection, principalIds, range, duration, findOptions),
|
|
240
793
|
subscribe: (handler) => push(connection, handler),
|
|
794
|
+
changes: (changesOptions) => changes(connection, changesOptions),
|
|
795
|
+
getEventProjections: (ids) => getEventProjections(connection, ids),
|
|
241
796
|
};
|
|
242
797
|
}
|