@mshindi-labs/google 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +7 -4
  2. package/dist/calendar.cjs +1641 -0
  3. package/dist/calendar.cjs.map +1 -0
  4. package/dist/calendar.d.cts +161 -0
  5. package/dist/calendar.d.ts +161 -0
  6. package/dist/calendar.js +1641 -0
  7. package/dist/calendar.js.map +1 -0
  8. package/dist/{chunk-JVP7HHFU.js → chunk-4V5ZJNPI.js} +2 -2
  9. package/dist/{chunk-KJPQ3DMR.cjs → chunk-6PMJ6VB6.cjs} +6 -6
  10. package/dist/{chunk-KJPQ3DMR.cjs.map → chunk-6PMJ6VB6.cjs.map} +1 -1
  11. package/dist/{chunk-SIDO26T7.js → chunk-6RDWEYXZ.js} +11 -4
  12. package/dist/chunk-6RDWEYXZ.js.map +1 -0
  13. package/dist/chunk-AMBBE4TW.js +56 -0
  14. package/dist/chunk-AMBBE4TW.js.map +1 -0
  15. package/dist/{chunk-VN5VWVCT.cjs → chunk-DPAPYMB3.cjs} +63 -56
  16. package/dist/chunk-DPAPYMB3.cjs.map +1 -0
  17. package/dist/{chunk-RWT25QHA.js → chunk-FCHXM22B.js} +45 -3
  18. package/dist/{chunk-RWT25QHA.js.map → chunk-FCHXM22B.js.map} +1 -1
  19. package/dist/{chunk-V22QP2AM.cjs → chunk-JDA3ZRUY.cjs} +3 -3
  20. package/dist/{chunk-V22QP2AM.cjs.map → chunk-JDA3ZRUY.cjs.map} +1 -1
  21. package/dist/{chunk-SHDP4A3A.cjs → chunk-JZVDD4DL.cjs} +44 -2
  22. package/dist/chunk-JZVDD4DL.cjs.map +1 -0
  23. package/dist/chunk-S357VL5V.cjs +56 -0
  24. package/dist/chunk-S357VL5V.cjs.map +1 -0
  25. package/dist/{chunk-Z7O6GO3C.js → chunk-SXD5K23S.js} +2 -2
  26. package/dist/core.cjs +30 -18
  27. package/dist/core.cjs.map +1 -1
  28. package/dist/core.d.cts +23 -4
  29. package/dist/core.d.ts +23 -4
  30. package/dist/core.js +16 -4
  31. package/dist/core.js.map +1 -1
  32. package/dist/{create-google-CPGcK-3G.d.cts → create-google-Bo8_Nc1C.d.cts} +2 -1
  33. package/dist/{create-google-nP9f9jd9.d.ts → create-google-snvkHaEk.d.ts} +2 -1
  34. package/dist/{events-BsWOMtza.d.ts → events-BlC10ISp.d.cts} +31 -0
  35. package/dist/{events-BsWOMtza.d.cts → events-BlC10ISp.d.ts} +31 -0
  36. package/dist/gmail.cjs +48 -75
  37. package/dist/gmail.cjs.map +1 -1
  38. package/dist/gmail.d.cts +2 -2
  39. package/dist/gmail.d.ts +2 -2
  40. package/dist/gmail.js +15 -42
  41. package/dist/gmail.js.map +1 -1
  42. package/dist/postgres.cjs +8 -8
  43. package/dist/postgres.d.cts +1 -1
  44. package/dist/postgres.d.ts +1 -1
  45. package/dist/postgres.js +1 -1
  46. package/dist/testing.cjs +226 -13
  47. package/dist/testing.cjs.map +1 -1
  48. package/dist/testing.d.cts +91 -2
  49. package/dist/testing.d.ts +91 -2
  50. package/dist/testing.js +216 -3
  51. package/dist/testing.js.map +1 -1
  52. package/dist/transport-DHApc5oq.d.cts +103 -0
  53. package/dist/transport-DHApc5oq.d.ts +103 -0
  54. package/package.json +19 -4
  55. package/dist/chunk-SHDP4A3A.cjs.map +0 -1
  56. package/dist/chunk-SIDO26T7.js.map +0 -1
  57. package/dist/chunk-VN5VWVCT.cjs.map +0 -1
  58. /package/dist/{chunk-JVP7HHFU.js.map → chunk-4V5ZJNPI.js.map} +0 -0
  59. /package/dist/{chunk-Z7O6GO3C.js.map → chunk-SXD5K23S.js.map} +0 -0
@@ -0,0 +1,1641 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ var _chunkS357VL5Vcjs = require('./chunk-S357VL5V.cjs');
10
+
11
+
12
+
13
+ var _chunkDPAPYMB3cjs = require('./chunk-DPAPYMB3.cjs');
14
+
15
+
16
+ var _chunkJDA3ZRUYcjs = require('./chunk-JDA3ZRUY.cjs');
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+ var _chunkJZVDD4DLcjs = require('./chunk-JZVDD4DL.cjs');
29
+
30
+ // src/calendar/service.ts
31
+ var _crypto = require('crypto');
32
+
33
+ // src/calendar/ids.ts
34
+
35
+ var B32HEX = "0123456789abcdefghijklmnopqrstuv";
36
+ function base32hex(bytes) {
37
+ let out = "";
38
+ let bits = 0;
39
+ let acc = 0;
40
+ for (const byte of bytes) {
41
+ acc = acc << 8 | byte;
42
+ bits += 8;
43
+ while (bits >= 5) {
44
+ out += B32HEX[acc >>> bits - 5 & 31];
45
+ bits -= 5;
46
+ }
47
+ acc &= (1 << bits) - 1;
48
+ }
49
+ if (bits > 0) out += B32HEX[acc << 5 - bits & 31];
50
+ return out;
51
+ }
52
+ function deriveEventId(tenantId, organizerEmail, idempotencyKey) {
53
+ const digest = _crypto.createHash.call(void 0, "sha256").update(
54
+ `mshindi-google/v1|${tenantId}|${organizerEmail.toLowerCase()}|${idempotencyKey}`,
55
+ "utf8"
56
+ ).digest();
57
+ return base32hex(digest).slice(0, 32);
58
+ }
59
+ function fingerprint(e) {
60
+ const attendees = e.attendees.map((a) => [a.email.toLowerCase(), a.optional]).sort((x, y) => x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0);
61
+ const meeting = e.meeting.type === "in_person" ? { type: "in_person", location: e.meeting.location } : { type: "google_meet" };
62
+ const canonical = JSON.stringify({
63
+ start: e.start.toISOString(),
64
+ end: e.end.toISOString(),
65
+ timeZone: e.timeZone,
66
+ title: e.title,
67
+ description: e.description,
68
+ meeting,
69
+ guestsCanSeeOtherGuests: e.guestsCanSeeOtherGuests,
70
+ attendees
71
+ });
72
+ return _crypto.createHash.call(void 0, "sha256").update(canonical, "utf8").digest("hex").slice(0, 32);
73
+ }
74
+
75
+ // src/calendar/retry.ts
76
+ var CalendarUnauthorizedSignal = class extends Error {
77
+ constructor() {
78
+ super("Google rejected the access token (401)");
79
+ this.name = "CalendarUnauthorizedSignal";
80
+ }
81
+ };
82
+ var DuplicateEventSignal = class extends Error {
83
+ constructor() {
84
+ super("Event already exists (409)");
85
+ this.name = "DuplicateEventSignal";
86
+ }
87
+ };
88
+ var EventGoneSignal = class extends Error {
89
+ constructor() {
90
+ super("Event not found or deleted (404/410)");
91
+ this.name = "EventGoneSignal";
92
+ }
93
+ };
94
+ var PreconditionFailedSignal = class extends Error {
95
+ constructor() {
96
+ super("Event changed since it was read (412)");
97
+ this.name = "PreconditionFailedSignal";
98
+ }
99
+ };
100
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
101
+ "ENOTFOUND",
102
+ "EAI_AGAIN",
103
+ "ECONNREFUSED",
104
+ "ECONNRESET",
105
+ "ETIMEDOUT",
106
+ "ESOCKETTIMEDOUT"
107
+ ]);
108
+ var RATE_REASONS = /* @__PURE__ */ new Set(["rateLimitExceeded", "userRateLimitExceeded"]);
109
+ function classifyCalendarError(err) {
110
+ if (err instanceof _chunkJZVDD4DLcjs.GoogleLibError) return { kind: "fail", error: err };
111
+ const e = _chunkS357VL5Vcjs.asErr.call(void 0, err);
112
+ const status = _chunkS357VL5Vcjs.readStatus.call(void 0, e);
113
+ const reason = _chunkS357VL5Vcjs.readReason.call(void 0, e);
114
+ const code = _chunkS357VL5Vcjs.readNetCode.call(void 0, e);
115
+ const opts = { cause: err };
116
+ if (status === 429 || status === 403 && reason !== null && RATE_REASONS.has(reason)) {
117
+ return { kind: "retry", delayMs: _chunkS357VL5Vcjs.readRetryAfterMs.call(void 0, e) };
118
+ }
119
+ if (status === 401) return { kind: "unauthorized" };
120
+ if (status === 409) return { kind: "duplicate" };
121
+ if (status === 404 || status === 410) return { kind: "gone" };
122
+ if (status === 412) return { kind: "precondition" };
123
+ if (status === 400) {
124
+ if (/conference/i.test(_chunkS357VL5Vcjs.readMessages.call(void 0, e))) {
125
+ return {
126
+ kind: "fail",
127
+ error: new (0, _chunkJZVDD4DLcjs.ConferencingUnavailableError)(void 0, opts)
128
+ };
129
+ }
130
+ return { kind: "fail", error: new (0, _chunkJZVDD4DLcjs.GoogleApiError)(400, reason, opts) };
131
+ }
132
+ if (status !== null && status >= 500) return { kind: "retry", delayMs: null };
133
+ if (code !== null && (NETWORK_CODES.has(code) || code.startsWith("ERR_TLS_") || code.startsWith("CERT_") || code === "ABORT_ERR") || e.name === "AbortError" || /socket hang up/i.test(_chunkS357VL5Vcjs.readMessages.call(void 0, e))) {
134
+ return { kind: "retry", delayMs: null };
135
+ }
136
+ if (status !== null) {
137
+ return { kind: "fail", error: new (0, _chunkJZVDD4DLcjs.GoogleApiError)(status, reason, opts) };
138
+ }
139
+ return { kind: "fail", error: new (0, _chunkJZVDD4DLcjs.GoogleApiError)(0, code, opts) };
140
+ }
141
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
142
+ async function withCalendarRetry(fn, opts = {}) {
143
+ const maxAttempts = _nullishCoalesce(opts.maxAttempts, () => ( 3));
144
+ const baseMs = _nullishCoalesce(opts.baseMs, () => ( 250));
145
+ const capMs = _nullishCoalesce(opts.capMs, () => ( 8e3));
146
+ const sleep = _nullishCoalesce(opts.sleep, () => ( defaultSleep));
147
+ const random = _nullishCoalesce(opts.random, () => ( Math.random));
148
+ for (let attempt = 0; ; attempt++) {
149
+ try {
150
+ return await fn();
151
+ } catch (err) {
152
+ const c = classifyCalendarError(err);
153
+ if (c.kind === "fail") throw c.error;
154
+ if (c.kind === "unauthorized") throw new CalendarUnauthorizedSignal();
155
+ if (c.kind === "duplicate") throw new DuplicateEventSignal();
156
+ if (c.kind === "gone") throw new EventGoneSignal();
157
+ if (c.kind === "precondition") throw new PreconditionFailedSignal();
158
+ if (c.delayMs !== null && c.delayMs > capMs) {
159
+ throw new (0, _chunkJZVDD4DLcjs.RateLimitedError)(c.delayMs, { cause: err });
160
+ }
161
+ if (attempt + 1 >= maxAttempts) {
162
+ const e = _chunkS357VL5Vcjs.asErr.call(void 0, err);
163
+ const status = _chunkS357VL5Vcjs.readStatus.call(void 0, e);
164
+ if (status === 429 || status === 403) {
165
+ throw new (0, _chunkJZVDD4DLcjs.RateLimitedError)(c.delayMs, { cause: err });
166
+ }
167
+ if (status !== null) {
168
+ throw new (0, _chunkJZVDD4DLcjs.GoogleApiError)(status, _chunkS357VL5Vcjs.readReason.call(void 0, e), { cause: err });
169
+ }
170
+ throw new (0, _chunkJZVDD4DLcjs.GoogleApiError)(0, _chunkS357VL5Vcjs.readNetCode.call(void 0, e), { cause: err });
171
+ }
172
+ await sleep(
173
+ _nullishCoalesce(c.delayMs, () => ( random() * Math.min(capMs, baseMs * 2 ** attempt)))
174
+ );
175
+ }
176
+ }
177
+ }
178
+
179
+ // src/calendar/time.ts
180
+ var MINUTE = 6e4;
181
+ var HOUR = 60 * MINUTE;
182
+ var WEEKDAYS = {
183
+ Mon: "mon",
184
+ Tue: "tue",
185
+ Wed: "wed",
186
+ Thu: "thu",
187
+ Fri: "fri",
188
+ Sat: "sat",
189
+ Sun: "sun"
190
+ };
191
+ var formatters = /* @__PURE__ */ new Map();
192
+ function formatter(tz) {
193
+ let f = formatters.get(tz);
194
+ if (f === void 0) {
195
+ f = new Intl.DateTimeFormat("en-US", {
196
+ timeZone: tz,
197
+ hourCycle: "h23",
198
+ year: "numeric",
199
+ month: "numeric",
200
+ day: "numeric",
201
+ hour: "numeric",
202
+ minute: "numeric",
203
+ weekday: "short"
204
+ });
205
+ formatters.set(tz, f);
206
+ }
207
+ return f;
208
+ }
209
+ function assertTimeZone(tz, field) {
210
+ if (typeof tz !== "string" || tz.length === 0 || tz.length > 64) {
211
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
212
+ }
213
+ try {
214
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
215
+ } catch (e2) {
216
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
217
+ }
218
+ return tz;
219
+ }
220
+ function zonedParts(at, tz) {
221
+ const out = {};
222
+ for (const p of formatter(tz).formatToParts(at)) out[p.type] = p.value;
223
+ const weekday = WEEKDAYS[_nullishCoalesce(out.weekday, () => ( ""))];
224
+ if (weekday === void 0) throw new Error("unexpected Intl weekday");
225
+ return {
226
+ year: Number(out.year),
227
+ month: Number(out.month),
228
+ day: Number(out.day),
229
+ hour: Number(out.hour) % 24,
230
+ minute: Number(out.minute),
231
+ weekday
232
+ };
233
+ }
234
+ var wallAsUTC = (p) => Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute);
235
+ var sameWall = (a, b) => a.year === b.year && a.month === b.month && a.day === b.day && a.hour === b.hour && a.minute === b.minute;
236
+ function offsetAt(t, tz) {
237
+ const floored = t - (t % MINUTE + MINUTE) % MINUTE;
238
+ return wallAsUTC(zonedParts(new Date(floored), tz)) - floored;
239
+ }
240
+ function zonedToInstant(p, tz) {
241
+ const guess = wallAsUTC(p);
242
+ const o1 = offsetAt(guess, tz);
243
+ const o2 = offsetAt(guess - o1, tz);
244
+ const found = /* @__PURE__ */ new Set();
245
+ const shifts = [0, -HOUR, HOUR, -HOUR / 2, HOUR / 2];
246
+ for (const offset of new Set(
247
+ [o1, o2].flatMap((o) => shifts.map((d) => o + d))
248
+ )) {
249
+ const cand = guess - offset;
250
+ if (sameWall(zonedParts(new Date(cand), tz), p)) found.add(cand);
251
+ }
252
+ if (found.size === 0) return null;
253
+ return new Date(Math.min(...found));
254
+ }
255
+
256
+ // src/calendar/slots.ts
257
+ var MINUTE2 = 6e4;
258
+ var DAY_MINUTES = 24 * 60;
259
+ var MAX_WINDOW_MS = 31 * DAY_MINUTES * MINUTE2;
260
+ var WEEKDAYS2 = [
261
+ "mon",
262
+ "tue",
263
+ "wed",
264
+ "thu",
265
+ "fri",
266
+ "sat",
267
+ "sun"
268
+ ];
269
+ var HHMM = /^(\d{2}):(\d{2})$/;
270
+ function intIn(value, min, max, field) {
271
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
272
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
273
+ }
274
+ return value;
275
+ }
276
+ var isDate = (d) => d instanceof Date && !Number.isNaN(d.getTime());
277
+ function parseHHMM(s, allow24, field) {
278
+ const m = typeof s === "string" ? HHMM.exec(s) : null;
279
+ if (m === null) throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
280
+ const h = Number(m[1]);
281
+ const min = Number(m[2]);
282
+ if (allow24 && h === 24 && min === 0) return DAY_MINUTES;
283
+ if (h > 23 || min > 59) throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
284
+ return h * 60 + min;
285
+ }
286
+ function parseHours(wh, path) {
287
+ if (typeof wh !== "object" || wh === null) throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(path);
288
+ const { timeZone, days } = wh;
289
+ const tz = assertTimeZone(timeZone, `${path}.timeZone`);
290
+ const daysField = `${path}.days`;
291
+ if (typeof days !== "object" || days === null)
292
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(daysField);
293
+ const out = { timeZone: tz, days: {} };
294
+ for (const [key, list] of Object.entries(days)) {
295
+ if (!WEEKDAYS2.includes(key) || !Array.isArray(list)) {
296
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(daysField);
297
+ }
298
+ out.days[key] = list.map((iv) => {
299
+ const { start, end } = _nullishCoalesce(iv, () => ( {}));
300
+ const s = parseHHMM(start, false, daysField);
301
+ const e = parseHHMM(end, true, daysField);
302
+ if (s >= e) throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(daysField);
303
+ return { start: s, end: e };
304
+ });
305
+ }
306
+ return out;
307
+ }
308
+ function prepareBusy(ranges, buffer, field) {
309
+ if (!Array.isArray(ranges)) throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
310
+ const list = ranges.map((r) => {
311
+ const { start, end } = _nullishCoalesce(r, () => ( {}));
312
+ if (!isDate(start) || !isDate(end)) throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
313
+ return { start: start.getTime() - buffer, end: end.getTime() + buffer };
314
+ });
315
+ list.sort((a, b) => a.start - b.start);
316
+ const merged = [];
317
+ for (const iv of list) {
318
+ const last = merged.at(-1);
319
+ if (last !== void 0 && iv.start <= last.end)
320
+ last.end = Math.max(last.end, iv.end);
321
+ else if (iv.end > iv.start) merged.push({ ...iv });
322
+ }
323
+ return merged;
324
+ }
325
+ function overlapsBusy(busy, start, end) {
326
+ let lo = 0;
327
+ let hi = busy.length;
328
+ while (lo < hi) {
329
+ const mid = lo + hi >> 1;
330
+ if (busy[mid].start < end) lo = mid + 1;
331
+ else hi = mid;
332
+ }
333
+ return lo > 0 && busy[lo - 1].end > start;
334
+ }
335
+ var addDays = (p, n) => {
336
+ const d = new Date(Date.UTC(p.year, p.month - 1, p.day + n));
337
+ return {
338
+ year: d.getUTCFullYear(),
339
+ month: d.getUTCMonth() + 1,
340
+ day: d.getUTCDate(),
341
+ hour: 0,
342
+ minute: 0
343
+ };
344
+ };
345
+ function boundInstant(date, minutes, tz) {
346
+ for (let m = minutes; m <= minutes + 24 * 60; m++) {
347
+ const p = m >= DAY_MINUTES ? addDays(date, 1) : date;
348
+ const mm = m % DAY_MINUTES;
349
+ const at = zonedToInstant(
350
+ { ...p, hour: Math.floor(mm / 60), minute: mm % 60 },
351
+ tz
352
+ );
353
+ if (at !== null) return at.getTime();
354
+ }
355
+ throw new Error("unresolvable wall time");
356
+ }
357
+ function workingInstants(hours, from, to) {
358
+ const tz = hours.timeZone;
359
+ const a = zonedParts(new Date(from), tz);
360
+ const b = zonedParts(new Date(to), tz);
361
+ const lastKey = Date.UTC(b.year, b.month - 1, b.day);
362
+ const out = [];
363
+ for (let n = 0; ; n++) {
364
+ const date = addDays({ ...a, hour: 0, minute: 0 }, n);
365
+ const utc = Date.UTC(date.year, date.month - 1, date.day);
366
+ if (utc > lastKey) break;
367
+ const weekday = WEEKDAYS2[(new Date(utc).getUTCDay() + 6) % 7];
368
+ for (const iv of _nullishCoalesce(hours.days[weekday], () => ( []))) {
369
+ out.push({
370
+ start: boundInstant(date, iv.start, tz),
371
+ end: boundInstant(date, iv.end, tz)
372
+ });
373
+ }
374
+ }
375
+ return out.sort((x, y) => x.start - y.start);
376
+ }
377
+ function insideHours(working, start, end) {
378
+ let lo = 0;
379
+ let hi = working.length;
380
+ while (lo < hi) {
381
+ const mid = lo + hi >> 1;
382
+ if (working[mid].start <= start) lo = mid + 1;
383
+ else hi = mid;
384
+ }
385
+ for (let i = lo - 1; i >= 0 && working[i].start > start - 26 * 60 * MINUTE2; i--) {
386
+ if (end <= working[i].end) return true;
387
+ }
388
+ return false;
389
+ }
390
+ function dayCandidates(date, step, tz) {
391
+ const midnight = Date.UTC(date.year, date.month - 1, date.day);
392
+ const offsetOf = (t) => {
393
+ const p = zonedParts(new Date(t), tz);
394
+ return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute) - t;
395
+ };
396
+ const offset = offsetOf(midnight);
397
+ let fixed = true;
398
+ for (let h = -2; h <= 26 && fixed; h++) {
399
+ fixed = offsetOf(midnight - offset + h * 60 * MINUTE2) === offset;
400
+ }
401
+ const out = [];
402
+ for (let m = 0; m < DAY_MINUTES; m += step) {
403
+ if (fixed) out.push(midnight + m * MINUTE2 - offset);
404
+ else {
405
+ const at = zonedToInstant(
406
+ { ...date, hour: Math.floor(m / 60), minute: m % 60 },
407
+ tz
408
+ );
409
+ out.push(at === null ? null : at.getTime());
410
+ }
411
+ }
412
+ return out;
413
+ }
414
+ function parseSlotParams(input) {
415
+ const durationMinutes = intIn(
416
+ input.durationMinutes,
417
+ 5,
418
+ 480,
419
+ "durationMinutes"
420
+ );
421
+ const stepMinutes = intIn(_nullishCoalesce(input.stepMinutes, () => ( 15)), 5, 60, "stepMinutes");
422
+ const bufferMinutes = intIn(
423
+ _nullishCoalesce(input.bufferMinutes, () => ( 0)),
424
+ 0,
425
+ 240,
426
+ "bufferMinutes"
427
+ );
428
+ const minNoticeMinutes = intIn(
429
+ _nullishCoalesce(input.minNoticeMinutes, () => ( 60)),
430
+ 0,
431
+ 10080,
432
+ "minNoticeMinutes"
433
+ );
434
+ const maxResults = intIn(_nullishCoalesce(input.maxResults, () => ( 10)), 1, 50, "maxResults");
435
+ const tenant = parseHours(input.workingHours, "workingHours");
436
+ const overrides = /* @__PURE__ */ new Map();
437
+ const byAttendee = _nullishCoalesce(input.workingHoursByAttendee, () => ( {}));
438
+ if (typeof byAttendee !== "object" || byAttendee === null)
439
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("workingHoursByAttendee");
440
+ for (const [email, wh] of Object.entries(byAttendee)) {
441
+ overrides.set(
442
+ email.toLowerCase(),
443
+ parseHours(wh, `workingHoursByAttendee.${email}`)
444
+ );
445
+ }
446
+ return {
447
+ durationMinutes,
448
+ stepMinutes,
449
+ bufferMinutes,
450
+ minNoticeMinutes,
451
+ maxResults,
452
+ tenant,
453
+ overrides
454
+ };
455
+ }
456
+ function findCommonSlots(input) {
457
+ const {
458
+ durationMinutes: duration,
459
+ stepMinutes: step,
460
+ bufferMinutes: buffer,
461
+ minNoticeMinutes: notice,
462
+ maxResults,
463
+ tenant,
464
+ overrides
465
+ } = parseSlotParams(input);
466
+ if (!isDate(input.now)) throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("now");
467
+ const { window } = input;
468
+ if (typeof window !== "object" || window === null || !isDate(window.start) || !isDate(window.end)) {
469
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("window");
470
+ }
471
+ const winStart = window.start.getTime();
472
+ const winEnd = window.end.getTime();
473
+ if (winEnd <= winStart || winEnd - winStart > MAX_WINDOW_MS) {
474
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("window");
475
+ }
476
+ if (typeof input.busy !== "object" || input.busy === null)
477
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("busy");
478
+ const people = Object.entries(input.busy).map(
479
+ ([email, ranges]) => ({
480
+ hours: _nullishCoalesce(overrides.get(email.toLowerCase()), () => ( tenant)),
481
+ busy: prepareBusy(ranges, buffer * MINUTE2, `busy.${email}`),
482
+ working: []
483
+ })
484
+ );
485
+ if (people.length === 0)
486
+ people.push({ hours: tenant, busy: [], working: [] });
487
+ const workingCache = /* @__PURE__ */ new Map();
488
+ for (const p of people) {
489
+ let w = workingCache.get(p.hours);
490
+ if (w === void 0) {
491
+ w = workingInstants(p.hours, winStart, winEnd);
492
+ workingCache.set(p.hours, w);
493
+ }
494
+ p.working = w;
495
+ }
496
+ const earliest = Math.max(winStart, input.now.getTime() + notice * MINUTE2);
497
+ const durationMs = duration * MINUTE2;
498
+ const tz = tenant.timeZone;
499
+ const first = zonedParts(window.start, tz);
500
+ const last = zonedParts(new Date(winEnd - 1), tz);
501
+ const lastKey = Date.UTC(last.year, last.month - 1, last.day);
502
+ const seen = /* @__PURE__ */ new Set();
503
+ const slots = [];
504
+ for (let n = 0; ; n++) {
505
+ const date = addDays({ ...first, hour: 0, minute: 0 }, n);
506
+ if (Date.UTC(date.year, date.month - 1, date.day) > lastKey) break;
507
+ for (const start of dayCandidates(date, step, tz)) {
508
+ if (start === null) continue;
509
+ const end = start + durationMs;
510
+ if (start < earliest || end > winEnd || seen.has(start)) continue;
511
+ seen.add(start);
512
+ if (people.every(
513
+ (p) => !overlapsBusy(p.busy, start, end) && insideHours(p.working, start, end)
514
+ )) {
515
+ slots.push({ start: new Date(start), end: new Date(end) });
516
+ }
517
+ }
518
+ }
519
+ slots.sort((a, b) => a.start.getTime() - b.start.getTime());
520
+ return slots.slice(0, maxResults);
521
+ }
522
+
523
+ // src/calendar/transport.ts
524
+ var _googleauthlibrary = require('google-auth-library');
525
+ var CALENDAR_ID = "primary";
526
+ var ifMatchArgs = (ifMatch) => ifMatch === void 0 ? [] : [{ headers: { "If-Match": ifMatch } }];
527
+ function createCalendarApiTransport() {
528
+ const client = async (accessToken) => {
529
+ const mod = await _chunkJDA3ZRUYcjs.loadPeer.call(void 0, "@googleapis/calendar");
530
+ const { calendar } = mod.calendar ? mod : mod.default;
531
+ const auth = new (0, _googleauthlibrary.OAuth2Client)();
532
+ auth.setCredentials({ access_token: accessToken });
533
+ return calendar({ version: "v3", auth });
534
+ };
535
+ return {
536
+ async freeBusy({ accessToken, timeMin, timeMax, emails }) {
537
+ const api = await client(accessToken);
538
+ const { data } = await api.freebusy.query({
539
+ requestBody: {
540
+ timeMin,
541
+ timeMax,
542
+ items: emails.map((id) => ({ id }))
543
+ }
544
+ });
545
+ const out = {};
546
+ for (const [email, cal] of Object.entries(_nullishCoalesce(_optionalChain([data, 'optionalAccess', _ => _.calendars]), () => ( {})))) {
547
+ out[email] = {
548
+ busy: (_nullishCoalesce(cal.busy, () => ( []))).map((b) => ({
549
+ start: _nullishCoalesce(b.start, () => ( "")),
550
+ end: _nullishCoalesce(b.end, () => ( ""))
551
+ })),
552
+ errors: (_nullishCoalesce(cal.errors, () => ( []))).map((x) => ({ reason: _nullishCoalesce(x.reason, () => ( "")) }))
553
+ };
554
+ }
555
+ return out;
556
+ },
557
+ async insert({ accessToken, event, sendUpdates, conferenceDataVersion }) {
558
+ const api = await client(accessToken);
559
+ const { data } = await api.events.insert({
560
+ calendarId: CALENDAR_ID,
561
+ requestBody: event,
562
+ sendUpdates,
563
+ conferenceDataVersion
564
+ });
565
+ return data;
566
+ },
567
+ async get({ accessToken, eventId }) {
568
+ const api = await client(accessToken);
569
+ const { data } = await api.events.get({
570
+ calendarId: CALENDAR_ID,
571
+ eventId
572
+ });
573
+ return data;
574
+ },
575
+ async patch({
576
+ accessToken,
577
+ eventId,
578
+ patch,
579
+ sendUpdates,
580
+ conferenceDataVersion,
581
+ ifMatch
582
+ }) {
583
+ const api = await client(accessToken);
584
+ const { data } = await api.events.patch(
585
+ {
586
+ calendarId: CALENDAR_ID,
587
+ eventId,
588
+ requestBody: patch,
589
+ sendUpdates,
590
+ conferenceDataVersion
591
+ },
592
+ ...ifMatchArgs(ifMatch)
593
+ );
594
+ return data;
595
+ },
596
+ async delete({ accessToken, eventId, sendUpdates, ifMatch }) {
597
+ const api = await client(accessToken);
598
+ await api.events.delete(
599
+ { calendarId: CALENDAR_ID, eventId, sendUpdates },
600
+ ...ifMatchArgs(ifMatch)
601
+ );
602
+ }
603
+ };
604
+ }
605
+
606
+ // src/calendar/validate.ts
607
+ var CONTROLS = /[\u0000-\u001f\u007f-\u009f]/;
608
+ var LOCATION_FORBIDDEN = /[\r\n\0]/;
609
+ var SEND_UPDATES = ["all", "external_only", "none"];
610
+ var CHANGE_KEYS = /* @__PURE__ */ new Set([
611
+ "start",
612
+ "end",
613
+ "timeZone",
614
+ "title",
615
+ "description",
616
+ "attendees",
617
+ "meeting",
618
+ "guestsCanSeeOtherGuests"
619
+ ]);
620
+ var MAX_EVENT_MS = 24 * 36e5;
621
+ var MAX_WINDOW_MS2 = 31 * 24 * 36e5;
622
+ var fail = (field) => {
623
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
624
+ };
625
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
626
+ function requireString(v, field, min, max) {
627
+ if (typeof v !== "string" || v.length < min || v.length > max) fail(field);
628
+ return v;
629
+ }
630
+ function validId(v, field) {
631
+ return requireString(v, field, 1, Number.MAX_SAFE_INTEGER);
632
+ }
633
+ function validateIdentity(i, actor = true) {
634
+ validId(i.tenantId, "tenantId");
635
+ validId(i.connectionId, "connectionId");
636
+ if (actor) validId(i.actorId, "actorId");
637
+ }
638
+ function validDate(v, field) {
639
+ if (!(v instanceof Date) || Number.isNaN(v.getTime())) fail(field);
640
+ return v;
641
+ }
642
+ function validTitle(v) {
643
+ const t = requireString(v, "title", 1, 255);
644
+ if (CONTROLS.test(t)) fail("title");
645
+ return t;
646
+ }
647
+ function validDescription(v) {
648
+ if (typeof v !== "string" || v.includes("\0")) return fail("description");
649
+ if (Buffer.byteLength(v, "utf8") > 8192) fail("description");
650
+ return v;
651
+ }
652
+ function validMeeting(v) {
653
+ if (!isObject(v)) return fail("meeting");
654
+ const keys = Object.keys(v);
655
+ if (v.type === "google_meet") {
656
+ if (keys.length !== 1) fail("meeting");
657
+ return { type: "google_meet" };
658
+ }
659
+ if (v.type === "in_person") {
660
+ if (keys.some((k) => k !== "type" && k !== "location")) fail("meeting");
661
+ const loc = requireString(v.location, "meeting.location", 1, 1024);
662
+ if (LOCATION_FORBIDDEN.test(loc)) fail("meeting.location");
663
+ return { type: "in_person", location: loc };
664
+ }
665
+ return fail("meeting");
666
+ }
667
+ function validBool(v, field) {
668
+ if (typeof v !== "boolean") fail(field);
669
+ return v;
670
+ }
671
+ function validAttendees(v, organizerEmail) {
672
+ if (!Array.isArray(v)) return fail("attendees");
673
+ const organizer = organizerEmail.toLowerCase();
674
+ const seen = /* @__PURE__ */ new Set([organizer]);
675
+ const out = [];
676
+ v.forEach((raw, i) => {
677
+ if (!isObject(raw)) fail(`attendees[${i}]`);
678
+ const a = raw;
679
+ const email = _chunkS357VL5Vcjs.normalizeEmail.call(void 0, a.email);
680
+ if (email === null) fail(`attendees[${i}]`);
681
+ let displayName = null;
682
+ if (a.displayName !== void 0) {
683
+ const n = requireString(
684
+ a.displayName,
685
+ `attendees[${i}].displayName`,
686
+ 0,
687
+ 200
688
+ );
689
+ if (CONTROLS.test(n)) fail(`attendees[${i}].displayName`);
690
+ displayName = n === "" ? null : n;
691
+ }
692
+ const optional = a.optional === void 0 ? false : validBool(a.optional, `attendees[${i}].optional`);
693
+ const key = email.toLowerCase();
694
+ if (seen.has(key)) return;
695
+ seen.add(key);
696
+ out.push({ email, displayName, optional });
697
+ });
698
+ if (out.length < 1 || out.length > 100) fail("attendees");
699
+ return out;
700
+ }
701
+ function checkRange(start, end) {
702
+ const span = end.getTime() - start.getTime();
703
+ if (span <= 0 || span > MAX_EVENT_MS) fail("end");
704
+ }
705
+ function validSendUpdates(v) {
706
+ if (v === void 0) return "all";
707
+ if (typeof v !== "string" || !SEND_UPDATES.includes(v)) fail("sendUpdates");
708
+ return v;
709
+ }
710
+ function validateCreateInput(input, organizerEmail) {
711
+ if (!isObject(input)) return fail("input");
712
+ const i = input;
713
+ validateIdentity(i);
714
+ const key = requireString(i.idempotencyKey, "idempotencyKey", 1, 200);
715
+ if (CONTROLS.test(key)) fail("idempotencyKey");
716
+ const title = validTitle(i.title);
717
+ const description = i.description === void 0 ? null : validDescription(i.description);
718
+ const start = validDate(i.start, "start");
719
+ const end = validDate(i.end, "end");
720
+ checkRange(start, end);
721
+ const timeZone = assertTimeZone(i.timeZone, "timeZone");
722
+ const attendees = validAttendees(i.attendees, organizerEmail);
723
+ const meeting = validMeeting(i.meeting);
724
+ const guestsCanSeeOtherGuests = i.guestsCanSeeOtherGuests === void 0 ? false : validBool(i.guestsCanSeeOtherGuests, "guestsCanSeeOtherGuests");
725
+ const sendUpdates = validSendUpdates(i.sendUpdates);
726
+ return {
727
+ idempotencyKey: key,
728
+ title,
729
+ description,
730
+ start,
731
+ end,
732
+ timeZone,
733
+ attendees,
734
+ meeting,
735
+ guestsCanSeeOtherGuests,
736
+ sendUpdates
737
+ };
738
+ }
739
+ function validateChanges(changes, organizerEmail) {
740
+ if (!isObject(changes)) return fail("changes");
741
+ const c = changes;
742
+ if (Object.keys(c).some((k) => !CHANGE_KEYS.has(k))) fail("changes");
743
+ const out = {};
744
+ if (c.title !== void 0) out.title = validTitle(c.title);
745
+ if (c.description !== void 0)
746
+ out.description = c.description === null ? null : validDescription(c.description);
747
+ if (c.start !== void 0) out.start = validDate(c.start, "start");
748
+ if (c.end !== void 0) out.end = validDate(c.end, "end");
749
+ if (c.timeZone !== void 0)
750
+ out.timeZone = assertTimeZone(c.timeZone, "timeZone");
751
+ if (c.attendees !== void 0)
752
+ out.attendees = validAttendees(c.attendees, organizerEmail);
753
+ if (c.meeting !== void 0) out.meeting = validMeeting(c.meeting);
754
+ if (c.guestsCanSeeOtherGuests !== void 0)
755
+ out.guestsCanSeeOtherGuests = validBool(
756
+ c.guestsCanSeeOtherGuests,
757
+ "guestsCanSeeOtherGuests"
758
+ );
759
+ return out;
760
+ }
761
+ function validateAvailabilityInput(input) {
762
+ if (!isObject(input)) return fail("input");
763
+ const i = input;
764
+ validateIdentity(i);
765
+ if (!Array.isArray(i.attendees)) return fail("attendees");
766
+ const seen = /* @__PURE__ */ new Set();
767
+ for (const raw of i.attendees) {
768
+ const email = _chunkS357VL5Vcjs.normalizeEmail.call(void 0, raw);
769
+ if (email === null) fail("attendees");
770
+ seen.add(email.toLowerCase());
771
+ }
772
+ if (seen.size < 1 || seen.size > 50) fail("attendees");
773
+ const w = i.window;
774
+ if (!isObject(w)) return fail("window");
775
+ const start = w.start;
776
+ const end = w.end;
777
+ if (!(start instanceof Date) || !(end instanceof Date) || Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()))
778
+ return fail("window");
779
+ const span = end.getTime() - start.getTime();
780
+ if (span <= 0 || span > MAX_WINDOW_MS2) fail("window");
781
+ return { attendees: [...seen], window: { start, end } };
782
+ }
783
+
784
+ // src/calendar/view.ts
785
+ var RESPONSES = {
786
+ accepted: "accepted",
787
+ declined: "declined",
788
+ tentative: "tentative",
789
+ needsAction: "needs_action"
790
+ };
791
+ var STATUSES = ["confirmed", "tentative", "cancelled"];
792
+ function assertManaged(e, tenantId) {
793
+ const priv = _optionalChain([e, 'access', _2 => _2.extendedProperties, 'optionalAccess', _3 => _3.private]);
794
+ if (_optionalChain([priv, 'optionalAccess', _4 => _4.mshindiGoogle]) !== "v1" || priv.mshindiTenant !== tenantId) {
795
+ throw new (0, _chunkJZVDD4DLcjs.EventNotManagedError)();
796
+ }
797
+ }
798
+ function meetingOf(e) {
799
+ const cd = e.conferenceData;
800
+ if (_optionalChain([cd, 'optionalAccess', _5 => _5.conferenceSolution, 'optionalAccess', _6 => _6.key, 'optionalAccess', _7 => _7.type]) === "hangoutsMeet" || _optionalChain([cd, 'optionalAccess', _8 => _8.createRequest]) !== void 0) {
801
+ const video = _optionalChain([cd, 'optionalAccess', _9 => _9.entryPoints, 'optionalAccess', _10 => _10.find, 'call', _11 => _11(
802
+ (p) => p.entryPointType === "video" && typeof p.uri === "string"
803
+ )]);
804
+ return { type: "google_meet", meetUrl: _nullishCoalesce(_optionalChain([video, 'optionalAccess', _12 => _12.uri]), () => ( null)) };
805
+ }
806
+ return { type: "in_person", location: _nullishCoalesce(e.location, () => ( "")) };
807
+ }
808
+ var guestsOf = (e) => (_nullishCoalesce(e.attendees, () => ( []))).filter(
809
+ (a) => a.organizer !== true && a.self !== true && !!a.email
810
+ );
811
+ function toNormalized(e) {
812
+ const m = meetingOf(e);
813
+ return {
814
+ title: _nullishCoalesce(e.summary, () => ( "")),
815
+ description: _nullishCoalesce(e.description, () => ( null)),
816
+ start: new Date(_nullishCoalesce(_optionalChain([e, 'access', _13 => _13.start, 'optionalAccess', _14 => _14.dateTime]), () => ( ""))),
817
+ end: new Date(_nullishCoalesce(_optionalChain([e, 'access', _15 => _15.end, 'optionalAccess', _16 => _16.dateTime]), () => ( ""))),
818
+ timeZone: _nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _17 => _17.start, 'optionalAccess', _18 => _18.timeZone]), () => ( _optionalChain([e, 'access', _19 => _19.end, 'optionalAccess', _20 => _20.timeZone]))), () => ( "UTC")),
819
+ attendees: guestsOf(e).map((a) => ({
820
+ email: a.email,
821
+ displayName: _nullishCoalesce(a.displayName, () => ( null)),
822
+ optional: _nullishCoalesce(a.optional, () => ( false))
823
+ })),
824
+ meeting: m.type === "google_meet" ? { type: "google_meet" } : { type: "in_person", location: m.location },
825
+ guestsCanSeeOtherGuests: _nullishCoalesce(e.guestsCanSeeOtherGuests, () => ( false))
826
+ };
827
+ }
828
+ function toView(e) {
829
+ const status = _nullishCoalesce(STATUSES.find((s) => s === e.status), () => ( "confirmed"));
830
+ return {
831
+ eventId: e.id,
832
+ status,
833
+ title: _nullishCoalesce(e.summary, () => ( "")),
834
+ start: new Date(_nullishCoalesce(_optionalChain([e, 'access', _21 => _21.start, 'optionalAccess', _22 => _22.dateTime]), () => ( ""))),
835
+ end: new Date(_nullishCoalesce(_optionalChain([e, 'access', _23 => _23.end, 'optionalAccess', _24 => _24.dateTime]), () => ( ""))),
836
+ timeZone: _nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _25 => _25.start, 'optionalAccess', _26 => _26.timeZone]), () => ( _optionalChain([e, 'access', _27 => _27.end, 'optionalAccess', _28 => _28.timeZone]))), () => ( "UTC")),
837
+ meeting: meetingOf(e),
838
+ guestsCanSeeOtherGuests: _nullishCoalesce(e.guestsCanSeeOtherGuests, () => ( false)),
839
+ attendees: guestsOf(e).map((a) => ({
840
+ email: a.email,
841
+ displayName: _nullishCoalesce(a.displayName, () => ( null)),
842
+ optional: _nullishCoalesce(a.optional, () => ( false)),
843
+ response: _nullishCoalesce(RESPONSES[_nullishCoalesce(a.responseStatus, () => ( ""))], () => ( "needs_action"))
844
+ })),
845
+ htmlLink: _nullishCoalesce(e.htmlLink, () => ( "")),
846
+ updatedAt: new Date(_nullishCoalesce(e.updated, () => ( 0)))
847
+ };
848
+ }
849
+
850
+ // src/calendar/service.ts
851
+ var GOOGLE_SEND_UPDATES = {
852
+ all: "all",
853
+ external_only: "externalOnly",
854
+ none: "none"
855
+ };
856
+ var CONFERENCE_POLL_MS = [500, 1e3, 2e3, 3e3, 3500];
857
+ var RELEASE_ATTEMPTS = 3;
858
+ var PATCH_ATTEMPTS = 3;
859
+ var MAX_EVENT_MS2 = 24 * 36e5;
860
+ var BACKOFF_BASE_MS = 250;
861
+ var BACKOFF_CAP_MS = 8e3;
862
+ var defaultSleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
863
+ var conferenceStatus = (e) => _optionalChain([e, 'access', _29 => _29.conferenceData, 'optionalAccess', _30 => _30.createRequest, 'optionalAccess', _31 => _31.status, 'optionalAccess', _32 => _32.statusCode]);
864
+ var meetReady = (e) => conferenceStatus(e) === "success" && (_nullishCoalesce(_optionalChain([e, 'access', _33 => _33.conferenceData, 'optionalAccess', _34 => _34.entryPoints]), () => ( []))).some(
865
+ (p) => p.entryPointType === "video" && typeof p.uri === "string"
866
+ );
867
+ var inviteState = (e) => _optionalChain([e, 'access', _35 => _35.extendedProperties, 'optionalAccess', _36 => _36.private, 'optionalAccess', _37 => _37.mshindiInvite]);
868
+ function requireIds(input, fields) {
869
+ for (const field of fields) {
870
+ const v = _optionalChain([input, 'optionalAccess', _38 => _38[field]]);
871
+ if (typeof v !== "string" || v === "") throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
872
+ }
873
+ }
874
+ function parseSendUpdates(v) {
875
+ if (v === void 0) return "all";
876
+ if (typeof v !== "string" || !Object.prototype.hasOwnProperty.call(GOOGLE_SEND_UPDATES, v)) {
877
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("sendUpdates");
878
+ }
879
+ return GOOGLE_SEND_UPDATES[v];
880
+ }
881
+ var attendeeKey = (as) => JSON.stringify(
882
+ as.map((a) => [a.email.toLowerCase(), a.optional, a.displayName]).sort((x, y) => x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0)
883
+ );
884
+ var SAME = {
885
+ title: (a, b) => a === b,
886
+ description: (a, b) => a === b,
887
+ start: (a, b) => a.getTime() === b.getTime(),
888
+ end: (a, b) => a.getTime() === b.getTime(),
889
+ timeZone: (a, b) => a === b,
890
+ attendees: (a, b) => attendeeKey(a) === attendeeKey(b),
891
+ meeting: (a, b) => a.type === b.type && (a.type !== "in_person" || a.location === b.location),
892
+ guestsCanSeeOtherGuests: (a, b) => a === b
893
+ };
894
+ var same = (k, a, b) => SAME[k](a[k], b[k]);
895
+ function changedKeys(e, current, changes) {
896
+ return Object.keys(changes).filter(
897
+ (k) => !same(k, current, changes) || k === "meeting" && _optionalChain([changes, 'access', _39 => _39.meeting, 'optionalAccess', _40 => _40.type]) === "google_meet" && !meetReady(e)
898
+ ).sort();
899
+ }
900
+ function withKnownNames(current, changes) {
901
+ if (changes.attendees === void 0) return changes;
902
+ const names = new Map(
903
+ current.attendees.map((a) => [a.email.toLowerCase(), a.displayName])
904
+ );
905
+ return {
906
+ ...changes,
907
+ attendees: changes.attendees.map(
908
+ (a) => a.displayName !== null ? a : { ...a, displayName: _nullishCoalesce(names.get(a.email.toLowerCase()), () => ( null)) }
909
+ )
910
+ };
911
+ }
912
+ function updatePatch(current, next, changed, fp) {
913
+ const p = {};
914
+ let requestId = null;
915
+ const has = (k) => changed.includes(k);
916
+ let conferenceDataVersion = 0;
917
+ if (has("title")) p.summary = next.title;
918
+ if (has("description")) p.description = next.description;
919
+ if (has("start") || has("end") || has("timeZone")) {
920
+ p.start = { dateTime: next.start.toISOString(), timeZone: next.timeZone };
921
+ p.end = { dateTime: next.end.toISOString(), timeZone: next.timeZone };
922
+ }
923
+ if (has("attendees")) {
924
+ const all = _nullishCoalesce(current.attendees, () => ( []));
925
+ const kept = new Map(
926
+ all.flatMap(
927
+ (a) => a.email && a.organizer !== true && a.self !== true ? [[a.email.toLowerCase(), a]] : []
928
+ )
929
+ );
930
+ p.attendees = [
931
+ ...all.filter((a) => a.organizer === true || a.self === true),
932
+ ...next.attendees.map((a) => {
933
+ const { displayName: _d, ...was } = _nullishCoalesce(kept.get(a.email.toLowerCase()), () => ( {}));
934
+ void _d;
935
+ return {
936
+ ...was,
937
+ email: a.email,
938
+ ...a.displayName !== null && { displayName: a.displayName },
939
+ optional: a.optional
940
+ };
941
+ })
942
+ ];
943
+ }
944
+ if (has("meeting")) {
945
+ const wasMeet = toNormalized(current).meeting.type === "google_meet";
946
+ if (next.meeting.type === "google_meet") {
947
+ if (!wasMeet || !meetReady(current)) {
948
+ requestId = _crypto.randomUUID.call(void 0, );
949
+ p.conferenceData = {
950
+ createRequest: {
951
+ requestId,
952
+ conferenceSolutionKey: { type: "hangoutsMeet" }
953
+ }
954
+ };
955
+ if (!wasMeet) p.location = null;
956
+ conferenceDataVersion = 1;
957
+ }
958
+ } else {
959
+ p.location = next.meeting.location;
960
+ if (wasMeet) {
961
+ p.conferenceData = null;
962
+ conferenceDataVersion = 1;
963
+ }
964
+ }
965
+ }
966
+ if (has("guestsCanSeeOtherGuests")) {
967
+ p.guestsCanSeeOtherGuests = next.guestsCanSeeOtherGuests;
968
+ }
969
+ p.extendedProperties = { private: { mshindiFingerprint: fp } };
970
+ return { patch: p, conferenceDataVersion, requestId };
971
+ }
972
+ function eventBody(id, ev, stamp) {
973
+ const meet = ev.meeting.type === "google_meet";
974
+ return {
975
+ id,
976
+ summary: ev.title,
977
+ ...ev.description !== null && { description: ev.description },
978
+ start: { dateTime: ev.start.toISOString(), timeZone: ev.timeZone },
979
+ end: { dateTime: ev.end.toISOString(), timeZone: ev.timeZone },
980
+ attendees: ev.attendees.map((a) => ({
981
+ email: a.email,
982
+ ...a.displayName !== null && { displayName: a.displayName },
983
+ optional: a.optional
984
+ })),
985
+ ...ev.meeting.type === "in_person" && { location: ev.meeting.location },
986
+ guestsCanInviteOthers: false,
987
+ guestsCanModify: false,
988
+ guestsCanSeeOtherGuests: ev.guestsCanSeeOtherGuests,
989
+ ...meet && {
990
+ conferenceData: {
991
+ createRequest: {
992
+ requestId: _crypto.randomUUID.call(void 0, ),
993
+ conferenceSolutionKey: { type: "hangoutsMeet" }
994
+ }
995
+ }
996
+ },
997
+ extendedProperties: {
998
+ private: {
999
+ mshindiGoogle: "v1",
1000
+ mshindiTenant: stamp.tenantId,
1001
+ mshindiKey: stamp.key,
1002
+ mshindiFingerprint: stamp.fingerprint,
1003
+ mshindiInvite: meet ? "pending" : "sent"
1004
+ }
1005
+ }
1006
+ };
1007
+ }
1008
+ function sanitize(err) {
1009
+ if (err instanceof _chunkJZVDD4DLcjs.GoogleLibError) return err;
1010
+ if (err instanceof EventGoneSignal) return new (0, _chunkJZVDD4DLcjs.EventNotFoundError)();
1011
+ if (err instanceof DuplicateEventSignal || err instanceof PreconditionFailedSignal) {
1012
+ return new (0, _chunkJZVDD4DLcjs.EventConflictError)();
1013
+ }
1014
+ return new (0, _chunkJZVDD4DLcjs.GoogleApiError)(0, null, { cause: err });
1015
+ }
1016
+ var REASONS = {
1017
+ notFound: "not_found",
1018
+ forbidden: "no_access",
1019
+ noAccess: "no_access"
1020
+ };
1021
+ function mergeBusy(raw, w) {
1022
+ const lo = w.start.getTime();
1023
+ const hi = w.end.getTime();
1024
+ const spans = [];
1025
+ for (const b of raw) {
1026
+ const s = Math.max(Date.parse(b.start), lo);
1027
+ const e = Math.min(Date.parse(b.end), hi);
1028
+ if (Number.isFinite(s) && Number.isFinite(e) && e > s) spans.push([s, e]);
1029
+ }
1030
+ spans.sort((a, b) => a[0] - b[0]);
1031
+ const merged = [];
1032
+ for (const [s, e] of spans) {
1033
+ const last = merged[merged.length - 1];
1034
+ if (last !== void 0 && s <= last[1]) last[1] = Math.max(last[1], e);
1035
+ else merged.push([s, e]);
1036
+ }
1037
+ return merged.map(([s, e]) => ({ start: new Date(s), end: new Date(e) }));
1038
+ }
1039
+ function createCalendar(google, opts = {}) {
1040
+ const transport = _nullishCoalesce(opts.transport, () => ( createCalendarApiTransport()));
1041
+ const retryOpts = {
1042
+ ...opts.sleep ? { sleep: opts.sleep } : {},
1043
+ ...opts.random ? { random: opts.random } : {}
1044
+ };
1045
+ const retry = (fn) => withCalendarRetry(fn, retryOpts);
1046
+ const sleep = _nullishCoalesce(opts.sleep, () => ( defaultSleep2));
1047
+ const random = _nullishCoalesce(opts.random, () => ( Math.random));
1048
+ const rethrow = (err) => withCalendarRetry(() => Promise.reject(err), {
1049
+ ...retryOpts,
1050
+ maxAttempts: 1
1051
+ });
1052
+ async function withToken(tenantId, connectionId, fn) {
1053
+ const { store, tokens, emit, now, logger } = google[_chunkDPAPYMB3cjs.internals];
1054
+ const first = await tokens.getAccessToken(tenantId, connectionId);
1055
+ const { refreshToken: _omit, ...view } = first.connection;
1056
+ void _omit;
1057
+ _chunkDPAPYMB3cjs.assertServiceScopes.call(void 0, view.scopes, ["calendar"], { tenantId, connectionId });
1058
+ let result;
1059
+ try {
1060
+ result = await fn(first.accessToken, view);
1061
+ } catch (err) {
1062
+ if (!(err instanceof CalendarUnauthorizedSignal)) throw err;
1063
+ const fresh = await tokens.getAccessToken(tenantId, connectionId, {
1064
+ forceRefresh: true
1065
+ });
1066
+ try {
1067
+ result = await fn(fresh.accessToken, view);
1068
+ } catch (err2) {
1069
+ if (!(err2 instanceof CalendarUnauthorizedSignal)) throw err2;
1070
+ await store.updateConnectionStatus(
1071
+ tenantId,
1072
+ connectionId,
1073
+ "revoked",
1074
+ "unauthorized"
1075
+ );
1076
+ tokens.evict(connectionId);
1077
+ await emit({
1078
+ type: "connection.revoked",
1079
+ tenantId,
1080
+ connectionId,
1081
+ reason: "unauthorized",
1082
+ at: now()
1083
+ });
1084
+ throw new (0, _chunkJZVDD4DLcjs.ConnectionRevokedError)("unauthorized", {
1085
+ tenantId,
1086
+ connectionId
1087
+ });
1088
+ }
1089
+ }
1090
+ try {
1091
+ await store.touchConnection(tenantId, connectionId, now());
1092
+ } catch (e3) {
1093
+ try {
1094
+ _optionalChain([logger, 'optionalAccess', _41 => _41.warn, 'call', _42 => _42("google touchConnection failed")]);
1095
+ } catch (e4) {
1096
+ }
1097
+ }
1098
+ return result;
1099
+ }
1100
+ const warn = (message) => {
1101
+ try {
1102
+ _optionalChain([google, 'access', _43 => _43[_chunkDPAPYMB3cjs.internals], 'access', _44 => _44.logger, 'optionalAccess', _45 => _45.warn, 'call', _46 => _46(message)]);
1103
+ } catch (e5) {
1104
+ }
1105
+ };
1106
+ const getManaged = async (accessToken, eventId, tenantId) => {
1107
+ let e;
1108
+ try {
1109
+ e = await retry(() => transport.get({ accessToken, eventId }));
1110
+ } catch (err) {
1111
+ if (err instanceof EventGoneSignal) throw new (0, _chunkJZVDD4DLcjs.EventNotFoundError)();
1112
+ throw err;
1113
+ }
1114
+ assertManaged(e, tenantId);
1115
+ return e;
1116
+ };
1117
+ async function pollConference(accessToken, eventId, from) {
1118
+ let event = from;
1119
+ for (const ms of CONFERENCE_POLL_MS) {
1120
+ if (meetReady(event) || conferenceStatus(event) !== "pending") break;
1121
+ await sleep(ms);
1122
+ event = await retry(() => transport.get({ accessToken, eventId }));
1123
+ }
1124
+ return event;
1125
+ }
1126
+ async function getAvailability(input) {
1127
+ return (await availabilityOf(input)).availability;
1128
+ }
1129
+ async function availabilityOf(input) {
1130
+ const { attendees, window } = validateAvailabilityInput(input);
1131
+ const { tenantId, connectionId } = input;
1132
+ let raw;
1133
+ try {
1134
+ raw = await withToken(
1135
+ tenantId,
1136
+ connectionId,
1137
+ (accessToken) => retry(
1138
+ () => transport.freeBusy({
1139
+ accessToken,
1140
+ timeMin: window.start.toISOString(),
1141
+ timeMax: window.end.toISOString(),
1142
+ emails: attendees
1143
+ })
1144
+ )
1145
+ );
1146
+ } catch (err) {
1147
+ throw sanitize(err);
1148
+ }
1149
+ const byLower = new Map(
1150
+ Object.entries(raw).map(([k, v]) => [k.toLowerCase(), v])
1151
+ );
1152
+ const out = {};
1153
+ for (const email of attendees) {
1154
+ const cal = byLower.get(email);
1155
+ if (cal === void 0) {
1156
+ out[email] = { status: "unknown", reason: "error" };
1157
+ } else if (cal.errors.length > 0) {
1158
+ out[email] = {
1159
+ status: "unknown",
1160
+ reason: _nullishCoalesce(REASONS[_nullishCoalesce(_optionalChain([cal, 'access', _47 => _47.errors, 'access', _48 => _48[0], 'optionalAccess', _49 => _49.reason]), () => ( ""))], () => ( "error"))
1161
+ };
1162
+ } else {
1163
+ out[email] = { status: "ok", busy: mergeBusy(cal.busy, window) };
1164
+ }
1165
+ }
1166
+ return { availability: out, window };
1167
+ }
1168
+ async function createEvent(input) {
1169
+ for (const field of ["tenantId", "connectionId", "actorId"]) {
1170
+ if (typeof _optionalChain([input, 'optionalAccess', _50 => _50[field]]) !== "string" || input[field] === "") {
1171
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
1172
+ }
1173
+ }
1174
+ validateCreateInput(input, "");
1175
+ const { tenantId, connectionId, actorId } = input;
1176
+ const { emit, now, logger } = google[_chunkDPAPYMB3cjs.internals];
1177
+ let ownInsertMayHaveLanded = false;
1178
+ let released = false;
1179
+ let releaseAttempted = false;
1180
+ try {
1181
+ const { event, created, ev } = await withToken(
1182
+ tenantId,
1183
+ connectionId,
1184
+ async (accessToken, connection) => {
1185
+ const ev2 = validateCreateInput(input, connection.email);
1186
+ const id = deriveEventId(
1187
+ tenantId,
1188
+ connection.email,
1189
+ ev2.idempotencyKey
1190
+ );
1191
+ const fp = fingerprint(ev2);
1192
+ const meet = ev2.meeting.type === "google_meet";
1193
+ const body = eventBody(id, ev2, {
1194
+ tenantId,
1195
+ key: ev2.idempotencyKey,
1196
+ fingerprint: fp
1197
+ });
1198
+ const sendUpdates = GOOGLE_SEND_UPDATES[ev2.sendUpdates];
1199
+ const getEv = () => retry(() => transport.get({ accessToken, eventId: id }));
1200
+ let event2;
1201
+ let created2;
1202
+ try {
1203
+ event2 = await retry(async () => {
1204
+ try {
1205
+ const out = await transport.insert({
1206
+ accessToken,
1207
+ event: body,
1208
+ sendUpdates: meet ? "none" : sendUpdates,
1209
+ conferenceDataVersion: meet ? 1 : 0
1210
+ });
1211
+ ownInsertMayHaveLanded = true;
1212
+ return out;
1213
+ } catch (err) {
1214
+ const status = _chunkS357VL5Vcjs.readStatus.call(void 0, _chunkS357VL5Vcjs.asErr.call(void 0, err));
1215
+ if (classifyCalendarError(err).kind === "retry" && status !== 429 && status !== 403) {
1216
+ ownInsertMayHaveLanded = true;
1217
+ }
1218
+ throw err;
1219
+ }
1220
+ });
1221
+ created2 = true;
1222
+ } catch (err) {
1223
+ if (!(err instanceof DuplicateEventSignal)) throw err;
1224
+ created2 = ownInsertMayHaveLanded;
1225
+ try {
1226
+ event2 = await getEv();
1227
+ } catch (err2) {
1228
+ if (err2 instanceof EventGoneSignal) {
1229
+ throw new (0, _chunkJZVDD4DLcjs.EventConflictError)(
1230
+ "An event with this idempotency key exists but cannot be read"
1231
+ );
1232
+ }
1233
+ throw err2;
1234
+ }
1235
+ assertReplayable(event2, tenantId, ev2.idempotencyKey, fp);
1236
+ }
1237
+ if (meet && inviteState(event2) === "pending") {
1238
+ const conf = await confirmConference(accessToken, id, event2);
1239
+ if (conf.releasedElsewhere) {
1240
+ event2 = conf.event;
1241
+ created2 = false;
1242
+ } else {
1243
+ const rel = await releaseInvites(
1244
+ accessToken,
1245
+ id,
1246
+ sendUpdates,
1247
+ conf.event
1248
+ );
1249
+ event2 = rel.event;
1250
+ released = rel.byUs;
1251
+ }
1252
+ } else if (created2 && !meet) {
1253
+ released = true;
1254
+ } else if (meet && releaseAttempted && inviteState(event2) === "sent") {
1255
+ released = true;
1256
+ }
1257
+ return { event: event2, created: created2, ev: ev2 };
1258
+ }
1259
+ );
1260
+ if (released) {
1261
+ await emit({
1262
+ type: "calendar_event.created",
1263
+ tenantId,
1264
+ actorId,
1265
+ connectionId,
1266
+ eventId: event.id,
1267
+ attendees: ev.attendees.map((a) => a.email),
1268
+ title: ev.title,
1269
+ start: ev.start,
1270
+ end: ev.end,
1271
+ at: now()
1272
+ });
1273
+ }
1274
+ return { ...toView(event), created };
1275
+ } catch (err) {
1276
+ const safe = sanitize(err);
1277
+ await emit({
1278
+ type: "calendar_event.failed",
1279
+ tenantId,
1280
+ actorId,
1281
+ connectionId,
1282
+ operation: "create",
1283
+ errorCode: safe.code,
1284
+ at: now()
1285
+ });
1286
+ throw safe;
1287
+ }
1288
+ function assertReplayable(e, tenant, key, fp) {
1289
+ const priv = _optionalChain([e, 'access', _51 => _51.extendedProperties, 'optionalAccess', _52 => _52.private]);
1290
+ if (_optionalChain([priv, 'optionalAccess', _53 => _53.mshindiGoogle]) !== "v1" || priv.mshindiTenant !== tenant || priv.mshindiKey !== key) {
1291
+ throw new (0, _chunkJZVDD4DLcjs.EventConflictError)(
1292
+ "An event with this id exists and is not owned by this idempotency key"
1293
+ );
1294
+ }
1295
+ if (e.status === "cancelled") {
1296
+ throw new (0, _chunkJZVDD4DLcjs.EventConflictError)(
1297
+ "The event for this idempotency key was cancelled; use a new idempotency key"
1298
+ );
1299
+ }
1300
+ if (priv.mshindiFingerprint !== fp) {
1301
+ throw new (0, _chunkJZVDD4DLcjs.EventConflictError)(
1302
+ "An event with this idempotency key exists with different details; use updateEvent to change it"
1303
+ );
1304
+ }
1305
+ }
1306
+ async function confirmConference(accessToken, eventId, inserted) {
1307
+ const getEv = () => retry(() => transport.get({ accessToken, eventId }));
1308
+ let event = await pollConference(accessToken, eventId, inserted);
1309
+ if (meetReady(event)) return { event, releasedElsewhere: false };
1310
+ try {
1311
+ for (let attempt = 0; attempt < RELEASE_ATTEMPTS; attempt++) {
1312
+ try {
1313
+ await retry(
1314
+ () => transport.delete({
1315
+ accessToken,
1316
+ eventId,
1317
+ sendUpdates: "none",
1318
+ ...event.etag !== void 0 && { ifMatch: event.etag }
1319
+ })
1320
+ );
1321
+ break;
1322
+ } catch (err) {
1323
+ if (!(err instanceof PreconditionFailedSignal)) throw err;
1324
+ const current = await getEv();
1325
+ if (current.status === "cancelled") break;
1326
+ if (inviteState(current) === "sent") {
1327
+ return { event: current, releasedElsewhere: true };
1328
+ }
1329
+ if (meetReady(current)) {
1330
+ return { event: current, releasedElsewhere: false };
1331
+ }
1332
+ event = current;
1333
+ if (attempt + 1 >= RELEASE_ATTEMPTS) throw err;
1334
+ }
1335
+ }
1336
+ } catch (e6) {
1337
+ try {
1338
+ _optionalChain([logger, 'optionalAccess', _54 => _54.warn, 'call', _55 => _55(
1339
+ "google calendar: could not withdraw event after Meet creation failed"
1340
+ )]);
1341
+ } catch (e7) {
1342
+ }
1343
+ }
1344
+ throw new (0, _chunkJZVDD4DLcjs.ConferencingUnavailableError)(
1345
+ "Google Meet link could not be created; the event was withdrawn without notifying guests. Retry with a new idempotency key.",
1346
+ { tenantId, connectionId }
1347
+ );
1348
+ }
1349
+ async function releaseInvites(accessToken, eventId, sendUpdates, observed) {
1350
+ if (inviteState(observed) === "sent") {
1351
+ return { event: observed, byUs: false };
1352
+ }
1353
+ let etag = observed.etag;
1354
+ for (let attempt = 0; ; attempt++) {
1355
+ try {
1356
+ releaseAttempted = true;
1357
+ const event = await transport.patch({
1358
+ accessToken,
1359
+ eventId,
1360
+ patch: {
1361
+ extendedProperties: { private: { mshindiInvite: "sent" } }
1362
+ },
1363
+ sendUpdates,
1364
+ conferenceDataVersion: 1,
1365
+ ...etag !== void 0 && { ifMatch: etag }
1366
+ });
1367
+ return { event, byUs: true };
1368
+ } catch (err) {
1369
+ const c = classifyCalendarError(err);
1370
+ if (c.kind !== "retry" && c.kind !== "precondition") {
1371
+ return rethrow(err);
1372
+ }
1373
+ const current = await retry(
1374
+ () => transport.get({ accessToken, eventId })
1375
+ );
1376
+ if (inviteState(current) === "sent") {
1377
+ return { event: current, byUs: c.kind === "retry" };
1378
+ }
1379
+ if (current.status === "cancelled") {
1380
+ throw new (0, _chunkJZVDD4DLcjs.EventConflictError)(
1381
+ "The event for this idempotency key was cancelled; use a new idempotency key"
1382
+ );
1383
+ }
1384
+ etag = current.etag;
1385
+ const tooLong = c.kind === "retry" && c.delayMs !== null && c.delayMs > BACKOFF_CAP_MS;
1386
+ if (attempt + 1 >= RELEASE_ATTEMPTS || tooLong) return rethrow(err);
1387
+ if (c.kind === "retry") {
1388
+ await sleep(
1389
+ _nullishCoalesce(c.delayMs, () => ( random() * Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt)))
1390
+ );
1391
+ }
1392
+ }
1393
+ }
1394
+ }
1395
+ }
1396
+ async function updateEvent(input) {
1397
+ requireIds(input, [
1398
+ "tenantId",
1399
+ "connectionId",
1400
+ "actorId",
1401
+ "eventId"
1402
+ ]);
1403
+ validateChanges(input.changes, "");
1404
+ const sendUpdates = parseSendUpdates(input.sendUpdates);
1405
+ const { tenantId, connectionId, actorId, eventId } = input;
1406
+ const { emit, now } = google[_chunkDPAPYMB3cjs.internals];
1407
+ let attempted = null;
1408
+ try {
1409
+ const out = await withToken(
1410
+ tenantId,
1411
+ connectionId,
1412
+ async (accessToken, connection) => {
1413
+ const changes = validateChanges(input.changes, connection.email);
1414
+ const current = await getManaged(accessToken, eventId, tenantId);
1415
+ if (current.status === "cancelled") throw new (0, _chunkJZVDD4DLcjs.EventCancelledError)();
1416
+ if (!_optionalChain([current, 'access', _56 => _56.start, 'optionalAccess', _57 => _57.dateTime]) || !_optionalChain([current, 'access', _58 => _58.end, 'optionalAccess', _59 => _59.dateTime])) {
1417
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("start");
1418
+ }
1419
+ const before = toNormalized(current);
1420
+ if (Number.isNaN(before.start.getTime()) || Number.isNaN(before.end.getTime())) {
1421
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("start");
1422
+ }
1423
+ const wanted = withKnownNames(before, changes);
1424
+ const next = { ...before, ...wanted };
1425
+ const span = next.end.getTime() - next.start.getTime();
1426
+ if (!(span > 0 && span <= MAX_EVENT_MS2)) {
1427
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)("end");
1428
+ }
1429
+ const changed = changedKeys(current, before, wanted);
1430
+ if (changed.length === 0) {
1431
+ return {
1432
+ event: current,
1433
+ next,
1434
+ changed: _nullishCoalesce(_optionalChain([attempted, 'optionalAccess', _60 => _60.changed]), () => ( null))
1435
+ };
1436
+ }
1437
+ const body = updatePatch(current, next, changed, fingerprint(next));
1438
+ attempted = { changed };
1439
+ let event = await patchVerified(accessToken, body, next, changed);
1440
+ if (body.requestId !== null) {
1441
+ try {
1442
+ event = await pollConference(accessToken, eventId, event);
1443
+ } catch (e8) {
1444
+ }
1445
+ if (!meetReady(event)) {
1446
+ warn(
1447
+ "google calendar: Meet link could not be created while updating an event"
1448
+ );
1449
+ }
1450
+ }
1451
+ return { event, next, changed };
1452
+ }
1453
+ );
1454
+ if (out.changed !== null) {
1455
+ await emit({
1456
+ type: "calendar_event.updated",
1457
+ tenantId,
1458
+ actorId,
1459
+ connectionId,
1460
+ eventId,
1461
+ attendees: out.next.attendees.map((a) => a.email),
1462
+ title: out.next.title,
1463
+ start: out.next.start,
1464
+ end: out.next.end,
1465
+ changed: out.changed,
1466
+ at: now()
1467
+ });
1468
+ }
1469
+ return toView(out.event);
1470
+ } catch (err) {
1471
+ throw await failed(err, "update", { tenantId, actorId, connectionId });
1472
+ }
1473
+ async function patchVerified(accessToken, body, next, changed) {
1474
+ const landed = (e) => {
1475
+ const got = toNormalized(e);
1476
+ return changed.every((k) => same(k, got, next)) && (body.requestId === null || _optionalChain([e, 'access', _61 => _61.conferenceData, 'optionalAccess', _62 => _62.createRequest, 'optionalAccess', _63 => _63.requestId]) === body.requestId);
1477
+ };
1478
+ for (let attempt = 0; ; attempt++) {
1479
+ try {
1480
+ return await transport.patch({
1481
+ accessToken,
1482
+ eventId,
1483
+ patch: body.patch,
1484
+ sendUpdates,
1485
+ conferenceDataVersion: body.conferenceDataVersion
1486
+ });
1487
+ } catch (err) {
1488
+ const c = classifyCalendarError(err);
1489
+ if (c.kind !== "retry") return rethrow(err);
1490
+ const current = await getManaged(accessToken, eventId, tenantId);
1491
+ if (current.status === "cancelled") throw new (0, _chunkJZVDD4DLcjs.EventCancelledError)();
1492
+ if (landed(current)) return current;
1493
+ const tooLong = c.delayMs !== null && c.delayMs > BACKOFF_CAP_MS;
1494
+ if (attempt + 1 >= PATCH_ATTEMPTS || tooLong) return rethrow(err);
1495
+ await sleep(
1496
+ _nullishCoalesce(c.delayMs, () => ( random() * Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt)))
1497
+ );
1498
+ }
1499
+ }
1500
+ }
1501
+ }
1502
+ async function cancelEvent(input) {
1503
+ requireIds(input, [
1504
+ "tenantId",
1505
+ "connectionId",
1506
+ "actorId",
1507
+ "eventId"
1508
+ ]);
1509
+ const sendUpdates = parseSendUpdates(input.sendUpdates);
1510
+ const { tenantId, connectionId, actorId, eventId } = input;
1511
+ const { emit, now } = google[_chunkDPAPYMB3cjs.internals];
1512
+ let ownDeleteMayHaveLanded = false;
1513
+ try {
1514
+ const cancelled = await withToken(
1515
+ tenantId,
1516
+ connectionId,
1517
+ async (accessToken) => {
1518
+ const current = await getManaged(accessToken, eventId, tenantId);
1519
+ if (current.status === "cancelled") {
1520
+ return ownDeleteMayHaveLanded ? current : null;
1521
+ }
1522
+ try {
1523
+ await retry(async () => {
1524
+ try {
1525
+ await transport.delete({
1526
+ accessToken,
1527
+ eventId,
1528
+ // Guests of a pending event were never invited (D§5.3.1).
1529
+ sendUpdates: inviteState(current) === "pending" ? "none" : sendUpdates
1530
+ });
1531
+ } catch (err) {
1532
+ const status = _chunkS357VL5Vcjs.readStatus.call(void 0, _chunkS357VL5Vcjs.asErr.call(void 0, err));
1533
+ if (classifyCalendarError(err).kind === "retry" && status !== 429 && status !== 403) {
1534
+ ownDeleteMayHaveLanded = true;
1535
+ }
1536
+ throw err;
1537
+ }
1538
+ });
1539
+ } catch (err) {
1540
+ if (!(err instanceof EventGoneSignal)) throw err;
1541
+ if (!ownDeleteMayHaveLanded) return null;
1542
+ }
1543
+ return current;
1544
+ }
1545
+ );
1546
+ if (cancelled !== null) {
1547
+ const ev = toNormalized(cancelled);
1548
+ await emit({
1549
+ type: "calendar_event.cancelled",
1550
+ tenantId,
1551
+ actorId,
1552
+ connectionId,
1553
+ eventId,
1554
+ attendees: ev.attendees.map((a) => a.email),
1555
+ title: ev.title,
1556
+ start: ev.start,
1557
+ end: ev.end,
1558
+ at: now()
1559
+ });
1560
+ }
1561
+ } catch (err) {
1562
+ throw await failed(err, "cancel", { tenantId, actorId, connectionId });
1563
+ }
1564
+ }
1565
+ async function failed(err, operation, ids) {
1566
+ const safe = sanitize(err);
1567
+ const { emit, now } = google[_chunkDPAPYMB3cjs.internals];
1568
+ await emit({
1569
+ type: "calendar_event.failed",
1570
+ ...ids,
1571
+ operation,
1572
+ errorCode: safe.code,
1573
+ at: now()
1574
+ });
1575
+ return safe;
1576
+ }
1577
+ return {
1578
+ getAvailability,
1579
+ createEvent,
1580
+ updateEvent,
1581
+ cancelEvent,
1582
+ async suggestSlots(input) {
1583
+ validateAvailabilityInput(input);
1584
+ parseSlotParams(input);
1585
+ const { availability, window } = await availabilityOf(input);
1586
+ const unknownAttendees = Object.entries(availability).filter(([, v]) => v.status === "unknown").map(([k]) => k);
1587
+ if (unknownAttendees.length > 0) return { slots: [], unknownAttendees };
1588
+ const busy = {};
1589
+ for (const [email, v] of Object.entries(availability)) {
1590
+ if (v.status === "ok") busy[email] = v.busy;
1591
+ }
1592
+ const slots = findCommonSlots({
1593
+ now: google[_chunkDPAPYMB3cjs.internals].now(),
1594
+ window,
1595
+ durationMinutes: input.durationMinutes,
1596
+ workingHours: input.workingHours,
1597
+ busy,
1598
+ ...input.workingHoursByAttendee !== void 0 && {
1599
+ workingHoursByAttendee: input.workingHoursByAttendee
1600
+ },
1601
+ ...input.bufferMinutes !== void 0 && {
1602
+ bufferMinutes: input.bufferMinutes
1603
+ },
1604
+ ...input.stepMinutes !== void 0 && {
1605
+ stepMinutes: input.stepMinutes
1606
+ },
1607
+ ...input.minNoticeMinutes !== void 0 && {
1608
+ minNoticeMinutes: input.minNoticeMinutes
1609
+ },
1610
+ ...input.maxResults !== void 0 && { maxResults: input.maxResults }
1611
+ });
1612
+ return { slots };
1613
+ },
1614
+ async getEvent(input) {
1615
+ for (const field of ["tenantId", "connectionId", "eventId"]) {
1616
+ if (typeof _optionalChain([input, 'optionalAccess', _64 => _64[field]]) !== "string" || input[field] === "") {
1617
+ throw new (0, _chunkJZVDD4DLcjs.InvalidEventError)(field);
1618
+ }
1619
+ }
1620
+ const { tenantId, connectionId, eventId } = input;
1621
+ let ev;
1622
+ try {
1623
+ ev = await withToken(
1624
+ tenantId,
1625
+ connectionId,
1626
+ (accessToken) => retry(() => transport.get({ accessToken, eventId }))
1627
+ );
1628
+ } catch (err) {
1629
+ throw sanitize(err);
1630
+ }
1631
+ assertManaged(ev, tenantId);
1632
+ return toView(ev);
1633
+ }
1634
+ };
1635
+ }
1636
+
1637
+
1638
+
1639
+
1640
+ exports.createCalendar = createCalendar; exports.createCalendarApiTransport = createCalendarApiTransport; exports.findCommonSlots = findCommonSlots;
1641
+ //# sourceMappingURL=calendar.cjs.map