@remit/backend 0.0.90 → 0.0.91

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remit/backend",
3
- "version": "0.0.90",
3
+ "version": "0.0.91",
4
4
  "description": "Remit Mail Inspector API backend",
5
5
  "license": "MIT",
6
6
  "author": "",
@@ -58,6 +58,7 @@
58
58
  "dependencies": {
59
59
  "@remit/config-format": "*",
60
60
  "@remit/config-transfer": "*",
61
+ "@remit/calendar-service": "*",
61
62
  "@remit/data-ports": "*",
62
63
  "@remit/domain-enums": "*",
63
64
  "@remit/api-openapi-types": "*",
@@ -0,0 +1,668 @@
1
+ import type {
2
+ CalendarEventInstance,
3
+ CalendarEventResponse,
4
+ CalendarFreeBusySpan,
5
+ CreateCalendarEventInput,
6
+ UpdateCalendarEventInput,
7
+ } from "@remit/api-openapi-types";
8
+ import {
9
+ applyScopedDelete,
10
+ applyScopedUpdate,
11
+ buildEventCalendar,
12
+ type CalendarEventFields,
13
+ type CalendarInstance,
14
+ type CalendarWindow,
15
+ deleteCalendarObject,
16
+ listBusySpans,
17
+ listCalendarInstances,
18
+ parseCalendar,
19
+ projectCalendar,
20
+ putCalendarObject,
21
+ type RecurrenceScopeValue,
22
+ type ScopedWrite,
23
+ toOffsetIso,
24
+ toUtcIso,
25
+ } from "@remit/calendar-service";
26
+ import type {
27
+ CalendarCollectionItem,
28
+ CalendarObjectItem,
29
+ } from "@remit/data-ports";
30
+ import { base36uuid } from "@remit/data-ports/id";
31
+ import { RecurrenceScope } from "@remit/domain-enums";
32
+ import type { APIGatewayProxyEvent } from "aws-lambda";
33
+ import { getAccountConfigIdFromEvent } from "../auth.js";
34
+ import { getClient } from "../service/data-client.js";
35
+ import type {
36
+ CalendarEventDetailOperationIds,
37
+ CalendarEventOperationIds,
38
+ CalendarFreeBusyOperationIds,
39
+ OperationHandler,
40
+ } from "../types.js";
41
+ import {
42
+ badRequest,
43
+ type CalendarDeps,
44
+ type CalendarOutcome,
45
+ calendarDepsOf,
46
+ findCalendarFor,
47
+ listCalendarsFor,
48
+ notFound,
49
+ preconditionFailed,
50
+ refuseCalendar,
51
+ } from "./calendar.js";
52
+
53
+ /**
54
+ * The widest window a single read may ask for. A year covers every view the
55
+ * client has — a year grid is the coarsest — and keeps one request from asking
56
+ * the server to expand a decade of a daily series.
57
+ */
58
+ export const CALENDAR_MAX_WINDOW_DAYS = 366;
59
+
60
+ const MAX_WINDOW_MS = CALENDAR_MAX_WINDOW_DAYS * 24 * 60 * 60 * 1000;
61
+
62
+ /** Mints the id a new resource is named and identified by. */
63
+ export interface CalendarEventDeps extends CalendarDeps {
64
+ newId: () => string;
65
+ now: () => Date;
66
+ }
67
+
68
+ export const calendarEventDepsOf = (deps: CalendarDeps): CalendarEventDeps => ({
69
+ ...deps,
70
+ newId: base36uuid,
71
+ now: () => new Date(),
72
+ });
73
+
74
+ /**
75
+ * Reads the window a listing asked for.
76
+ *
77
+ * Both ends must carry an offset, because a window with no offset names no
78
+ * span of time — and a client whose `from` was read an hour out gets an
79
+ * apparently empty morning rather than an error.
80
+ */
81
+ export const readWindow = (
82
+ from: unknown,
83
+ to: unknown,
84
+ ): CalendarOutcome<CalendarWindow> => {
85
+ if (typeof from !== "string" || typeof to !== "string") {
86
+ return refuseCalendar(
87
+ "InvalidWindow",
88
+ "a listing needs both `from` and `to`",
89
+ );
90
+ }
91
+ const fromMs = Date.parse(from);
92
+ const toMs = Date.parse(to);
93
+ if (Number.isNaN(fromMs) || Number.isNaN(toMs)) {
94
+ return refuseCalendar(
95
+ "InvalidWindow",
96
+ "`from` and `to` must be ISO 8601 date-times with a zone offset",
97
+ );
98
+ }
99
+ if (toMs <= fromMs) {
100
+ return refuseCalendar("InvalidWindow", "`to` must come after `from`");
101
+ }
102
+ if (toMs - fromMs > MAX_WINDOW_MS) {
103
+ return refuseCalendar(
104
+ "InvalidWindow",
105
+ `a window may cover at most ${CALENDAR_MAX_WINDOW_DAYS} days`,
106
+ );
107
+ }
108
+ return { ok: true, value: { from: toUtcIso(fromMs), to: toUtcIso(toMs) } };
109
+ };
110
+
111
+ /** The collections a listing covers, defaulting to every one the caller holds. */
112
+ export const collectionsForListing = async (
113
+ deps: CalendarDeps,
114
+ accountConfigId: string,
115
+ calendarIds: string[],
116
+ ): Promise<CalendarOutcome<CalendarCollectionItem[]>> => {
117
+ const held = await listCalendarsFor(deps, accountConfigId);
118
+ if (calendarIds.length === 0) return { ok: true, value: held };
119
+
120
+ const selected = held.filter((collection) =>
121
+ calendarIds.includes(collection.calendarId),
122
+ );
123
+ const missing = calendarIds.find(
124
+ (calendarId) =>
125
+ !held.some((collection) => collection.calendarId === calendarId),
126
+ );
127
+ if (missing) {
128
+ return refuseCalendar("NotFound", `no calendar ${missing} on this account`);
129
+ }
130
+ return { ok: true, value: selected };
131
+ };
132
+
133
+ const toInstanceResponse = (
134
+ instance: CalendarInstance,
135
+ ): CalendarEventInstance => ({
136
+ calendarId: instance.calendarId,
137
+ calendarObjectId: instance.calendarObjectId,
138
+ recurrenceId: instance.recurrenceId,
139
+ icalUid: instance.icalUid,
140
+ summary: instance.summary,
141
+ start: instance.start,
142
+ end: instance.end,
143
+ allDay: instance.allDay,
144
+ status: instance.status,
145
+ transparency: instance.transparency,
146
+ zoneCertainty: instance.zoneCertainty,
147
+ etag: instance.etag,
148
+ hasRecurrence: instance.hasRecurrence,
149
+ });
150
+
151
+ const toEventResponse = (
152
+ object: CalendarObjectItem,
153
+ ): CalendarEventResponse => ({
154
+ calendarObjectId: object.calendarObjectId,
155
+ calendarId: object.calendarId,
156
+ resourceName: object.resourceName,
157
+ icalUid: object.icalUid,
158
+ icalData: object.icalData,
159
+ etag: object.etag,
160
+ sequence: object.sequence,
161
+ syncSequence: object.syncSequence,
162
+ summary: object.summary,
163
+ dtStart: object.dtStart,
164
+ dtEnd: object.dtEnd,
165
+ allDay: object.allDay,
166
+ zoneCertainty: object.zoneCertainty,
167
+ status: object.status,
168
+ transparency: object.transparency,
169
+ hasRecurrence: object.hasRecurrence,
170
+ expandedThrough: object.expandedThrough,
171
+ createdAt: object.createdAt,
172
+ updatedAt: object.updatedAt,
173
+ });
174
+
175
+ const eventFieldsOf = (
176
+ input: CreateCalendarEventInput,
177
+ ): CalendarEventFields => ({
178
+ summary: input.summary,
179
+ description: input.description ?? "",
180
+ location: input.location ?? "",
181
+ start: input.start,
182
+ end: input.end,
183
+ allDay: input.allDay ?? false,
184
+ timeZone: input.timeZone ?? "",
185
+ status: input.status ?? "Confirmed",
186
+ transparency: input.transparency ?? "Opaque",
187
+ recurrenceRule: input.recurrenceRule ?? "",
188
+ });
189
+
190
+ /**
191
+ * Reduce a PATCH body to the event fields an update may set, preserving
192
+ * absence: a body carrying only `summary` yields only `summary`, and the
193
+ * resource's times are then left exactly as they were.
194
+ */
195
+ export const pickEventUpdate = (
196
+ body: Partial<UpdateCalendarEventInput>,
197
+ ): Partial<CalendarEventFields> => {
198
+ const patch: Partial<CalendarEventFields> = {};
199
+ const fields = [
200
+ "summary",
201
+ "description",
202
+ "location",
203
+ "start",
204
+ "end",
205
+ "allDay",
206
+ "timeZone",
207
+ "status",
208
+ "transparency",
209
+ "recurrenceRule",
210
+ ] as const;
211
+ for (const field of fields) {
212
+ if (!Object.hasOwn(body, field)) continue;
213
+ Object.assign(patch, { [field]: body[field] });
214
+ }
215
+ return patch;
216
+ };
217
+
218
+ /**
219
+ * Whether an `If-Match` header lets the write through.
220
+ *
221
+ * No header is no precondition, which is what HTTP says and what a first-party
222
+ * client that just read the resource wants. `*` matches any existing resource.
223
+ * Quotes and a weak-validator prefix are transport spelling and are stripped
224
+ * before comparing, because the stored tag carries neither.
225
+ */
226
+ export const etagMatches = (
227
+ ifMatch: string | undefined,
228
+ etag: string,
229
+ ): boolean => {
230
+ if (ifMatch === undefined || ifMatch === "") return true;
231
+ return ifMatch
232
+ .split(",")
233
+ .map((candidate) => candidate.trim().replace(/^W\//, "").replace(/"/g, ""))
234
+ .some((candidate) => candidate === "*" || candidate === etag);
235
+ };
236
+
237
+ /**
238
+ * An absent scope means the whole series, which is what a client editing an
239
+ * event that does not recur sends. A scope that is present but not one of the
240
+ * three is refused rather than read as `All`: the widest, most destructive
241
+ * reading is the worst possible answer to a typo.
242
+ */
243
+ export const readScope = (
244
+ value: unknown,
245
+ ): CalendarOutcome<RecurrenceScopeValue> => {
246
+ if (value === undefined || value === "") {
247
+ return { ok: true, value: RecurrenceScope.All };
248
+ }
249
+ if (
250
+ value === RecurrenceScope.This ||
251
+ value === RecurrenceScope.Following ||
252
+ value === RecurrenceScope.All
253
+ ) {
254
+ return { ok: true, value };
255
+ }
256
+ return refuseCalendar(
257
+ "InvalidScope",
258
+ `scope must be one of This, Following or All, and this request sent "${String(value)}"`,
259
+ );
260
+ };
261
+
262
+ /**
263
+ * Writes what a scoped edit resolved to.
264
+ *
265
+ * A split is two resources and one write set: the truncated original and the
266
+ * remainder land together or not at all, because half a split is a series the
267
+ * user sees twice or not at all.
268
+ */
269
+ export const commitScopedWrite = async (
270
+ deps: CalendarEventDeps,
271
+ accountConfigId: string,
272
+ object: CalendarObjectItem,
273
+ collectionTimezone: string,
274
+ write: ScopedWrite,
275
+ ): Promise<CalendarOutcome<CalendarObjectItem | null>> => {
276
+ if (write.kind === "Delete") {
277
+ await deleteCalendarObject(deps.calendarUnitOfWork, {
278
+ accountConfigId,
279
+ calendarId: object.calendarId,
280
+ calendarObjectId: object.calendarObjectId,
281
+ });
282
+ return { ok: true, value: null };
283
+ }
284
+
285
+ // Both resources are read before either is written. A refusal returned from
286
+ // inside the write set would commit it — the truncated head alone, with the
287
+ // remainder of the series gone — so nothing that can be refused is left
288
+ // inside it, and a refusal from the write path there is a broken invariant
289
+ // rather than an outcome.
290
+ const checked = await Promise.all(
291
+ [write.icalData, ...(write.kind === "Split" ? [write.following] : [])].map(
292
+ (icalData) => readWritableCalendar(icalData, collectionTimezone),
293
+ ),
294
+ );
295
+ const refused = checked.find((result) => !result.ok);
296
+ if (refused && !refused.ok) return refused;
297
+
298
+ return deps.calendarUnitOfWork.transaction(async () => {
299
+ const head = await putCalendarObject(deps.calendarUnitOfWork, {
300
+ accountConfigId,
301
+ calendarId: object.calendarId,
302
+ resourceName: object.resourceName,
303
+ icalData: write.icalData,
304
+ });
305
+ if (!head.ok) throw refusedAfterValidation(head.error.code);
306
+ if (write.kind === "Replace") return { ok: true, value: head.value };
307
+
308
+ const following = await putCalendarObject(deps.calendarUnitOfWork, {
309
+ accountConfigId,
310
+ calendarId: object.calendarId,
311
+ resourceName: `${deps.newId()}.ics`,
312
+ icalData: write.following,
313
+ });
314
+ if (!following.ok) throw refusedAfterValidation(following.error.code);
315
+ // The remainder is what the patch applied to, and it lives under an id the
316
+ // caller has never seen — returning the truncated head instead would leave
317
+ // them holding the resource their edit is not in.
318
+ return { ok: true, value: following.value };
319
+ });
320
+ };
321
+
322
+ const refusedAfterValidation = (code: string): Error =>
323
+ new Error(
324
+ `the calendar write path refused text this request had already validated (${code})`,
325
+ );
326
+
327
+ /** Reads a resource the same way the write path will, without writing it. */
328
+ const readWritableCalendar = async (
329
+ icalData: string,
330
+ collectionTimezone: string,
331
+ ): Promise<CalendarOutcome<null>> => {
332
+ const parsed = await parseCalendar(icalData);
333
+ if (!parsed.ok) return parsed;
334
+ const projected = projectCalendar(parsed.value, collectionTimezone);
335
+ if (!projected.ok) return projected;
336
+ return { ok: true, value: null };
337
+ };
338
+
339
+ export const createCalendarEventFor = async (
340
+ deps: CalendarEventDeps,
341
+ accountConfigId: string,
342
+ input: CreateCalendarEventInput,
343
+ ): Promise<CalendarOutcome<CalendarObjectItem>> => {
344
+ const collection = await findCalendarFor(
345
+ deps,
346
+ accountConfigId,
347
+ input.calendarId,
348
+ );
349
+ if (!collection.ok) return collection;
350
+
351
+ const id = deps.newId();
352
+ const built = await buildEventCalendar(
353
+ eventFieldsOf(input),
354
+ `${id}@reader.remit`,
355
+ deps.now(),
356
+ );
357
+ if (!built.ok) return built;
358
+
359
+ return putCalendarObject(deps.calendarUnitOfWork, {
360
+ accountConfigId,
361
+ calendarId: collection.value.calendarId,
362
+ resourceName: `${id}.ics`,
363
+ icalData: built.value,
364
+ });
365
+ };
366
+
367
+ export interface ScopedRequest {
368
+ calendarId: string;
369
+ calendarObjectId: string;
370
+ scope: RecurrenceScopeValue;
371
+ recurrenceId: string;
372
+ ifMatch: string | undefined;
373
+ }
374
+
375
+ interface ResolvedResource {
376
+ collection: CalendarCollectionItem;
377
+ object: CalendarObjectItem;
378
+ }
379
+
380
+ const resolveResource = async (
381
+ deps: CalendarEventDeps,
382
+ accountConfigId: string,
383
+ request: Pick<ScopedRequest, "calendarId" | "calendarObjectId">,
384
+ ): Promise<CalendarOutcome<ResolvedResource>> => {
385
+ const collection = await findCalendarFor(
386
+ deps,
387
+ accountConfigId,
388
+ request.calendarId,
389
+ );
390
+ if (!collection.ok) return collection;
391
+
392
+ const object = await deps.calendarObject.find(
393
+ request.calendarId,
394
+ request.calendarObjectId,
395
+ );
396
+ if (!object) {
397
+ return refuseCalendar(
398
+ "NotFound",
399
+ `no event ${request.calendarObjectId} in this calendar`,
400
+ );
401
+ }
402
+ return { ok: true, value: { collection: collection.value, object } };
403
+ };
404
+
405
+ export const updateCalendarEventFor = async (
406
+ deps: CalendarEventDeps,
407
+ accountConfigId: string,
408
+ request: ScopedRequest,
409
+ patch: Partial<CalendarEventFields>,
410
+ ): Promise<CalendarOutcome<CalendarObjectItem | null>> => {
411
+ const resolved = await resolveResource(deps, accountConfigId, request);
412
+ if (!resolved.ok) return resolved;
413
+ const { collection, object } = resolved.value;
414
+
415
+ if (!etagMatches(request.ifMatch, object.etag)) {
416
+ return refuseCalendar(
417
+ "EtagMismatch",
418
+ "this event has been written since you read it — read it again and reapply the change",
419
+ );
420
+ }
421
+
422
+ const parsed = await parseCalendar(object.icalData);
423
+ if (!parsed.ok) {
424
+ throw new Error(
425
+ `stored calendar object ${object.calendarObjectId} no longer parses: ${parsed.error.message}`,
426
+ );
427
+ }
428
+
429
+ const write = await applyScopedUpdate(
430
+ parsed.value,
431
+ collection.timezone,
432
+ {
433
+ scope: request.scope,
434
+ recurrenceId: request.recurrenceId,
435
+ followingUid: `${deps.newId()}@reader.remit`,
436
+ },
437
+ patch,
438
+ );
439
+ if (!write.ok) return write;
440
+ return commitScopedWrite(
441
+ deps,
442
+ accountConfigId,
443
+ object,
444
+ collection.timezone,
445
+ write.value,
446
+ );
447
+ };
448
+
449
+ export const deleteCalendarEventFor = async (
450
+ deps: CalendarEventDeps,
451
+ accountConfigId: string,
452
+ request: ScopedRequest,
453
+ ): Promise<CalendarOutcome<CalendarObjectItem | null>> => {
454
+ const resolved = await resolveResource(deps, accountConfigId, request);
455
+ if (!resolved.ok) return resolved;
456
+ const { collection, object } = resolved.value;
457
+
458
+ if (!etagMatches(request.ifMatch, object.etag)) {
459
+ return refuseCalendar(
460
+ "EtagMismatch",
461
+ "this event has been written since you read it — read it again and reapply the change",
462
+ );
463
+ }
464
+
465
+ const parsed = await parseCalendar(object.icalData);
466
+ if (!parsed.ok) {
467
+ throw new Error(
468
+ `stored calendar object ${object.calendarObjectId} no longer parses: ${parsed.error.message}`,
469
+ );
470
+ }
471
+
472
+ const write = await applyScopedDelete(parsed.value, collection.timezone, {
473
+ scope: request.scope,
474
+ recurrenceId: request.recurrenceId,
475
+ followingUid: "",
476
+ });
477
+ if (!write.ok) return write;
478
+ return commitScopedWrite(
479
+ deps,
480
+ accountConfigId,
481
+ object,
482
+ collection.timezone,
483
+ write.value,
484
+ );
485
+ };
486
+
487
+ const readCalendarIds = (value: unknown): string[] => {
488
+ if (typeof value === "string") return value === "" ? [] : [value];
489
+ if (Array.isArray(value)) return value.filter((id) => typeof id === "string");
490
+ return [];
491
+ };
492
+
493
+ const answerRefusal = (error: { code: string; message: string }) =>
494
+ error.code === "NotFound"
495
+ ? notFound(error.message)
496
+ : error.code === "EtagMismatch"
497
+ ? preconditionFailed(error.message)
498
+ : badRequest(error);
499
+
500
+ const scopedRequestOf = (
501
+ context: Parameters<OperationHandler>[0],
502
+ ): CalendarOutcome<ScopedRequest> => {
503
+ const params = context.request.params as { calendarObjectId: string };
504
+ const query = context.request.query as {
505
+ calendarId?: string;
506
+ scope?: string;
507
+ recurrenceId?: string;
508
+ };
509
+ const scope = readScope(query.scope);
510
+ if (!scope.ok) return scope;
511
+
512
+ const headers = (context.request.headers ?? {}) as Record<string, string>;
513
+ const ifMatch = Object.entries(headers).find(
514
+ ([name]) => name.toLowerCase() === "if-match",
515
+ )?.[1];
516
+ return {
517
+ ok: true,
518
+ value: {
519
+ calendarId: query.calendarId ?? "",
520
+ calendarObjectId: params.calendarObjectId,
521
+ scope: scope.value,
522
+ recurrenceId: query.recurrenceId ?? "",
523
+ ifMatch,
524
+ },
525
+ };
526
+ };
527
+
528
+ export const CalendarEventOperations: Record<
529
+ CalendarEventOperationIds,
530
+ OperationHandler<CalendarEventOperationIds>
531
+ > = {
532
+ CalendarEventOperations_listCalendarEvents: async (
533
+ context,
534
+ ...args: unknown[]
535
+ ) => {
536
+ const event = args[0] as APIGatewayProxyEvent;
537
+ const accountConfigId = getAccountConfigIdFromEvent(event);
538
+ const query = context.request.query as {
539
+ from?: string;
540
+ to?: string;
541
+ calendarId?: string | string[];
542
+ };
543
+ const window = readWindow(query.from, query.to);
544
+ if (!window.ok) return badRequest(window.error);
545
+
546
+ const deps = calendarDepsOf(await getClient());
547
+ const collections = await collectionsForListing(
548
+ deps,
549
+ accountConfigId,
550
+ readCalendarIds(query.calendarId),
551
+ );
552
+ if (!collections.ok) return answerRefusal(collections.error);
553
+
554
+ const instances = await listCalendarInstances(
555
+ deps,
556
+ collections.value,
557
+ window.value,
558
+ );
559
+ return { items: instances.map(toInstanceResponse) };
560
+ },
561
+
562
+ CalendarEventOperations_createCalendarEvent: async (
563
+ context,
564
+ ...args: unknown[]
565
+ ) => {
566
+ const event = args[0] as APIGatewayProxyEvent;
567
+ const accountConfigId = getAccountConfigIdFromEvent(event);
568
+ const input = context.request.requestBody as CreateCalendarEventInput;
569
+ const deps = calendarEventDepsOf(calendarDepsOf(await getClient()));
570
+
571
+ const created = await createCalendarEventFor(deps, accountConfigId, input);
572
+ if (!created.ok) return answerRefusal(created.error);
573
+ return toEventResponse(created.value);
574
+ },
575
+ };
576
+
577
+ export const CalendarEventDetailOperations: Record<
578
+ CalendarEventDetailOperationIds,
579
+ OperationHandler<CalendarEventDetailOperationIds>
580
+ > = {
581
+ CalendarEventDetailOperations_getCalendarEvent: async (
582
+ context,
583
+ ...args: unknown[]
584
+ ) => {
585
+ const event = args[0] as APIGatewayProxyEvent;
586
+ const accountConfigId = getAccountConfigIdFromEvent(event);
587
+ const request = scopedRequestOf(context);
588
+ if (!request.ok) return badRequest(request.error);
589
+ const deps = calendarEventDepsOf(calendarDepsOf(await getClient()));
590
+
591
+ const resolved = await resolveResource(
592
+ deps,
593
+ accountConfigId,
594
+ request.value,
595
+ );
596
+ if (!resolved.ok) return answerRefusal(resolved.error);
597
+ return toEventResponse(resolved.value.object);
598
+ },
599
+
600
+ CalendarEventDetailOperations_updateCalendarEvent: async (
601
+ context,
602
+ ...args: unknown[]
603
+ ) => {
604
+ const event = args[0] as APIGatewayProxyEvent;
605
+ const accountConfigId = getAccountConfigIdFromEvent(event);
606
+ const body = context.request
607
+ .requestBody as Partial<UpdateCalendarEventInput>;
608
+ const request = scopedRequestOf(context);
609
+ if (!request.ok) return badRequest(request.error);
610
+ const deps = calendarEventDepsOf(calendarDepsOf(await getClient()));
611
+
612
+ const updated = await updateCalendarEventFor(
613
+ deps,
614
+ accountConfigId,
615
+ request.value,
616
+ pickEventUpdate(body),
617
+ );
618
+ if (!updated.ok) return answerRefusal(updated.error);
619
+ if (!updated.value) {
620
+ throw new Error("a scoped update resolved to a delete");
621
+ }
622
+ return toEventResponse(updated.value);
623
+ },
624
+
625
+ CalendarEventDetailOperations_deleteCalendarEvent: async (
626
+ context,
627
+ ...args: unknown[]
628
+ ) => {
629
+ const event = args[0] as APIGatewayProxyEvent;
630
+ const accountConfigId = getAccountConfigIdFromEvent(event);
631
+ const request = scopedRequestOf(context);
632
+ if (!request.ok) return badRequest(request.error);
633
+ const deps = calendarEventDepsOf(calendarDepsOf(await getClient()));
634
+
635
+ const removed = await deleteCalendarEventFor(
636
+ deps,
637
+ accountConfigId,
638
+ request.value,
639
+ );
640
+ if (!removed.ok) return answerRefusal(removed.error);
641
+ return { statusCode: 204 };
642
+ },
643
+ };
644
+
645
+ export const CalendarFreeBusyOperations: Record<
646
+ CalendarFreeBusyOperationIds,
647
+ OperationHandler<CalendarFreeBusyOperationIds>
648
+ > = {
649
+ CalendarFreeBusyOperations_listCalendarFreeBusy: async (
650
+ context,
651
+ ...args: unknown[]
652
+ ) => {
653
+ const event = args[0] as APIGatewayProxyEvent;
654
+ const accountConfigId = getAccountConfigIdFromEvent(event);
655
+ const query = context.request.query as { from?: string; to?: string };
656
+ const window = readWindow(query.from, query.to);
657
+ if (!window.ok) return badRequest(window.error);
658
+
659
+ const deps = calendarDepsOf(await getClient());
660
+ const collections = await listCalendarsFor(deps, accountConfigId);
661
+ const spans = await listBusySpans(deps, collections, window.value);
662
+ const items: CalendarFreeBusySpan[] = spans.map((span) => ({
663
+ start: toOffsetIso(span.startMs, "UTC"),
664
+ end: toOffsetIso(span.endMs, "UTC"),
665
+ }));
666
+ return { items };
667
+ },
668
+ };