@mshindi-labs/google 1.1.0 → 1.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.
Files changed (80) hide show
  1. package/README.md +9 -4
  2. package/dist/calendar.cjs +1593 -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 +1593 -0
  7. package/dist/calendar.js.map +1 -0
  8. package/dist/chunk-2MJE3WQ5.js +63 -0
  9. package/dist/chunk-2MJE3WQ5.js.map +1 -0
  10. package/dist/chunk-4UEM6VO4.cjs +119 -0
  11. package/dist/chunk-4UEM6VO4.cjs.map +1 -0
  12. package/dist/{chunk-RWT25QHA.js → chunk-6VGR73PY.js} +87 -2
  13. package/dist/chunk-6VGR73PY.js.map +1 -0
  14. package/dist/{chunk-SIDO26T7.js → chunk-7YVRJ3GY.js} +12 -4
  15. package/dist/chunk-7YVRJ3GY.js.map +1 -0
  16. package/dist/chunk-7ZLAL7UY.cjs +63 -0
  17. package/dist/chunk-7ZLAL7UY.cjs.map +1 -0
  18. package/dist/chunk-BYHOVCN3.cjs +20 -0
  19. package/dist/chunk-BYHOVCN3.cjs.map +1 -0
  20. package/dist/chunk-FPEP5FL5.js +87 -0
  21. package/dist/chunk-FPEP5FL5.js.map +1 -0
  22. package/dist/chunk-JA2JLBNN.js +119 -0
  23. package/dist/chunk-JA2JLBNN.js.map +1 -0
  24. package/dist/{chunk-VN5VWVCT.cjs → chunk-KFQ4O6MT.cjs} +64 -56
  25. package/dist/chunk-KFQ4O6MT.cjs.map +1 -0
  26. package/dist/chunk-LWCB3V7V.js +20 -0
  27. package/dist/chunk-LWCB3V7V.js.map +1 -0
  28. package/dist/{chunk-KJPQ3DMR.cjs → chunk-RWRVNSQG.cjs} +6 -6
  29. package/dist/{chunk-KJPQ3DMR.cjs.map → chunk-RWRVNSQG.cjs.map} +1 -1
  30. package/dist/{chunk-Z7O6GO3C.js → chunk-UR3KSPDZ.js} +2 -2
  31. package/dist/{chunk-SHDP4A3A.cjs → chunk-UUXXCUIB.cjs} +87 -2
  32. package/dist/chunk-UUXXCUIB.cjs.map +1 -0
  33. package/dist/{chunk-V22QP2AM.cjs → chunk-V5Q6XSYZ.cjs} +3 -3
  34. package/dist/{chunk-V22QP2AM.cjs.map → chunk-V5Q6XSYZ.cjs.map} +1 -1
  35. package/dist/chunk-X7QL7AQ6.cjs +87 -0
  36. package/dist/chunk-X7QL7AQ6.cjs.map +1 -0
  37. package/dist/{chunk-JVP7HHFU.js → chunk-ZPDFK5VR.js} +2 -2
  38. package/dist/core.cjs +40 -18
  39. package/dist/core.cjs.map +1 -1
  40. package/dist/core.d.cts +40 -4
  41. package/dist/core.d.ts +40 -4
  42. package/dist/core.js +26 -4
  43. package/dist/core.js.map +1 -1
  44. package/dist/{create-google-CPGcK-3G.d.cts → create-google-B0fX1ixG.d.cts} +3 -1
  45. package/dist/{create-google-nP9f9jd9.d.ts → create-google-CjsKhktN.d.ts} +3 -1
  46. package/dist/{events-BsWOMtza.d.ts → events-BlC10ISp.d.cts} +31 -0
  47. package/dist/{events-BsWOMtza.d.cts → events-BlC10ISp.d.ts} +31 -0
  48. package/dist/gmail.cjs +54 -79
  49. package/dist/gmail.cjs.map +1 -1
  50. package/dist/gmail.d.cts +2 -2
  51. package/dist/gmail.d.ts +2 -2
  52. package/dist/gmail.js +19 -44
  53. package/dist/gmail.js.map +1 -1
  54. package/dist/postgres.cjs +8 -8
  55. package/dist/postgres.d.cts +1 -1
  56. package/dist/postgres.d.ts +1 -1
  57. package/dist/postgres.js +1 -1
  58. package/dist/sheets.cjs +1317 -0
  59. package/dist/sheets.cjs.map +1 -0
  60. package/dist/sheets.d.cts +292 -0
  61. package/dist/sheets.d.ts +292 -0
  62. package/dist/sheets.js +1317 -0
  63. package/dist/sheets.js.map +1 -0
  64. package/dist/testing.cjs +1119 -39
  65. package/dist/testing.cjs.map +1 -1
  66. package/dist/testing.d.cts +223 -2
  67. package/dist/testing.d.ts +223 -2
  68. package/dist/testing.js +1110 -30
  69. package/dist/testing.js.map +1 -1
  70. package/dist/transport-DHApc5oq.d.cts +103 -0
  71. package/dist/transport-DHApc5oq.d.ts +103 -0
  72. package/dist/transport-uuotQ13Y.d.cts +137 -0
  73. package/dist/transport-uuotQ13Y.d.ts +137 -0
  74. package/package.json +35 -4
  75. package/dist/chunk-RWT25QHA.js.map +0 -1
  76. package/dist/chunk-SHDP4A3A.cjs.map +0 -1
  77. package/dist/chunk-SIDO26T7.js.map +0 -1
  78. package/dist/chunk-VN5VWVCT.cjs.map +0 -1
  79. /package/dist/{chunk-Z7O6GO3C.js.map → chunk-UR3KSPDZ.js.map} +0 -0
  80. /package/dist/{chunk-JVP7HHFU.js.map → chunk-ZPDFK5VR.js.map} +0 -0
package/dist/testing.cjs CHANGED
@@ -1,22 +1,25 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class; var _class2; var _class3;
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; } var _class; var _class2; var _class3; var _class4; var _class5;
2
2
 
3
- var _chunkKJPQ3DMRcjs = require('./chunk-KJPQ3DMR.cjs');
3
+ var _chunkRWRVNSQGcjs = require('./chunk-RWRVNSQG.cjs');
4
4
 
5
5
 
6
+ var _chunk4UEM6VO4cjs = require('./chunk-4UEM6VO4.cjs');
6
7
 
7
8
 
8
9
 
9
- var _chunkV22QP2AMcjs = require('./chunk-V22QP2AM.cjs');
10
10
 
11
11
 
12
- var _chunkSHDP4A3Acjs = require('./chunk-SHDP4A3A.cjs');
12
+ var _chunkV5Q6XSYZcjs = require('./chunk-V5Q6XSYZ.cjs');
13
+
14
+
15
+ var _chunkUUXXCUIBcjs = require('./chunk-UUXXCUIB.cjs');
13
16
 
14
17
  // src/testing/local-key-provider.ts
15
18
  var _crypto = require('crypto');
16
- var LocalKeyProvider = class extends _chunkKJPQ3DMRcjs.StaticKeyProvider {
19
+ var LocalKeyProvider = class extends _chunkRWRVNSQGcjs.StaticKeyProvider {
17
20
  constructor(opts = {}) {
18
21
  if (process.env.NODE_ENV === "production" && !opts.allowInProduction) {
19
- throw new (0, _chunkSHDP4A3Acjs.InvalidConfigError)(
22
+ throw new (0, _chunkUUXXCUIBcjs.InvalidConfigError)(
20
23
  "LocalKeyProvider must not be used in production (pass allowInProduction: true to override)"
21
24
  );
22
25
  }
@@ -329,7 +332,7 @@ function runStoreContractTests(name, makeStore, api) {
329
332
  expect(await store.replaceEncryptedValue(ref, ev("hijacked"))).toBe(
330
333
  false
331
334
  );
332
- } catch (e) {
335
+ } catch (e2) {
333
336
  }
334
337
  }
335
338
  expect((await store.getConnection("t1", C(1))).refreshToken.ct).toBe(
@@ -410,24 +413,24 @@ function runStoreContractTests(name, makeStore, api) {
410
413
  it("touchConnection sets lastUsedAt", async () => {
411
414
  await seedClients();
412
415
  await store.upsertConnection(conn(C(1), "t1", "sub1"));
413
- const at = /* @__PURE__ */ new Date("2026-02-02T10:00:00.000Z");
414
- await store.touchConnection("t1", C(1), at);
416
+ const at2 = /* @__PURE__ */ new Date("2026-02-02T10:00:00.000Z");
417
+ await store.touchConnection("t1", C(1), at2);
415
418
  const got = await store.getConnection("t1", C(1));
416
419
  expect(got.lastUsedAt).toBeInstanceOf(Date);
417
- expect(got.lastUsedAt.getTime()).toBe(at.getTime());
420
+ expect(got.lastUsedAt.getTime()).toBe(at2.getTime());
418
421
  });
419
422
  it("setConnectionDisplayName updates displayName and updatedAt only", async () => {
420
423
  await seedClients();
421
424
  const original = conn(C(1), "t1", "sub1");
422
425
  await store.upsertConnection(original);
423
- const at = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
424
- expect(await store.setConnectionDisplayName("t1", C(1), "HR", at)).toBe(
426
+ const at2 = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
427
+ expect(await store.setConnectionDisplayName("t1", C(1), "HR", at2)).toBe(
425
428
  true
426
429
  );
427
430
  const got = await store.getConnection("t1", C(1));
428
- expect(got).toEqual({ ...original, displayName: "HR", updatedAt: at });
431
+ expect(got).toEqual({ ...original, displayName: "HR", updatedAt: at2 });
429
432
  expect(got.updatedAt).toBeInstanceOf(Date);
430
- expect(await store.setConnectionDisplayName("t1", C(1), null, at)).toBe(
433
+ expect(await store.setConnectionDisplayName("t1", C(1), null, at2)).toBe(
431
434
  true
432
435
  );
433
436
  expect((await store.getConnection("t1", C(1))).displayName).toBeNull();
@@ -440,8 +443,8 @@ function runStoreContractTests(name, makeStore, api) {
440
443
  });
441
444
  const before = await store.getConnection("t1", C(1));
442
445
  expect(before.status).toBe("revoked");
443
- const at = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
444
- expect(await store.setConnectionDisplayName("t1", C(1), "HR", at)).toBe(
446
+ const at2 = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
447
+ expect(await store.setConnectionDisplayName("t1", C(1), "HR", at2)).toBe(
445
448
  true
446
449
  );
447
450
  const got = await store.getConnection("t1", C(1));
@@ -454,15 +457,15 @@ function runStoreContractTests(name, makeStore, api) {
454
457
  await seedClients();
455
458
  const original = conn(C(1), "t1", "sub1");
456
459
  await store.upsertConnection(original);
457
- const at = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
458
- expect(await store.setConnectionDisplayName("t2", C(1), "X", at)).toBe(
460
+ const at2 = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
461
+ expect(await store.setConnectionDisplayName("t2", C(1), "X", at2)).toBe(
459
462
  false
460
463
  );
461
- expect(await store.setConnectionDisplayName("t1", C(9), "X", at)).toBe(
464
+ expect(await store.setConnectionDisplayName("t1", C(9), "X", at2)).toBe(
462
465
  false
463
466
  );
464
467
  expect(
465
- await store.setConnectionDisplayName("t1", "not-a-uuid", "X", at)
468
+ await store.setConnectionDisplayName("t1", "not-a-uuid", "X", at2)
466
469
  ).toBe(false);
467
470
  expect(await store.getConnection("t1", C(1))).toEqual(original);
468
471
  expect(await store.getConnection("t2", C(1))).toBeNull();
@@ -471,15 +474,15 @@ function runStoreContractTests(name, makeStore, api) {
471
474
  await seedClients();
472
475
  const original = conn(C(1), "t1", "sub1", { displayName: "HR" });
473
476
  await store.upsertConnection(original);
474
- const at = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
475
- expect(await store.disconnectConnection("t1", C(1), at)).toBe(true);
477
+ const at2 = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
478
+ expect(await store.disconnectConnection("t1", C(1), at2)).toBe(true);
476
479
  const got = await store.getConnection("t1", C(1));
477
480
  expect(got).toEqual({
478
481
  ...original,
479
482
  refreshToken: null,
480
483
  status: "revoked",
481
484
  statusReason: "disconnected",
482
- updatedAt: at
485
+ updatedAt: at2
483
486
  });
484
487
  const refs = [];
485
488
  for await (const r of store.iterateEncryptedValues(10)) refs.push(r);
@@ -489,10 +492,10 @@ function runStoreContractTests(name, makeStore, api) {
489
492
  await seedClients();
490
493
  const original = conn(C(1), "t1", "sub1");
491
494
  await store.upsertConnection(original);
492
- const at = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
493
- expect(await store.disconnectConnection("t2", C(1), at)).toBe(false);
494
- expect(await store.disconnectConnection("t1", C(9), at)).toBe(false);
495
- expect(await store.disconnectConnection("t1", "not-a-uuid", at)).toBe(
495
+ const at2 = /* @__PURE__ */ new Date("2026-03-03T03:00:00.000Z");
496
+ expect(await store.disconnectConnection("t2", C(1), at2)).toBe(false);
497
+ expect(await store.disconnectConnection("t1", C(9), at2)).toBe(false);
498
+ expect(await store.disconnectConnection("t1", "not-a-uuid", at2)).toBe(
496
499
  false
497
500
  );
498
501
  expect(await store.getConnection("t1", C(1))).toEqual(original);
@@ -569,24 +572,24 @@ var InMemoryStore = (_class = class {constructor() { _class.prototype.__init.cal
569
572
  c.statusReason = reason;
570
573
  }
571
574
  }
572
- async touchConnection(tenantId, connectionId, at) {
575
+ async touchConnection(tenantId, connectionId, at2) {
573
576
  const c = this.connections.get(connectionId);
574
- if (c && c.tenantId === tenantId) c.lastUsedAt = new Date(at.getTime());
577
+ if (c && c.tenantId === tenantId) c.lastUsedAt = new Date(at2.getTime());
575
578
  }
576
- async setConnectionDisplayName(tenantId, connectionId, displayName, at) {
579
+ async setConnectionDisplayName(tenantId, connectionId, displayName, at2) {
577
580
  const c = this.connections.get(connectionId);
578
581
  if (!c || c.tenantId !== tenantId) return false;
579
582
  c.displayName = displayName;
580
- c.updatedAt = new Date(at.getTime());
583
+ c.updatedAt = new Date(at2.getTime());
581
584
  return true;
582
585
  }
583
- async disconnectConnection(tenantId, connectionId, at) {
586
+ async disconnectConnection(tenantId, connectionId, at2) {
584
587
  const c = this.connections.get(connectionId);
585
588
  if (!c || c.tenantId !== tenantId) return false;
586
589
  c.refreshToken = null;
587
590
  c.status = "revoked";
588
591
  c.statusReason = "disconnected";
589
- c.updatedAt = new Date(at.getTime());
592
+ c.updatedAt = new Date(at2.getTime());
590
593
  return true;
591
594
  }
592
595
  async insertOAuthState(rec) {
@@ -694,8 +697,8 @@ var FakeGoogleOAuth = (_class2 = class {
694
697
  }
695
698
  consent(authUrl, account) {
696
699
  const parsed = new URL(authUrl);
697
- if (parsed.origin + parsed.pathname !== _chunkV22QP2AMcjs.AUTH_ENDPOINT)
698
- throw new Error(`Auth URL must target the endpoint ${_chunkV22QP2AMcjs.AUTH_ENDPOINT}`);
700
+ if (parsed.origin + parsed.pathname !== _chunkV5Q6XSYZcjs.AUTH_ENDPOINT)
701
+ throw new Error(`Auth URL must target the endpoint ${_chunkV5Q6XSYZcjs.AUTH_ENDPOINT}`);
699
702
  const q = parsed.searchParams;
700
703
  for (const [k, v] of [
701
704
  ["response_type", "code"],
@@ -727,7 +730,7 @@ var FakeGoogleOAuth = (_class2 = class {
727
730
  if (c.clientId !== p.clientId) throw new Error("invalid_client");
728
731
  if (c.redirectUri !== p.redirectUri)
729
732
  throw new Error("redirect_uri_mismatch");
730
- if (_chunkV22QP2AMcjs.codeChallenge.call(void 0, p.codeVerifier) !== c.challenge)
733
+ if (_chunkV5Q6XSYZcjs.codeChallenge.call(void 0, p.codeVerifier) !== c.challenge)
731
734
  throw new Error("invalid_grant: PKCE verifier mismatch");
732
735
  const id = ++this.n;
733
736
  const idToken = `fake-id.${id}`;
@@ -760,7 +763,7 @@ var FakeGoogleOAuth = (_class2 = class {
760
763
  this.calls.push({ method: "refreshAccessToken" });
761
764
  const owner = this.refreshTokens.get(p.refreshToken);
762
765
  if (owner === void 0 || owner !== p.clientId || this.failing.has(p.refreshToken) || this.revoked.includes(p.refreshToken)) {
763
- throw new (0, _chunkV22QP2AMcjs.InvalidGrantError)();
766
+ throw new (0, _chunkV5Q6XSYZcjs.InvalidGrantError)();
764
767
  }
765
768
  return {
766
769
  accessToken: `ya29.fake-access-${++this.n}`,
@@ -786,7 +789,7 @@ var CaptureTransport = (_class3 = class {constructor() { _class3.prototype.__ini
786
789
  __init12() {this.messages = []}
787
790
  __init13() {this.n = 0}
788
791
  async send(p) {
789
- const mod = await _chunkV22QP2AMcjs.loadPeer.call(void 0,
792
+ const mod = await _chunkV5Q6XSYZcjs.loadPeer.call(void 0,
790
793
  "mailparser"
791
794
  );
792
795
  const { simpleParser } = mod.simpleParser ? mod : mod.default;
@@ -820,10 +823,1087 @@ var CaptureTransport = (_class3 = class {constructor() { _class3.prototype.__ini
820
823
  }
821
824
  }, _class3);
822
825
 
826
+ // src/testing/fake-calendar.ts
827
+ var clone2 = (v) => structuredClone(v);
828
+ function httpError(status, reason, message) {
829
+ return Object.assign(new Error(message), {
830
+ code: status,
831
+ response: {
832
+ status,
833
+ data: { error: { code: status, message, errors: [{ reason }] } }
834
+ }
835
+ });
836
+ }
837
+ var domainOf = (email) => email.slice(email.lastIndexOf("@") + 1).toLowerCase();
838
+ var FakeCalendar = (_class4 = class {
839
+ __init14() {this.events = /* @__PURE__ */ new Map()}
840
+ __init15() {this.calls = []}
841
+ __init16() {this.notifications = []}
842
+
843
+ __init17() {this.busy = /* @__PURE__ */ new Map()}
844
+ __init18() {this.failures = /* @__PURE__ */ new Map()}
845
+ __init19() {this.conference = "success"}
846
+ __init20() {this.pendingGets = 1}
847
+ __init21() {this.pendingLeft = /* @__PURE__ */ new Map()}
848
+ __init22() {this.etagN = 0}
849
+ __init23() {this.meetN = 0}
850
+ constructor(opts = {}) {;_class4.prototype.__init14.call(this);_class4.prototype.__init15.call(this);_class4.prototype.__init16.call(this);_class4.prototype.__init17.call(this);_class4.prototype.__init18.call(this);_class4.prototype.__init19.call(this);_class4.prototype.__init20.call(this);_class4.prototype.__init21.call(this);_class4.prototype.__init22.call(this);_class4.prototype.__init23.call(this);
851
+ this.organizerEmail = _nullishCoalesce(opts.organizerEmail, () => ( "organizer@example.com"));
852
+ }
853
+ setFreeBusy(email, busy) {
854
+ this.busy.set(email, busy);
855
+ }
856
+ setConferenceBehaviour(b, pendingGets = 1) {
857
+ this.conference = b;
858
+ this.pendingGets = pendingGets;
859
+ }
860
+ failNext(op, error, opts = {}) {
861
+ const q = _nullishCoalesce(this.failures.get(op), () => ( []));
862
+ for (let i = 0; i < (_nullishCoalesce(opts.times, () => ( 1))); i++) {
863
+ q.push({ error, afterApply: _nullishCoalesce(opts.afterApply, () => ( false)) });
864
+ }
865
+ this.failures.set(op, q);
866
+ }
867
+ async freeBusy(p) {
868
+ this.calls.push({ op: "freeBusy", emails: [...p.emails] });
869
+ return this.run("freeBusy", () => {
870
+ const out = {};
871
+ for (const email of p.emails) {
872
+ const cfg = this.busy.get(email);
873
+ if (cfg === void 0) out[email] = { busy: [], errors: [] };
874
+ else if (Array.isArray(cfg))
875
+ out[email] = { busy: clone2(cfg), errors: [] };
876
+ else out[email] = { busy: [], errors: [{ reason: cfg.error }] };
877
+ }
878
+ return out;
879
+ });
880
+ }
881
+ async insert(p) {
882
+ this.calls.push({ op: "insert", sendUpdates: p.sendUpdates });
883
+ return this.run("insert", () => {
884
+ if (this.events.has(p.event.id)) {
885
+ throw httpError(
886
+ 409,
887
+ "duplicate",
888
+ "The requested identifier already exists."
889
+ );
890
+ }
891
+ const ev2 = clone2(p.event);
892
+ ev2.status ??= "confirmed";
893
+ this.applyConference(ev2, p.conferenceDataVersion);
894
+ this.stamp(ev2);
895
+ this.events.set(ev2.id, ev2);
896
+ if (p.sendUpdates !== "none" && (_nullishCoalesce(_optionalChain([ev2, 'access', _ => _.attendees, 'optionalAccess', _2 => _2.length]), () => ( 0))) > 0) {
897
+ this.notify(ev2, "invite", p.sendUpdates);
898
+ }
899
+ return clone2(ev2);
900
+ });
901
+ }
902
+ async get(p) {
903
+ this.calls.push({ op: "get" });
904
+ return this.run("get", () => {
905
+ const ev2 = this.events.get(p.eventId);
906
+ if (!ev2) throw httpError(404, "notFound", "Not Found");
907
+ const reqId = _optionalChain([ev2, 'access', _3 => _3.conferenceData, 'optionalAccess', _4 => _4.createRequest, 'optionalAccess', _5 => _5.requestId]);
908
+ const key = `${ev2.id}:${_nullishCoalesce(reqId, () => ( ""))}`;
909
+ const left = this.pendingLeft.get(key);
910
+ if (left !== void 0) {
911
+ if (left > 0) {
912
+ this.pendingLeft.set(key, left - 1);
913
+ } else {
914
+ this.pendingLeft.delete(key);
915
+ this.completeConference(ev2);
916
+ }
917
+ }
918
+ return clone2(ev2);
919
+ });
920
+ }
921
+ async patch(p) {
922
+ this.calls.push({ op: "patch", sendUpdates: p.sendUpdates });
923
+ return this.run("patch", () => {
924
+ const ev2 = this.events.get(p.eventId);
925
+ if (!ev2) throw httpError(404, "notFound", "Not Found");
926
+ this.checkIfMatch(ev2, p.ifMatch);
927
+ const before = clone2(ev2);
928
+ const patch = clone2(p.patch);
929
+ const priv = _optionalChain([patch, 'access', _6 => _6.extendedProperties, 'optionalAccess', _7 => _7.private]);
930
+ delete patch.extendedProperties;
931
+ const { conferenceData, ...rest } = patch;
932
+ Object.assign(ev2, rest);
933
+ if (priv) {
934
+ ev2.extendedProperties = {
935
+ ...ev2.extendedProperties,
936
+ private: { ..._optionalChain([ev2, 'access', _8 => _8.extendedProperties, 'optionalAccess', _9 => _9.private]), ...priv }
937
+ };
938
+ }
939
+ if (conferenceData === null) {
940
+ delete ev2.conferenceData;
941
+ } else if (conferenceData !== void 0) {
942
+ ev2.conferenceData = conferenceData;
943
+ this.applyConference(ev2, p.conferenceDataVersion);
944
+ }
945
+ this.stamp(ev2);
946
+ if (p.sendUpdates !== "none") {
947
+ const changed = ["start", "end", "location", "attendees"].some((k) => JSON.stringify(before[k]) !== JSON.stringify(ev2[k]));
948
+ const flipped = _optionalChain([before, 'access', _10 => _10.extendedProperties, 'optionalAccess', _11 => _11.private, 'optionalAccess', _12 => _12.mshindiInvite]) === "pending" && _optionalChain([ev2, 'access', _13 => _13.extendedProperties, 'optionalAccess', _14 => _14.private, 'optionalAccess', _15 => _15.mshindiInvite]) === "sent";
949
+ if (flipped) this.notify(ev2, "invite", p.sendUpdates);
950
+ else if (changed) this.notify(ev2, "update", p.sendUpdates);
951
+ }
952
+ return clone2(ev2);
953
+ });
954
+ }
955
+ async delete(p) {
956
+ this.calls.push({ op: "delete", sendUpdates: p.sendUpdates });
957
+ return this.run("delete", () => {
958
+ const ev2 = this.events.get(p.eventId);
959
+ if (!ev2) throw httpError(404, "notFound", "Not Found");
960
+ this.checkIfMatch(ev2, p.ifMatch);
961
+ if (ev2.status === "cancelled") {
962
+ throw httpError(410, "deleted", "Resource has been deleted");
963
+ }
964
+ ev2.status = "cancelled";
965
+ this.stamp(ev2);
966
+ if (p.sendUpdates !== "none") this.notify(ev2, "cancel", p.sendUpdates);
967
+ });
968
+ }
969
+ clear() {
970
+ this.events.clear();
971
+ this.calls.length = 0;
972
+ this.notifications.length = 0;
973
+ }
974
+ run(op, fn) {
975
+ const f = _optionalChain([this, 'access', _16 => _16.failures, 'access', _17 => _17.get, 'call', _18 => _18(op), 'optionalAccess', _19 => _19.shift, 'call', _20 => _20()]);
976
+ if (f && !f.afterApply) throw f.error;
977
+ const result = fn();
978
+ if (f) throw f.error;
979
+ return result;
980
+ }
981
+ /** Google answers 412 when `If-Match` names an etag other than the current one. */
982
+ checkIfMatch(ev2, ifMatch) {
983
+ if (ifMatch !== void 0 && ifMatch !== ev2.etag) {
984
+ throw httpError(412, "conditionNotMet", "Precondition Failed");
985
+ }
986
+ }
987
+ /** Every applied mutation gets a new etag, as on Google. */
988
+ stamp(ev2) {
989
+ ev2.etag = `"fake-etag-${++this.etagN}"`;
990
+ ev2.htmlLink = `https://calendar.google.com/calendar/event?eid=${encodeURIComponent(ev2.id)}`;
991
+ ev2.updated = (/* @__PURE__ */ new Date()).toISOString();
992
+ }
993
+ notify(ev2, kind, mode) {
994
+ const org = domainOf(this.organizerEmail);
995
+ const to = (_nullishCoalesce(ev2.attendees, () => ( []))).flatMap((a) => a.email ? [a.email] : []).filter((e) => mode !== "externalOnly" || domainOf(e) !== org);
996
+ if (to.length > 0) this.notifications.push({ eventId: ev2.id, kind, to });
997
+ }
998
+ /** Resolves a `createRequest` the way Google does; ignored when version is 0. */
999
+ applyConference(ev2, version) {
1000
+ const cd = ev2.conferenceData;
1001
+ if (!_optionalChain([cd, 'optionalAccess', _21 => _21.createRequest])) return;
1002
+ if (version !== 1) {
1003
+ delete cd.createRequest;
1004
+ if (Object.keys(cd).length === 0) delete ev2.conferenceData;
1005
+ return;
1006
+ }
1007
+ cd.conferenceSolution = { key: { type: "hangoutsMeet" } };
1008
+ cd.createRequest.status = {
1009
+ statusCode: this.conference === "success" ? "success" : this.conference
1010
+ };
1011
+ if (this.conference === "success") this.addEntryPoint(ev2);
1012
+ if (this.conference === "pending") {
1013
+ this.pendingLeft.set(
1014
+ `${ev2.id}:${_nullishCoalesce(cd.createRequest.requestId, () => ( ""))}`,
1015
+ this.pendingGets
1016
+ );
1017
+ }
1018
+ }
1019
+ completeConference(ev2) {
1020
+ const req = _optionalChain([ev2, 'access', _22 => _22.conferenceData, 'optionalAccess', _23 => _23.createRequest]);
1021
+ if (!req) return;
1022
+ req.status = { statusCode: "success" };
1023
+ this.addEntryPoint(ev2);
1024
+ this.stamp(ev2);
1025
+ }
1026
+ addEntryPoint(ev2) {
1027
+ const cd = ev2.conferenceData;
1028
+ if (!cd) return;
1029
+ cd.entryPoints = [
1030
+ {
1031
+ entryPointType: "video",
1032
+ uri: `https://meet.google.com/fake-${++this.meetN}`
1033
+ }
1034
+ ];
1035
+ }
1036
+ }, _class4);
1037
+
1038
+ // src/testing/fake-sheets.ts
1039
+ var REQUEST_KEYS = new Set(
1040
+ "addBanding addChart addConditionalFormatRule addDataSource addDimensionGroup addFilterView addNamedRange addProtectedRange addSheet addSlicer addTable appendCells appendDimension autoFill autoResizeDimensions cancelDataSourceRefresh clearBasicFilter copyPaste createDeveloperMetadata cutPaste deleteBanding deleteConditionalFormatRule deleteDataSource deleteDeveloperMetadata deleteDimension deleteDimensionGroup deleteDuplicates deleteEmbeddedObject deleteFilterView deleteNamedRange deleteProtectedRange deleteRange deleteSheet deleteTable duplicateFilterView duplicateSheet findReplace insertDimension insertRange mergeCells moveDimension pasteData randomizeRange refreshDataSource repeatCell setBasicFilter setDataValidation sortRange textToColumns trimWhitespace unmergeCells updateBanding updateBorders updateCells updateChartSpec updateConditionalFormatRule updateDataSource updateDeveloperMetadata updateDimensionGroup updateDimensionProperties updateEmbeddedObjectBorder updateEmbeddedObjectPosition updateFilterView updateNamedRange updateProtectedRange updateSheetProperties updateSlicerSpec updateSpreadsheetProperties updateTable".split(" ")
1041
+ );
1042
+ var DEFAULT_ROWS = 1e3;
1043
+ var DEFAULT_COLUMNS = 26;
1044
+ var NUMBER = /^[+-]?\d+(\.\d+)?$/;
1045
+ var PERCENT = /^[+-]?\d+(\.\d+)?%$/;
1046
+ var BOOLEAN = /^(true|false)$/i;
1047
+ var DATE = /^(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?$/;
1048
+ var FIXED_YEAR = 2026;
1049
+ var NEEDS_FIELDS = new Set(
1050
+ "appendCells repeatCell updateBanding updateCells updateDataSource updateDeveloperMetadata updateDimensionGroup updateDimensionProperties updateEmbeddedObjectBorder updateFilterView updateNamedRange updateProtectedRange updateSlicerSpec updateSpreadsheetProperties updateTable".split(" ")
1051
+ );
1052
+ var NEEDS_RANGE = {
1053
+ repeatCell: [["range"]],
1054
+ mergeCells: [["range"]],
1055
+ unmergeCells: [["range"]],
1056
+ sortRange: [["range"]],
1057
+ updateBorders: [["range"]],
1058
+ setDataValidation: [["range"]],
1059
+ insertRange: [["range"]],
1060
+ deleteRange: [["range"]],
1061
+ updateCells: [["range", "start"]],
1062
+ setBasicFilter: [["filter.range", "filter.tableId"]],
1063
+ updateDimensionProperties: [["range", "dataSourceSheetRange"]],
1064
+ autoResizeDimensions: [["dimensions", "dataSourceSheetDimensions"]],
1065
+ copyPaste: [["source"], ["destination"]],
1066
+ cutPaste: [["source"], ["destination"]],
1067
+ moveDimension: [["source"]]
1068
+ };
1069
+ var ON_SHEET = /* @__PURE__ */ new Set(["clearBasicFilter", "appendDimension"]);
1070
+ var clone3 = (v) => structuredClone(v);
1071
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1072
+ var sameTitle = (a, b) => a.toLowerCase() === b.toLowerCase();
1073
+ function sheetsHttpError(status, reason, message) {
1074
+ return Object.assign(new Error(message), {
1075
+ code: status,
1076
+ response: {
1077
+ status,
1078
+ data: { error: { code: status, message, errors: [{ reason }] } }
1079
+ }
1080
+ });
1081
+ }
1082
+ var badRequest = (message) => sheetsHttpError(400, "badRequest", message);
1083
+ var parseError = (ref) => badRequest(`Unable to parse range: ${ref}`);
1084
+ var CLEAR = "clear";
1085
+ var SKIP = "skip";
1086
+ function dateCell(m) {
1087
+ const month = Number(m[1]);
1088
+ const day = Number(m[2]);
1089
+ let year = m[3] === void 0 ? FIXED_YEAR : Number(m[3]);
1090
+ if (_optionalChain([m, 'access', _24 => _24[3], 'optionalAccess', _25 => _25.length]) === 2) year += year < 30 ? 2e3 : 1900;
1091
+ const ms = Date.UTC(year, month - 1, day);
1092
+ const d = new Date(ms);
1093
+ if (d.getUTCMonth() !== month - 1 || d.getUTCDate() !== day) return null;
1094
+ return { v: ms / 864e5 + 25569, fmt: `${month}/${day}/${year}` };
1095
+ }
1096
+ function userEntered(s) {
1097
+ if (s.startsWith("'")) return { v: s.slice(1) };
1098
+ if (s.startsWith("=")) return { v: "", f: s };
1099
+ if (NUMBER.test(s)) return { v: Number(s) };
1100
+ if (PERCENT.test(s)) return { v: Number(s.slice(0, -1)) / 100, fmt: s };
1101
+ if (BOOLEAN.test(s)) return { v: s.toLowerCase() === "true" };
1102
+ const date = DATE.exec(s);
1103
+ const asDate = date ? dateCell(date) : null;
1104
+ if (asDate) return asDate;
1105
+ if (s.startsWith("+") || s.startsWith("-")) return { v: "", f: s };
1106
+ return { v: s };
1107
+ }
1108
+ function toCell(value, option) {
1109
+ if (value === null || value === void 0) return SKIP;
1110
+ if (typeof value === "boolean") return { v: value };
1111
+ if (typeof value === "number") {
1112
+ if (!Number.isFinite(value))
1113
+ throw badRequest("Invalid values: non-finite number");
1114
+ return { v: value };
1115
+ }
1116
+ if (typeof value !== "string") {
1117
+ throw badRequest(
1118
+ "Invalid values: cells must be strings, numbers or booleans"
1119
+ );
1120
+ }
1121
+ if (value === "") return CLEAR;
1122
+ return option === "RAW" ? { v: value } : userEntered(value);
1123
+ }
1124
+ function render(cell, mode) {
1125
+ if (cell.f !== void 0) return mode === "FORMULA" ? cell.f : "";
1126
+ if (mode !== "FORMATTED_VALUE") return cell.v;
1127
+ if (cell.fmt !== void 0) return cell.fmt;
1128
+ if (typeof cell.v === "boolean") return cell.v ? "TRUE" : "FALSE";
1129
+ return String(cell.v);
1130
+ }
1131
+ function trimmed(tab, rows, cols, mode) {
1132
+ const out = [];
1133
+ const lastRow = Math.min(rows[1], tab.cells.length);
1134
+ for (let r = rows[0]; r <= lastRow; r++) {
1135
+ const src = _nullishCoalesce(tab.cells[r - 1], () => ( []));
1136
+ const row = [];
1137
+ let keep = 0;
1138
+ for (let c = cols[0]; c <= Math.min(cols[1], src.length); c++) {
1139
+ const cell = src[c - 1];
1140
+ row.push(cell ? render(cell, mode) : "");
1141
+ if (cell) keep = row.length;
1142
+ }
1143
+ out.push(row.slice(0, keep));
1144
+ }
1145
+ while (out.length > 0 && out[out.length - 1].length === 0) out.pop();
1146
+ return out;
1147
+ }
1148
+ function setCell(tab, r, c, cell) {
1149
+ if (cell === void 0 && c > (_nullishCoalesce(_optionalChain([tab, 'access', _26 => _26.cells, 'access', _27 => _27[r - 1], 'optionalAccess', _28 => _28.length]), () => ( 0)))) return;
1150
+ while (tab.cells.length < r) tab.cells.push([]);
1151
+ const row = tab.cells[r - 1];
1152
+ row[c - 1] = cell;
1153
+ }
1154
+ function tabPart(title) {
1155
+ const plain = /^[A-Za-z_][A-Za-z0-9_]*$/.test(title) && !/^[A-Za-z]{1,3}\d+$/.test(title) && // looks like a cell, e.g. A1
1156
+ !/^R\d*C\d*$/i.test(title);
1157
+ return plain ? title : _chunk4UEM6VO4cjs.a1.quoteTab(title);
1158
+ }
1159
+ var typed = (v) => typeof v === "number" ? { numberValue: v } : typeof v === "boolean" ? { boolValue: v } : { stringValue: v };
1160
+ function cellData(cell) {
1161
+ if (cell.f !== void 0)
1162
+ return { userEnteredValue: { formulaValue: cell.f } };
1163
+ return {
1164
+ userEnteredValue: typed(cell.v),
1165
+ effectiveValue: typed(cell.v),
1166
+ formattedValue: String(render(cell, "FORMATTED_VALUE"))
1167
+ };
1168
+ }
1169
+ function at(v, path) {
1170
+ return path.split(".").reduce((o, k) => isObj(o) ? o[k] : void 0, v);
1171
+ }
1172
+ function cellRef(row, col) {
1173
+ return `${_chunk4UEM6VO4cjs.a1.indexToColumn(col)}${row}`;
1174
+ }
1175
+ function blockRef(tab, r0, c0, r1, c1) {
1176
+ const tl = cellRef(r0, c0);
1177
+ return `${tabPart(tab.title)}!${r0 === r1 && c0 === c1 ? tl : `${tl}:${cellRef(r1, c1)}`}`;
1178
+ }
1179
+ function addPath(mask, path, sub) {
1180
+ let m = mask;
1181
+ for (const seg of path.slice(0, -1)) {
1182
+ const next = m.get(seg);
1183
+ if (next === true) return;
1184
+ if (next === void 0) m.set(seg, m = /* @__PURE__ */ new Map());
1185
+ else m = next;
1186
+ }
1187
+ const last = path[path.length - 1];
1188
+ const existing = m.get(last);
1189
+ if (existing === true || sub === true || existing === void 0) {
1190
+ m.set(last, existing === void 0 ? sub : true);
1191
+ } else {
1192
+ for (const [k, v] of sub) addPath(existing, [k], v);
1193
+ }
1194
+ }
1195
+ function parseMask(src) {
1196
+ const text = src.replace(/\s+/g, "");
1197
+ let i = 0;
1198
+ const invalid = () => badRequest(`Invalid field selection ${src}`);
1199
+ const list = () => {
1200
+ const mask2 = /* @__PURE__ */ new Map();
1201
+ for (; ; ) {
1202
+ const start = i;
1203
+ while (i < text.length && /[A-Za-z0-9_.*]/.test(text[i])) i++;
1204
+ const path = text.slice(start, i).split(".");
1205
+ if (path.some((seg) => seg === "")) throw invalid();
1206
+ let sub = true;
1207
+ if (text[i] === "(") {
1208
+ i++;
1209
+ sub = list();
1210
+ if (text[i] !== ")") throw invalid();
1211
+ i++;
1212
+ }
1213
+ addPath(mask2, path, sub);
1214
+ if (text[i] !== ",") return mask2;
1215
+ i++;
1216
+ }
1217
+ };
1218
+ const mask = list();
1219
+ if (i !== text.length) throw invalid();
1220
+ return mask;
1221
+ }
1222
+ function project(value, mask) {
1223
+ if (mask === true || mask.has("*")) return value;
1224
+ if (Array.isArray(value)) return value.map((v) => project(v, mask));
1225
+ if (!isObj(value)) return value;
1226
+ const out = {};
1227
+ for (const [k, sub] of mask) {
1228
+ if (value[k] !== void 0) out[k] = project(value[k], sub);
1229
+ }
1230
+ return out;
1231
+ }
1232
+ function outRange(r) {
1233
+ const out = clone3(_nullishCoalesce(r, () => ( {})));
1234
+ if (!out.sheetId) delete out.sheetId;
1235
+ return out;
1236
+ }
1237
+ var FakeSheets = (_class5 = class {
1238
+ __init24() {this.calls = []}
1239
+ /** Every request of each committed `batchUpdate`, in order. */
1240
+ __init25() {this.appliedRequests = []}
1241
+
1242
+
1243
+
1244
+ __init26() {this.failures = /* @__PURE__ */ new Map()}
1245
+ constructor(opts = {}) {;_class5.prototype.__init24.call(this);_class5.prototype.__init25.call(this);_class5.prototype.__init26.call(this);
1246
+ this.spreadsheetId = _nullishCoalesce(opts.spreadsheetId, () => ( "fake-spreadsheet"));
1247
+ this.title = _nullishCoalesce(opts.title, () => ( "Fake Spreadsheet"));
1248
+ const seeds = _nullishCoalesce(opts.tabs, () => ( [{ title: "Sheet1", sheetId: 0 }]));
1249
+ if (seeds.length === 0)
1250
+ throw new Error("FakeSheets needs at least one tab");
1251
+ const used = new Set(
1252
+ seeds.flatMap((t) => t.sheetId === void 0 ? [] : [t.sheetId])
1253
+ );
1254
+ if (used.size !== seeds.filter((t) => t.sheetId !== void 0).length) {
1255
+ throw new Error("FakeSheets: duplicate sheetId in tabs");
1256
+ }
1257
+ let next = 0;
1258
+ const tabs = seeds.map((seed) => {
1259
+ if (seeds.filter((t) => sameTitle(t.title, seed.title)).length > 1) {
1260
+ throw new Error(`FakeSheets: duplicate tab title ${seed.title}`);
1261
+ }
1262
+ let sheetId = seed.sheetId;
1263
+ if (sheetId === void 0) {
1264
+ while (used.has(next)) next++;
1265
+ used.add(sheetId = next);
1266
+ }
1267
+ const rows = _nullishCoalesce(seed.rows, () => ( []));
1268
+ return {
1269
+ sheetId,
1270
+ title: seed.title,
1271
+ hidden: false,
1272
+ frozenRows: 0,
1273
+ frozenColumns: 0,
1274
+ rowCount: Math.max(DEFAULT_ROWS, rows.length),
1275
+ columnCount: Math.max(DEFAULT_COLUMNS, ...rows.map((r) => r.length)),
1276
+ cells: rows.map((r) => r.map((v) => v === "" ? void 0 : { v }))
1277
+ };
1278
+ });
1279
+ this.state = {
1280
+ tabs,
1281
+ named: [],
1282
+ protected: [],
1283
+ nextSheetId: Math.max(...used) + 1,
1284
+ nextNamedId: 1,
1285
+ nextProtectedId: 1
1286
+ };
1287
+ }
1288
+ // ---- inspection helpers ----
1289
+ tab(title) {
1290
+ const index = this.state.tabs.findIndex((t2) => t2.title === title);
1291
+ const t = this.state.tabs[index];
1292
+ if (!t) return void 0;
1293
+ return {
1294
+ sheetId: t.sheetId,
1295
+ hidden: t.hidden,
1296
+ frozenRows: t.frozenRows,
1297
+ frozenColumns: t.frozenColumns,
1298
+ index
1299
+ };
1300
+ }
1301
+ /** The tab's values (formulas read as `""`), trailing empty cells and rows trimmed. */
1302
+ values(title) {
1303
+ const t = this.mustTab(title);
1304
+ return trimmed(
1305
+ t,
1306
+ [1, t.cells.length],
1307
+ [1, Number.MAX_SAFE_INTEGER],
1308
+ "UNFORMATTED_VALUE"
1309
+ );
1310
+ }
1311
+ /** The formula stored at `cell` (e.g. `"C2"`), or null if the cell holds none. */
1312
+ formulaAt(title, cell) {
1313
+ const t = this.mustTab(title);
1314
+ const b = _chunk4UEM6VO4cjs.a1.parse(cell);
1315
+ if (b.startRow === null || b.startColumn === null) {
1316
+ throw new Error(`FakeSheets: not a cell reference: ${cell}`);
1317
+ }
1318
+ return _nullishCoalesce(_optionalChain([t, 'access', _29 => _29.cells, 'access', _30 => _30[b.startRow - 1], 'optionalAccess', _31 => _31[b.startColumn - 1], 'optionalAccess', _32 => _32.f]), () => ( null));
1319
+ }
1320
+ failNext(op, error, opts = {}) {
1321
+ const q = _nullishCoalesce(this.failures.get(op), () => ( []));
1322
+ q.push({ error, afterApply: _nullishCoalesce(opts.afterApply, () => ( false)) });
1323
+ this.failures.set(op, q);
1324
+ }
1325
+ // ---- SheetsTransport ----
1326
+ async getSpreadsheet(p) {
1327
+ this.calls.push({ op: "getSpreadsheet", fields: p.fields });
1328
+ return this.run(
1329
+ "getSpreadsheet",
1330
+ p,
1331
+ (s) => project(this.full(s), parseMask(p.fields))
1332
+ );
1333
+ }
1334
+ async valuesGet(p) {
1335
+ this.calls.push({ op: "valuesGet", ranges: [p.range] });
1336
+ return this.run(
1337
+ "valuesGet",
1338
+ p,
1339
+ (s) => this.read(s, p.range, p.valueRenderOption)
1340
+ );
1341
+ }
1342
+ async valuesBatchGet(p) {
1343
+ this.calls.push({ op: "valuesBatchGet", ranges: [...p.ranges] });
1344
+ return this.run("valuesBatchGet", p, (s) => ({
1345
+ spreadsheetId: this.spreadsheetId,
1346
+ valueRanges: p.ranges.map((r) => this.read(s, r, p.valueRenderOption))
1347
+ }));
1348
+ }
1349
+ async valuesUpdate(p) {
1350
+ this.calls.push({
1351
+ op: "valuesUpdate",
1352
+ ranges: [p.range],
1353
+ valueInputOption: p.valueInputOption
1354
+ });
1355
+ return this.run("valuesUpdate", p, (s) => ({
1356
+ spreadsheetId: this.spreadsheetId,
1357
+ ...this.write(s, p.range, p.values, p.valueInputOption)
1358
+ }));
1359
+ }
1360
+ async valuesBatchUpdate(p) {
1361
+ this.calls.push({
1362
+ op: "valuesBatchUpdate",
1363
+ ranges: p.data.map((d) => d.range),
1364
+ valueInputOption: p.valueInputOption
1365
+ });
1366
+ return this.run("valuesBatchUpdate", p, (s) => {
1367
+ const responses = p.data.map(
1368
+ (d) => this.write(s, d.range, d.values, p.valueInputOption)
1369
+ );
1370
+ return {
1371
+ spreadsheetId: this.spreadsheetId,
1372
+ totalUpdatedCells: responses.reduce((n, r) => n + r.updatedCells, 0),
1373
+ responses
1374
+ };
1375
+ });
1376
+ }
1377
+ async valuesAppend(p) {
1378
+ this.calls.push({
1379
+ op: "valuesAppend",
1380
+ ranges: [p.range],
1381
+ valueInputOption: p.valueInputOption
1382
+ });
1383
+ return this.run("valuesAppend", p, (s) => {
1384
+ const { tab, bounds } = this.resolve(s, p.range);
1385
+ let last = tab.cells.length;
1386
+ while (last > 0 && !_optionalChain([tab, 'access', _33 => _33.cells, 'access', _34 => _34[last - 1], 'optionalAccess', _35 => _35.some, 'call', _36 => _36(Boolean)])) last--;
1387
+ const row = last + 1;
1388
+ const column = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _37 => _37.startColumn]), () => ( 1));
1389
+ if (p.insertDataOption === "INSERT_ROWS") tab.rowCount += p.values.length;
1390
+ const out = this.writeAt(tab, row, column, p.values, p.valueInputOption);
1391
+ return { spreadsheetId: this.spreadsheetId, updates: out };
1392
+ });
1393
+ }
1394
+ async valuesBatchClear(p) {
1395
+ this.calls.push({ op: "valuesBatchClear", ranges: [...p.ranges] });
1396
+ return this.run("valuesBatchClear", p, (s) => {
1397
+ for (const ref of p.ranges) {
1398
+ const { tab, bounds } = this.resolve(s, ref);
1399
+ const r0 = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _38 => _38.startRow]), () => ( 1));
1400
+ const r1 = Math.min(_nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _39 => _39.endRow]), () => ( Infinity)), tab.cells.length);
1401
+ for (let r = r0; r <= r1; r++) {
1402
+ const row = _nullishCoalesce(tab.cells[r - 1], () => ( []));
1403
+ const c0 = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _40 => _40.startColumn]), () => ( 1));
1404
+ const c1 = Math.min(_nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _41 => _41.endColumn]), () => ( Infinity)), row.length);
1405
+ for (let c = c0; c <= c1; c++) row[c - 1] = void 0;
1406
+ }
1407
+ }
1408
+ });
1409
+ }
1410
+ async batchUpdate(p) {
1411
+ this.calls.push({
1412
+ op: "batchUpdate",
1413
+ requests: Array.isArray(p.requests) ? p.requests.length : 0
1414
+ });
1415
+ return this.run("batchUpdate", p, (s) => {
1416
+ if (!Array.isArray(p.requests) || p.requests.length === 0) {
1417
+ throw badRequest(
1418
+ "Invalid requests: must specify at least one request."
1419
+ );
1420
+ }
1421
+ const replies = p.requests.map((req, i) => this.apply(s, req, i));
1422
+ this.appliedRequests.push(...clone3(p.requests));
1423
+ return { spreadsheetId: this.spreadsheetId, replies };
1424
+ });
1425
+ }
1426
+ // ---- internals ----
1427
+ /** Injected failure, 404 check, then `fn` on a draft that is committed on success. */
1428
+ run(op, target, fn) {
1429
+ const f = _optionalChain([this, 'access', _42 => _42.failures, 'access', _43 => _43.get, 'call', _44 => _44(op), 'optionalAccess', _45 => _45.shift, 'call', _46 => _46()]);
1430
+ if (f && !f.afterApply) throw f.error;
1431
+ if (target.spreadsheetId !== this.spreadsheetId) {
1432
+ throw sheetsHttpError(404, "notFound", "Requested entity was not found.");
1433
+ }
1434
+ const draft = clone3(this.state);
1435
+ const result = clone3(fn(draft));
1436
+ this.state = draft;
1437
+ if (f) throw f.error;
1438
+ return result;
1439
+ }
1440
+ mustTab(title) {
1441
+ const t = this.state.tabs.find((x) => x.title === title);
1442
+ if (!t)
1443
+ throw new Error(`FakeSheets: no tab titled ${JSON.stringify(title)}`);
1444
+ return t;
1445
+ }
1446
+ /**
1447
+ * Resolves an A1 ref to its tab and bounds (null bounds = whole tab), as Google
1448
+ * does: `'quoted'` or unquoted title (no `'` in it) before `!`; a bare quoted
1449
+ * title is the whole tab; a bare ref that parses as A1 addresses the first
1450
+ * visible tab; any other bare text is a whole-tab title.
1451
+ */
1452
+ resolve(s, ref) {
1453
+ if (typeof ref !== "string" || ref === "") throw parseError(String(ref));
1454
+ const byTitle = (title) => {
1455
+ if (title.includes("'")) throw parseError(ref);
1456
+ return s.tabs.find((t) => sameTitle(t.title, title));
1457
+ };
1458
+ const isRange = (text) => {
1459
+ try {
1460
+ _chunk4UEM6VO4cjs.a1.parse(text);
1461
+ return true;
1462
+ } catch (e3) {
1463
+ return false;
1464
+ }
1465
+ };
1466
+ let tab;
1467
+ let rangePart;
1468
+ if (ref.startsWith("'")) {
1469
+ let split;
1470
+ try {
1471
+ split = _chunk4UEM6VO4cjs.a1.split(ref);
1472
+ } catch (e4) {
1473
+ throw parseError(ref);
1474
+ }
1475
+ tab = s.tabs.find((t) => sameTitle(t.title, split.tab));
1476
+ rangePart = split.range;
1477
+ } else if (!ref.includes("!")) {
1478
+ if (isRange(ref)) [tab, rangePart] = [s.tabs.find((t) => !t.hidden), ref];
1479
+ else [tab, rangePart] = [byTitle(ref), null];
1480
+ } else {
1481
+ const bang = ref.indexOf("!");
1482
+ tab = byTitle(ref.slice(0, bang));
1483
+ rangePart = ref.slice(bang + 1);
1484
+ if (bang === 0 || rangePart === "") throw parseError(ref);
1485
+ }
1486
+ if (!tab) throw parseError(ref);
1487
+ if (rangePart === null) return { tab, bounds: null, closed: false };
1488
+ try {
1489
+ return {
1490
+ tab,
1491
+ bounds: _chunk4UEM6VO4cjs.a1.parse(rangePart),
1492
+ closed: rangePart.includes(":")
1493
+ };
1494
+ } catch (e5) {
1495
+ throw parseError(ref);
1496
+ }
1497
+ }
1498
+ read(s, ref, mode) {
1499
+ const { tab, bounds } = this.resolve(s, ref);
1500
+ const maxRow = Math.max(_nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _47 => _47.startRow]), () => ( 0)), _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _48 => _48.endRow]), () => ( 0)));
1501
+ const maxCol = Math.max(_nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _49 => _49.startColumn]), () => ( 0)), _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _50 => _50.endColumn]), () => ( 0)));
1502
+ if (maxRow > tab.rowCount || maxCol > tab.columnCount) {
1503
+ throw badRequest(
1504
+ `Range (${ref}) exceeds grid limits. Max rows: ${tab.rowCount}, max columns: ${tab.columnCount}`
1505
+ );
1506
+ }
1507
+ const r0 = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _51 => _51.startRow]), () => ( 1));
1508
+ const r1 = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _52 => _52.endRow]), () => ( tab.rowCount));
1509
+ const c0 = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _53 => _53.startColumn]), () => ( 1));
1510
+ const c1 = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _54 => _54.endColumn]), () => ( tab.columnCount));
1511
+ const values = trimmed(tab, [r0, r1], [c0, c1], mode);
1512
+ return {
1513
+ range: blockRef(tab, r0, c0, r1, c1),
1514
+ majorDimension: "ROWS",
1515
+ ...values.length > 0 ? { values } : {}
1516
+ };
1517
+ }
1518
+ write(s, ref, values, option) {
1519
+ const { tab, bounds, closed } = this.resolve(s, ref);
1520
+ const r0 = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _55 => _55.startRow]), () => ( 1));
1521
+ const c0 = _nullishCoalesce(_optionalChain([bounds, 'optionalAccess', _56 => _56.startColumn]), () => ( 1));
1522
+ if (closed && Array.isArray(values)) {
1523
+ const lastRow = r0 + values.length - 1;
1524
+ const width = Math.max(
1525
+ 0,
1526
+ ...values.map((r) => Array.isArray(r) ? r.length : 0)
1527
+ );
1528
+ if (_optionalChain([bounds, 'optionalAccess', _57 => _57.endRow]) != null && lastRow > bounds.endRow) {
1529
+ throw badRequest(
1530
+ `Requested writing within range [${ref}], but tried writing to row [${lastRow}]`
1531
+ );
1532
+ }
1533
+ if (_optionalChain([bounds, 'optionalAccess', _58 => _58.endColumn]) != null && c0 + width - 1 > bounds.endColumn) {
1534
+ throw badRequest(
1535
+ `Requested writing within range [${ref}], but tried writing to column [${_chunk4UEM6VO4cjs.a1.indexToColumn(c0 + width - 1)}]`
1536
+ );
1537
+ }
1538
+ }
1539
+ return this.writeAt(tab, r0, c0, values, option);
1540
+ }
1541
+ writeAt(tab, r0, c0, values, option) {
1542
+ if (!Array.isArray(values) || !values.every(Array.isArray)) {
1543
+ throw badRequest("Invalid values: expected an array of rows");
1544
+ }
1545
+ const width = Math.max(1, ...values.map((r) => r.length));
1546
+ const height = Math.max(1, values.length);
1547
+ let cells = 0;
1548
+ values.forEach(
1549
+ (row, i) => row.forEach((value, j) => {
1550
+ const cell = toCell(value, option);
1551
+ if (cell === SKIP) return;
1552
+ cells++;
1553
+ setCell(tab, r0 + i, c0 + j, cell === CLEAR ? void 0 : cell);
1554
+ })
1555
+ );
1556
+ tab.rowCount = Math.max(tab.rowCount, r0 + height - 1);
1557
+ tab.columnCount = Math.max(tab.columnCount, c0 + width - 1);
1558
+ return {
1559
+ updatedRange: blockRef(tab, r0, c0, r0 + height - 1, c0 + width - 1),
1560
+ updatedRows: values.length,
1561
+ updatedColumns: width,
1562
+ updatedCells: cells
1563
+ };
1564
+ }
1565
+ sheetProps(s, t) {
1566
+ return {
1567
+ sheetId: t.sheetId,
1568
+ title: t.title,
1569
+ index: s.tabs.indexOf(t),
1570
+ sheetType: "GRID",
1571
+ // Like Google, false / zero values are omitted.
1572
+ ...t.hidden ? { hidden: true } : {},
1573
+ gridProperties: {
1574
+ rowCount: t.rowCount,
1575
+ columnCount: t.columnCount,
1576
+ ...t.frozenRows ? { frozenRowCount: t.frozenRows } : {},
1577
+ ...t.frozenColumns ? { frozenColumnCount: t.frozenColumns } : {}
1578
+ }
1579
+ };
1580
+ }
1581
+ full(s) {
1582
+ return {
1583
+ spreadsheetId: this.spreadsheetId,
1584
+ properties: { title: this.title, locale: "en_US", timeZone: "Etc/GMT" },
1585
+ sheets: s.tabs.map((t) => {
1586
+ const prs = s.protected.filter((pr) => (_nullishCoalesce(_optionalChain([pr, 'access', _59 => _59.range, 'optionalAccess', _60 => _60.sheetId]), () => ( 0))) === t.sheetId).map((pr) => ({ ...clone3(pr), range: outRange(pr.range) }));
1587
+ const rowData = t.cells.map(
1588
+ (row) => row.length > 0 ? { values: Array.from(row, (c) => c ? cellData(c) : {}) } : {}
1589
+ );
1590
+ return {
1591
+ properties: this.sheetProps(s, t),
1592
+ ...prs.length > 0 ? { protectedRanges: prs } : {},
1593
+ // A broad mask (`*`, `sheets`) returns grid data, as on Google.
1594
+ data: [rowData.length > 0 ? { rowData } : {}]
1595
+ };
1596
+ }),
1597
+ ...s.named.length > 0 ? {
1598
+ namedRanges: s.named.map((n) => ({
1599
+ ...clone3(n),
1600
+ range: outRange(n.range)
1601
+ }))
1602
+ } : {},
1603
+ spreadsheetUrl: `https://docs.google.com/spreadsheets/d/${this.spreadsheetId}/edit`
1604
+ };
1605
+ }
1606
+ apply(s, req, i) {
1607
+ const keys = isObj(req) ? Object.keys(req) : [];
1608
+ if (keys.length !== 1) {
1609
+ throw badRequest(
1610
+ `Invalid requests[${i}]: exactly one kind of request must be set.`
1611
+ );
1612
+ }
1613
+ const key = keys[0];
1614
+ if (!REQUEST_KEYS.has(key)) {
1615
+ throw badRequest(
1616
+ `Invalid JSON payload received. Unknown name "${key}" at 'requests[${i}]'.`
1617
+ );
1618
+ }
1619
+ const body = req[key];
1620
+ const fail = (msg) => badRequest(`Invalid requests[${i}].${key}: ${msg}`);
1621
+ if (!isObj(body)) throw fail("request body must be an object.");
1622
+ const byId = (id) => {
1623
+ const t = s.tabs.find((x) => x.sheetId === (_nullishCoalesce(id, () => ( 0))));
1624
+ if (!t) throw fail(`No grid with id: ${String(id)}`);
1625
+ return t;
1626
+ };
1627
+ const titleFree = (title, except) => {
1628
+ if (typeof title !== "string" || title.trim() === "") {
1629
+ throw fail("Sheet title must not be empty.");
1630
+ }
1631
+ if (s.tabs.some((t) => t !== except && sameTitle(t.title, title))) {
1632
+ throw fail(
1633
+ `A sheet with the name "${title}" already exists. Please enter another name.`
1634
+ );
1635
+ }
1636
+ return title;
1637
+ };
1638
+ const idFree = (id) => {
1639
+ if (!Number.isInteger(id) || id < 0)
1640
+ throw fail(`Invalid sheet id: ${String(id)}`);
1641
+ if (s.tabs.some((t) => t.sheetId === id))
1642
+ throw fail(`A sheet with id ${String(id)} already exists.`);
1643
+ return id;
1644
+ };
1645
+ const newId = () => {
1646
+ while (s.tabs.some((t) => t.sheetId === s.nextSheetId)) s.nextSheetId++;
1647
+ return s.nextSheetId++;
1648
+ };
1649
+ const insertAt = (t, index) => {
1650
+ const at2 = typeof index === "number" ? Math.max(0, Math.min(index, s.tabs.length)) : s.tabs.length;
1651
+ s.tabs.splice(at2, 0, t);
1652
+ };
1653
+ switch (key) {
1654
+ case "addSheet": {
1655
+ const props = _nullishCoalesce(body.properties, () => ( {}));
1656
+ const grid = _nullishCoalesce(props.gridProperties, () => ( {}));
1657
+ let title = props.title;
1658
+ if (title == null) {
1659
+ let n = s.tabs.length + 1;
1660
+ while (s.tabs.some((t2) => sameTitle(t2.title, `Sheet${n}`))) n++;
1661
+ title = `Sheet${n}`;
1662
+ }
1663
+ const t = {
1664
+ sheetId: props.sheetId == null ? newId() : idFree(props.sheetId),
1665
+ title: titleFree(title),
1666
+ hidden: _nullishCoalesce(props.hidden, () => ( false)),
1667
+ frozenRows: _nullishCoalesce(grid.frozenRowCount, () => ( 0)),
1668
+ frozenColumns: _nullishCoalesce(grid.frozenColumnCount, () => ( 0)),
1669
+ rowCount: _nullishCoalesce(grid.rowCount, () => ( DEFAULT_ROWS)),
1670
+ columnCount: _nullishCoalesce(grid.columnCount, () => ( DEFAULT_COLUMNS)),
1671
+ cells: []
1672
+ };
1673
+ insertAt(t, props.index);
1674
+ return { addSheet: { properties: this.sheetProps(s, t) } };
1675
+ }
1676
+ case "deleteSheet": {
1677
+ const t = byId(body.sheetId);
1678
+ if (s.tabs.length === 1)
1679
+ throw fail("You can't remove all the sheets in a document.");
1680
+ s.tabs.splice(s.tabs.indexOf(t), 1);
1681
+ const onTab = (r) => (_nullishCoalesce(_optionalChain([r, 'optionalAccess', _61 => _61.sheetId]), () => ( 0))) === t.sheetId;
1682
+ s.named = s.named.filter((n) => !onTab(n.range));
1683
+ s.protected = s.protected.filter((pr) => !onTab(pr.range));
1684
+ return {};
1685
+ }
1686
+ case "updateSheetProperties": {
1687
+ const props = _nullishCoalesce(body.properties, () => ( {}));
1688
+ if (typeof body.fields !== "string" || body.fields.trim() === "") {
1689
+ throw fail("At least one field must be specified in 'fields'.");
1690
+ }
1691
+ const t = byId(props.sheetId);
1692
+ const mask = parseMask(body.fields);
1693
+ const all = mask.has("*");
1694
+ const grid = _nullishCoalesce(props.gridProperties, () => ( {}));
1695
+ const gridMask = all ? true : mask.get("gridProperties");
1696
+ const wantsGrid = (k) => gridMask === true || gridMask instanceof Map && gridMask.has(k);
1697
+ for (const [k] of mask) {
1698
+ if (![
1699
+ "*",
1700
+ "title",
1701
+ "index",
1702
+ "hidden",
1703
+ "gridProperties",
1704
+ "tabColor",
1705
+ "tabColorStyle",
1706
+ "rightToLeft"
1707
+ ].includes(k)) {
1708
+ throw fail(`Invalid field: ${k}`);
1709
+ }
1710
+ }
1711
+ if (gridMask instanceof Map) {
1712
+ for (const [k] of gridMask) {
1713
+ if (![
1714
+ "rowCount",
1715
+ "columnCount",
1716
+ "frozenRowCount",
1717
+ "frozenColumnCount",
1718
+ "hideGridlines",
1719
+ "rowGroupControlAfter",
1720
+ "columnGroupControlAfter"
1721
+ ].includes(k)) {
1722
+ throw fail(`Invalid field: gridProperties.${k}`);
1723
+ }
1724
+ }
1725
+ }
1726
+ if (all || mask.has("title")) t.title = titleFree(props.title, t);
1727
+ if (all || mask.has("hidden")) t.hidden = _nullishCoalesce(props.hidden, () => ( false));
1728
+ if (wantsGrid("frozenRowCount"))
1729
+ t.frozenRows = _nullishCoalesce(grid.frozenRowCount, () => ( 0));
1730
+ if (wantsGrid("frozenColumnCount"))
1731
+ t.frozenColumns = _nullishCoalesce(grid.frozenColumnCount, () => ( 0));
1732
+ if (wantsGrid("rowCount") && grid.rowCount != null)
1733
+ t.rowCount = grid.rowCount;
1734
+ if (wantsGrid("columnCount") && grid.columnCount != null)
1735
+ t.columnCount = grid.columnCount;
1736
+ if (all || mask.has("index")) {
1737
+ const cur = s.tabs.indexOf(t);
1738
+ const target = _nullishCoalesce(props.index, () => ( s.tabs.length));
1739
+ s.tabs.splice(cur, 1);
1740
+ insertAt(t, target > cur ? target - 1 : target);
1741
+ }
1742
+ if (s.tabs.every((x) => x.hidden))
1743
+ throw fail("You can't hide all the sheets in a document.");
1744
+ return {};
1745
+ }
1746
+ case "duplicateSheet": {
1747
+ const src = byId(body.sourceSheetId);
1748
+ let title = body.newSheetName;
1749
+ if (title == null) {
1750
+ title = `Copy of ${src.title}`;
1751
+ for (let n = 2; s.tabs.some((t2) => sameTitle(t2.title, title)); n++) {
1752
+ title = `Copy of ${src.title} ${n}`;
1753
+ }
1754
+ }
1755
+ const t = {
1756
+ ...clone3(src),
1757
+ sheetId: body.newSheetId == null ? newId() : idFree(body.newSheetId),
1758
+ title: titleFree(title)
1759
+ };
1760
+ insertAt(t, _nullishCoalesce(body.insertSheetIndex, () => ( s.tabs.indexOf(src) + 1)));
1761
+ return { duplicateSheet: { properties: this.sheetProps(s, t) } };
1762
+ }
1763
+ case "insertDimension":
1764
+ case "deleteDimension": {
1765
+ const r = _nullishCoalesce(body.range, () => ( {}));
1766
+ const t = byId(r.sheetId);
1767
+ if (r.dimension !== "ROWS" && r.dimension !== "COLUMNS") {
1768
+ throw fail("range.dimension must be ROWS or COLUMNS.");
1769
+ }
1770
+ const rows = r.dimension === "ROWS";
1771
+ const size = rows ? t.rowCount : t.columnCount;
1772
+ const start = _nullishCoalesce(r.startIndex, () => ( 0));
1773
+ const end = _nullishCoalesce(r.endIndex, () => ( size));
1774
+ const n = end - start;
1775
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || n <= 0) {
1776
+ throw fail(`Invalid range: [${start}, ${end}).`);
1777
+ }
1778
+ if (key === "insertDimension") {
1779
+ if (start > size)
1780
+ throw fail(
1781
+ `Cannot insert at index ${start}; the sheet has ${size}.`
1782
+ );
1783
+ if (rows) {
1784
+ t.cells.splice(start, 0, ...Array.from({ length: n }, () => []));
1785
+ t.rowCount += n;
1786
+ } else {
1787
+ for (const row of t.cells) {
1788
+ if (row.length > start)
1789
+ row.splice(start, 0, ...new Array(n));
1790
+ }
1791
+ t.columnCount += n;
1792
+ }
1793
+ return {};
1794
+ }
1795
+ const frozen = rows ? t.frozenRows : t.frozenColumns;
1796
+ const what = rows ? "rows" : "columns";
1797
+ if (end > size)
1798
+ throw fail(
1799
+ `Cannot delete ${what} that do not exist (sheet has ${size}).`
1800
+ );
1801
+ if (n >= size)
1802
+ throw fail(`You can't delete all the ${what} on the sheet.`);
1803
+ if (size - n <= frozen)
1804
+ throw fail(
1805
+ `Sorry, it is not possible to delete all non-frozen ${what}.`
1806
+ );
1807
+ const lostFrozen = Math.max(0, Math.min(end, frozen) - start);
1808
+ if (rows) {
1809
+ t.cells.splice(start, n);
1810
+ t.rowCount -= n;
1811
+ t.frozenRows -= lostFrozen;
1812
+ } else {
1813
+ for (const row of t.cells) row.splice(start, n);
1814
+ t.columnCount -= n;
1815
+ t.frozenColumns -= lostFrozen;
1816
+ }
1817
+ return {};
1818
+ }
1819
+ case "addNamedRange": {
1820
+ const nr = _nullishCoalesce(body.namedRange, () => ( {}));
1821
+ const name = nr.name;
1822
+ if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,249}$/.test(name) || BOOLEAN.test(name) || /^[A-Za-z]{1,3}\d+$/.test(name) || /^R\d*C\d*$/i.test(name)) {
1823
+ throw fail(`Invalid name: ${JSON.stringify(name)}.`);
1824
+ }
1825
+ if (s.named.some((n) => sameTitle(n.name, name))) {
1826
+ throw fail(`A named range with the name "${name}" already exists.`);
1827
+ }
1828
+ byId(_optionalChain([nr, 'access', _62 => _62.range, 'optionalAccess', _63 => _63.sheetId]));
1829
+ const namedRangeId = _nullishCoalesce(nr.namedRangeId, () => ( `fake-named-${s.nextNamedId++}`));
1830
+ if (s.named.some((n) => n.namedRangeId === namedRangeId)) {
1831
+ throw fail(`A named range with id ${namedRangeId} already exists.`);
1832
+ }
1833
+ const stored = { namedRangeId, name, range: clone3(_nullishCoalesce(nr.range, () => ( {}))) };
1834
+ s.named.push(stored);
1835
+ return {
1836
+ addNamedRange: {
1837
+ namedRange: { ...clone3(stored), range: outRange(stored.range) }
1838
+ }
1839
+ };
1840
+ }
1841
+ case "deleteNamedRange": {
1842
+ const at2 = s.named.findIndex(
1843
+ (n) => n.namedRangeId === body.namedRangeId
1844
+ );
1845
+ if (at2 < 0)
1846
+ throw fail(`No named range with id: ${String(body.namedRangeId)}`);
1847
+ s.named.splice(at2, 1);
1848
+ return {};
1849
+ }
1850
+ case "addProtectedRange": {
1851
+ const pr = _nullishCoalesce(body.protectedRange, () => ( {}));
1852
+ if (!isObj(pr.range)) throw fail("protectedRange.range is required.");
1853
+ byId(pr.range.sheetId);
1854
+ const stored = { ...clone3(pr), protectedRangeId: s.nextProtectedId++ };
1855
+ s.protected.push(stored);
1856
+ return {
1857
+ addProtectedRange: {
1858
+ protectedRange: { ...clone3(stored), range: outRange(stored.range) }
1859
+ }
1860
+ };
1861
+ }
1862
+ case "deleteProtectedRange": {
1863
+ const at2 = s.protected.findIndex(
1864
+ (pr) => pr.protectedRangeId === body.protectedRangeId
1865
+ );
1866
+ if (at2 < 0)
1867
+ throw fail(
1868
+ `No protected range with id: ${String(body.protectedRangeId)}`
1869
+ );
1870
+ s.protected.splice(at2, 1);
1871
+ return {};
1872
+ }
1873
+ default: {
1874
+ if (NEEDS_FIELDS.has(key) && (typeof body.fields !== "string" || body.fields.trim() === "")) {
1875
+ throw fail("At least one field must be specified in 'fields'.");
1876
+ }
1877
+ for (const paths of _nullishCoalesce(NEEDS_RANGE[key], () => ( []))) {
1878
+ const found = paths.map((path) => at(body, path)).find((v) => v !== void 0);
1879
+ if (found === void 0)
1880
+ throw fail(`${paths.join(" or ")} is required.`);
1881
+ if (isObj(found)) byId(found.sheetId);
1882
+ }
1883
+ if (ON_SHEET.has(key)) byId(body.sheetId);
1884
+ this.checkSheetIds(body, (id) => byId(id));
1885
+ return {};
1886
+ }
1887
+ }
1888
+ }
1889
+ checkSheetIds(v, check) {
1890
+ if (Array.isArray(v)) v.forEach((x) => this.checkSheetIds(x, check));
1891
+ else if (isObj(v)) {
1892
+ for (const [k, x] of Object.entries(v)) {
1893
+ if (k === "sheetId" && typeof x === "number") check(x);
1894
+ else this.checkSheetIds(x, check);
1895
+ }
1896
+ }
1897
+ }
1898
+ }, _class5);
1899
+
1900
+
1901
+
1902
+
823
1903
 
824
1904
 
825
1905
 
826
1906
 
827
1907
 
828
- exports.CaptureTransport = CaptureTransport; exports.FakeGoogleOAuth = FakeGoogleOAuth; exports.InMemoryStore = InMemoryStore; exports.LocalKeyProvider = LocalKeyProvider; exports.runStoreContractTests = runStoreContractTests;
1908
+ exports.CaptureTransport = CaptureTransport; exports.FakeCalendar = FakeCalendar; exports.FakeGoogleOAuth = FakeGoogleOAuth; exports.FakeSheets = FakeSheets; exports.InMemoryStore = InMemoryStore; exports.LocalKeyProvider = LocalKeyProvider; exports.runStoreContractTests = runStoreContractTests; exports.sheetsHttpError = sheetsHttpError;
829
1909
  //# sourceMappingURL=testing.cjs.map