agenttwin 0.3.43 → 0.3.45

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 (94) hide show
  1. package/dist/api.js +26461 -4499
  2. package/dist/dashboard/assets/next/static/chunks/1937-6d51d4e124712da3.js +1 -0
  3. package/dist/dashboard/assets/next/static/chunks/{7772-f2d773cd3e94eea6.js → 3481-38a2a90084247ab1.js} +6 -6
  4. package/dist/dashboard/assets/next/static/chunks/6259-3689e5642b66d78c.js +1 -0
  5. package/dist/dashboard/assets/next/static/chunks/8176-80d26c1ba3e96c09.js +1 -0
  6. package/dist/dashboard/assets/next/static/chunks/app/_not-found/{page-cbf0a4f7672335b8.js → page-90e7c4625d67caa3.js} +1 -1
  7. package/dist/dashboard/assets/next/static/chunks/app/about/page-7b6ab8f6081f5e77.js +1 -0
  8. package/dist/dashboard/assets/next/static/chunks/app/account/password/page-037fec5f56012be1.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/api-policy/{page-35fd8f4fe3b2af15.js → page-540d65d1057a7527.js} +1 -1
  10. package/dist/dashboard/assets/next/static/chunks/app/auth/{page-35fd8f4fe3b2af15.js → page-540d65d1057a7527.js} +1 -1
  11. package/dist/dashboard/assets/next/static/chunks/app/blog/{layout-89f2942330b48007.js → layout-1f35c9c8280d8e88.js} +1 -1
  12. package/dist/dashboard/assets/next/static/chunks/app/compare/{page-35fd8f4fe3b2af15.js → page-540d65d1057a7527.js} +1 -1
  13. package/dist/dashboard/assets/next/static/chunks/app/contact/{page-35fd8f4fe3b2af15.js → page-540d65d1057a7527.js} +1 -1
  14. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-0a7a4610c777d4ca.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-7ee71756cadd81da.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/app/demo/{page-9e977d1d883f7386.js → page-fa467521a350a22e.js} +1 -1
  17. package/dist/dashboard/assets/next/static/chunks/app/developers/page-540d65d1057a7527.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/{page-aea3b669bcb45491.js → page-2f02d1a4e3c44daa.js} +1 -1
  19. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-540d65d1057a7527.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/enterprise/{page-ce47c76b4160b3c9.js → page-5d3aa113786c4257.js} +1 -1
  21. package/dist/dashboard/assets/next/static/chunks/app/guides/page-540d65d1057a7527.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/{layout-bc1ef1623bd1dca6.js → layout-f1fad0b3adfa8650.js} +1 -1
  23. package/dist/dashboard/assets/next/static/chunks/app/login/page-0fcaa825ae57072e.js +1 -0
  24. package/dist/dashboard/assets/next/static/chunks/app/not-found-540d65d1057a7527.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/onboarding/{page-9c1bd81087260f4f.js → page-0ef60a890802e3ea.js} +1 -1
  26. package/dist/dashboard/assets/next/static/chunks/app/page-02d88045d016e184.js +1 -0
  27. package/dist/dashboard/assets/next/static/chunks/app/pricing/{page-2e2f53160e686d9e.js → page-b20818439dc8daa3.js} +1 -1
  28. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-540d65d1057a7527.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-540d65d1057a7527.js +1 -0
  30. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-540d65d1057a7527.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/security/page-540d65d1057a7527.js +1 -0
  32. package/dist/dashboard/assets/next/static/chunks/app/signup/page-0fcaa825ae57072e.js +1 -0
  33. package/dist/dashboard/assets/next/static/chunks/app/status/{page-d075703822281526.js → page-477b90a47b806b39.js} +1 -1
  34. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-540d65d1057a7527.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/app/terms/page-540d65d1057a7527.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-f3b848d905696aa6.js +1 -0
  37. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-5114d5bc25cc925a.js +1 -0
  38. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-c5a3a914ad02b396.js +1 -0
  39. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-391350c8e39d35fe.js +1 -0
  40. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-cb95f6e08d868cb9.js +1 -0
  41. package/dist/dashboard/assets/next/static/chunks/app/v2/page-ba5549311d95d01d.js +1 -0
  42. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-391350c8e39d35fe.js +1 -0
  43. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-540d65d1057a7527.js +1 -0
  44. package/dist/dashboard/assets/next/static/chunks/{main-app-85f4e8de9868bedc.js → main-app-09f87cf7a6813e7b.js} +1 -1
  45. package/dist/dashboard/assets/next/static/chunks/{webpack-382af3529e0fbd25.js → webpack-956fc59a9b8e1c9d.js} +1 -1
  46. package/dist/dashboard/assets/next/static/css/481ca6c2928cd200.css +1 -0
  47. package/dist/dashboard/assets/next/static/css/9b2210225877b730.css +1 -0
  48. package/dist/dashboard/assets/next/static/css/{f55186d294d5c4d4.css → d9a8b84d1f38505a.css} +2 -2
  49. package/dist/dashboard/assets/next/static/css/{11f70fd04660da57.css → dbba4df791f6fafa.css} +1 -1
  50. package/dist/dashboard/assets/next/static/css/{41d14b615c51789f.css → f219b6480a7505ef.css} +1 -1
  51. package/dist/dashboard/index.html +2 -2
  52. package/dist/discover-worker.js +315 -36
  53. package/dist/engine.js +27112 -5122
  54. package/dist/gateway.js +26474 -4512
  55. package/dist/scan-worker.js +20755 -667
  56. package/dist/worker.js +1174 -445
  57. package/dist/world-host.js +1239 -467
  58. package/package.json +1 -1
  59. package/dist/dashboard/assets/next/static/chunks/1937-6c86fddc443de922.js +0 -1
  60. package/dist/dashboard/assets/next/static/chunks/2960-520ffde27b062af4.js +0 -1
  61. package/dist/dashboard/assets/next/static/chunks/5258-3d0060b41be9ad97.js +0 -1
  62. package/dist/dashboard/assets/next/static/chunks/app/about/page-6e8e140ea96e4e5e.js +0 -1
  63. package/dist/dashboard/assets/next/static/chunks/app/account/password/page-124ac1de3af2d687.js +0 -1
  64. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-0262e35e50882ab7.js +0 -1
  65. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-943e07dc51384546.js +0 -1
  66. package/dist/dashboard/assets/next/static/chunks/app/developers/page-35fd8f4fe3b2af15.js +0 -1
  67. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-35fd8f4fe3b2af15.js +0 -1
  68. package/dist/dashboard/assets/next/static/chunks/app/guides/page-35fd8f4fe3b2af15.js +0 -1
  69. package/dist/dashboard/assets/next/static/chunks/app/login/page-9a6e88fc56812fbb.js +0 -1
  70. package/dist/dashboard/assets/next/static/chunks/app/not-found-35fd8f4fe3b2af15.js +0 -1
  71. package/dist/dashboard/assets/next/static/chunks/app/page-7849ed5b53ffb2d1.js +0 -1
  72. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-35fd8f4fe3b2af15.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-35fd8f4fe3b2af15.js +0 -1
  74. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-35fd8f4fe3b2af15.js +0 -1
  75. package/dist/dashboard/assets/next/static/chunks/app/security/page-35fd8f4fe3b2af15.js +0 -1
  76. package/dist/dashboard/assets/next/static/chunks/app/signup/page-9a6e88fc56812fbb.js +0 -1
  77. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-35fd8f4fe3b2af15.js +0 -1
  78. package/dist/dashboard/assets/next/static/chunks/app/terms/page-35fd8f4fe3b2af15.js +0 -1
  79. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-22d3ae1def1dd220.js +0 -1
  80. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-1b768bed2b8a2747.js +0 -1
  81. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-38b897124c7f6223.js +0 -1
  82. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-91f11cbfe46c4c25.js +0 -1
  83. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-64dd3f1b59afe38a.js +0 -1
  84. package/dist/dashboard/assets/next/static/chunks/app/v2/page-9191727c63b6ce2e.js +0 -1
  85. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-91f11cbfe46c4c25.js +0 -1
  86. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-35fd8f4fe3b2af15.js +0 -1
  87. package/dist/dashboard/assets/next/static/css/14ef6d1b7f922ef2.css +0 -1
  88. package/dist/dashboard/assets/next/static/css/39133c9a03c8edb8.css +0 -1
  89. package/dist/dashboard/assets/next/static/css/8f1b98de253e73ed.css +0 -1
  90. package/dist/dashboard/assets/next/static/css/c3d3b671693fb96d.css +0 -1
  91. package/dist/dashboard/assets/next/static/css/dd3fb06005e18149.css +0 -1
  92. package/dist/dashboard/assets/next/static/css/f14e187b236cb6fb.css +0 -1
  93. /package/dist/dashboard/assets/next/static/{sxtodXehxQTT0-7MaA4p7 → iCEc5bCzyYUPa74FKyLIp}/_buildManifest.js +0 -0
  94. /package/dist/dashboard/assets/next/static/{sxtodXehxQTT0-7MaA4p7 → iCEc5bCzyYUPa74FKyLIp}/_ssgManifest.js +0 -0
package/dist/worker.js CHANGED
@@ -12,9 +12,9 @@ async function processes() {
12
12
  const script = "$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -gt 1 -and $_.CreationDate } | ForEach-Object { @{pid=[int]$_.ProcessId;parent=[int]$_.ParentProcessId;born=$_.CreationDate.ToUniversalTime().ToString('o');state='running'} }) | ConvertTo-Json -Compress";
13
13
  const { stdout: stdout2 } = await exec(shell, ["-NoProfile", "-NonInteractive", "-Command", script], { timeout: 1e3, windowsHide: true, maxBuffer: 4 * 1024 * 1024 });
14
14
  const data = JSON.parse(stdout2.trim() || "[]");
15
- const rows2 = Array.isArray(data) ? data : [data];
16
- if (!rows2.every((r) => Number.isSafeInteger(r.pid) && Number.isSafeInteger(r.parent) && typeof r.born === "string")) throw Error("Invalid process evidence");
17
- return rows2;
15
+ const rows6 = Array.isArray(data) ? data : [data];
16
+ if (!rows6.every((r) => Number.isSafeInteger(r.pid) && Number.isSafeInteger(r.parent) && typeof r.born === "string")) throw Error("Invalid process evidence");
17
+ return rows6;
18
18
  }
19
19
  const { stdout } = await exec("ps", ["-axo", "pid=,ppid=,stat=,lstart="], { timeout: 1e3, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } });
20
20
  return stdout.trim().split("\n").filter(Boolean).map((line) => {
@@ -38,21 +38,21 @@ function manageApplication(child) {
38
38
  child.once("error", () => resolve3());
39
39
  });
40
40
  async function capture() {
41
- const rows2 = await processes();
42
- for (const [pid, born] of known2) if (!rows2.some((r) => r.pid === pid && r.born === born)) known2.delete(pid);
43
- const root = rows2.find((r) => r.pid === child.pid);
41
+ const rows6 = await processes();
42
+ for (const [pid, born] of known2) if (!rows6.some((r) => r.pid === pid && r.born === born)) known2.delete(pid);
43
+ const root = rows6.find((r) => r.pid === child.pid);
44
44
  if (root && child.exitCode === null && child.signalCode === null) known2.set(root.pid, root.born);
45
45
  let changed = true;
46
46
  while (changed) {
47
47
  changed = false;
48
- for (const row of rows2) {
48
+ for (const row of rows6) {
49
49
  if (row.pid > 1 && known2.has(row.parent) && !known2.has(row.pid)) {
50
50
  known2.set(row.pid, row.born);
51
51
  changed = true;
52
52
  }
53
53
  }
54
54
  }
55
- return rows2.filter((r) => known2.get(r.pid) === r.born && !r.state.startsWith("Z"));
55
+ return rows6.filter((r) => known2.get(r.pid) === r.born && !r.state.startsWith("Z"));
56
56
  }
57
57
  let scanning = false;
58
58
  const tick = () => {
@@ -162,18 +162,18 @@ function windowsBrowserProcess(executable, commands = run) {
162
162
  async function snapshot() {
163
163
  const { stdout } = await commands(powershell, ["-NoProfile", "-NonInteractive", "-Command", script]);
164
164
  const parsed = JSON.parse(stdout.trim() || "[]");
165
- const rows2 = Array.isArray(parsed) ? parsed : [parsed];
166
- if (!rows2.every((r) => r && Number.isSafeInteger(r.pid) && r.pid >= 0 && Number.isSafeInteger(r.parent) && typeof r.created === "string" && r.created.length > 0 && typeof r.command === "string")) throw Error("Invalid Windows process evidence");
167
- return rows2;
165
+ const rows6 = Array.isArray(parsed) ? parsed : [parsed];
166
+ if (!rows6.every((r) => r && Number.isSafeInteger(r.pid) && r.pid >= 0 && Number.isSafeInteger(r.parent) && typeof r.created === "string" && r.created.length > 0 && typeof r.command === "string")) throw Error("Invalid Windows process evidence");
167
+ return rows6;
168
168
  }
169
169
  async function owned() {
170
- const rows2 = await snapshot();
171
- for (const [pid, created2] of known2) if (!rows2.some((r) => r.pid === pid && r.created === created2)) known2.delete(pid);
172
- for (const row of rows2) if (row.parent === process.pid && row.command.split(/[\s"]+/).includes(marker)) known2.set(row.pid, row.created);
170
+ const rows6 = await snapshot();
171
+ for (const [pid, created2] of known2) if (!rows6.some((r) => r.pid === pid && r.created === created2)) known2.delete(pid);
172
+ for (const row of rows6) if (row.parent === process.pid && row.command.split(/[\s"]+/).includes(marker)) known2.set(row.pid, row.created);
173
173
  let changed = true;
174
174
  while (changed) {
175
175
  changed = false;
176
- for (const row of rows2) {
176
+ for (const row of rows6) {
177
177
  const parent = known2.get(row.parent);
178
178
  if (row.pid > 1 && parent && row.created >= parent && !known2.has(row.pid)) {
179
179
  known2.set(row.pid, row.created);
@@ -181,7 +181,7 @@ function windowsBrowserProcess(executable, commands = run) {
181
181
  }
182
182
  }
183
183
  }
184
- return rows2.filter((r) => known2.get(r.pid) === r.created);
184
+ return rows6.filter((r) => known2.get(r.pid) === r.created);
185
185
  }
186
186
  return {
187
187
  launcher: executable,
@@ -237,7 +237,7 @@ exec ${quote(executable)} "$@"
237
237
  throw e;
238
238
  }
239
239
  if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error("Invalid browser process identity");
240
- const rows2 = await processes2(), leader = rows2.find((p) => p.pid === pid);
240
+ const rows6 = await processes2(), leader = rows6.find((p) => p.pid === pid);
241
241
  if (leader && leader.pgid !== pid) throw new Error("Browser launcher does not own its process group");
242
242
  group = pid;
243
243
  return group;
@@ -306,7 +306,7 @@ import { AsyncLocalStorage } from "async_hooks";
306
306
 
307
307
  // src/runtime/application-clock.ts
308
308
  var MAX_CLOCK_SCALE = 1e4;
309
- var canonicalNow = (now) => typeof now === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(now) && Number.isFinite(Date.parse(now)) && new Date(now).toISOString() === now;
309
+ var canonicalNow = (now5) => typeof now5 === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(now5) && Number.isFinite(Date.parse(now5)) && new Date(now5).toISOString() === now5;
310
310
  function validApplicationClock(value) {
311
311
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
312
312
  const v = value;
@@ -516,8 +516,8 @@ import { isAbsolute } from "path";
516
516
  // src/runtime/postgres-clock.ts
517
517
  function validPostgresClock(value) {
518
518
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 1) return false;
519
- const now = value.now;
520
- return typeof now === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(now) && Number.isFinite(Date.parse(now)) && new Date(now).toISOString() === now;
519
+ const now5 = value.now;
520
+ return typeof now5 === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(now5) && Number.isFinite(Date.parse(now5)) && new Date(now5).toISOString() === now5;
521
521
  }
522
522
 
523
523
  // src/runtime/engines/types.ts
@@ -713,19 +713,19 @@ function overlay(target, input, schema, merge) {
713
713
  } else target[key2] = isObj(v) || Array.isArray(v) ? structuredClone(v) : coerce(v, child);
714
714
  }
715
715
  }
716
- function newId(resource, rows2, stream) {
717
- const s = resource.idSchema, taken = new Set(rows2.map((r) => String(r[resource.idField])));
716
+ function newId(resource2, rows6, stream) {
717
+ const s = resource2.idSchema, taken = new Set(rows6.map((r) => String(r[resource2.idField])));
718
718
  for (let i = 0; i < 50; i++) {
719
719
  let id;
720
- if (s?.type === "integer" || s?.type === "number") id = rows2.reduce((m, r) => Math.max(m, Number(r[resource.idField]) || 0), 1e3) + 1 + i;
720
+ if (s?.type === "integer" || s?.type === "number") id = rows6.reduce((m, r) => Math.max(m, Number(r[resource2.idField]) || 0), 1e3) + 1 + i;
721
721
  else if (s?.pattern) id = fromPattern(s.pattern, stream);
722
722
  if (id === void 0 && typeof s?.example === "string" && /^[A-Za-z]{1,8}_/.test(s.example)) id = s.example.split("_")[0] + "_" + stream.nextHex(12);
723
723
  if (id === void 0 && s?.format === "uuid") id = fakeValue(s, "id", stream);
724
724
  if (id === void 0 && typeof s?.example === "string" && /^\d+$/.test(s.example)) id = String(1e7 + stream.nextInt(89999999));
725
- id ??= `${singular(resource.name).replace(/[^a-z0-9]/gi, "").slice(0, 4).toLowerCase() || "obj"}_${stream.nextHex(10)}`;
725
+ id ??= `${singular(resource2.name).replace(/[^a-z0-9]/gi, "").slice(0, 4).toLowerCase() || "obj"}_${stream.nextHex(10)}`;
726
726
  if (!taken.has(String(id))) return id;
727
727
  }
728
- return `${resource.name}_${stream.nextHex(16)}`;
728
+ return `${resource2.name}_${stream.nextHex(16)}`;
729
729
  }
730
730
  var cache = /* @__PURE__ */ new WeakMap();
731
731
  function routes(twin) {
@@ -795,29 +795,29 @@ function errorBody(twin, op2, status, code, message, seed) {
795
795
  var PAGE_SIZE = /^(limit|perpage|pagesize|maxresults|maxitems|top|size|first|count|maxkeys)$/;
796
796
  var CURSOR = /^(after|startingafter|cursor|pagetoken|nextpagetoken|offset|start|skip|page|marker|continuationtoken|nexttoken|startafter|startindex)$/;
797
797
  var resourceOf = (twin, op2) => twin.resources.find((r) => r.collection === op2.resource);
798
- var findRow = (rows2, resource, id) => rows2.findIndex((r) => String(r[resource.idField]) === id);
798
+ var findRow = (rows6, resource2, id) => rows6.findIndex((r) => String(r[resource2.idField]) === id);
799
799
  var parentKey = (name) => HIDDEN + name;
800
- function inScope(row, resource, params, op2) {
800
+ function inScope(row, resource2, params, op2) {
801
801
  for (const p of op2.parentParams ?? []) {
802
- const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
802
+ const field = Object.keys(resource2.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
803
803
  const value = row[parentKey(p)] ?? (field ? row[field] : void 0);
804
804
  if (value !== void 0 && String(value) !== params[p]) return false;
805
805
  }
806
806
  return true;
807
807
  }
808
- function withParents(row, resource, op2, params) {
808
+ function withParents(row, resource2, op2, params) {
809
809
  const out = visible(row);
810
810
  for (const p of op2.parentParams ?? []) {
811
- const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
811
+ const field = Object.keys(resource2.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
812
812
  if (field && (out[field] === void 0 || out[field] === null)) out[field] = params[p];
813
813
  }
814
814
  return out;
815
815
  }
816
- function shape(op2, resource, record3, stream, sequence, params = {}) {
816
+ function shape(op2, resource2, record3, stream, sequence, params = {}) {
817
817
  const r = op2.response;
818
- const out = withParents(record3, resource, op2, params);
819
- if (!r || r.type !== "object" || !r.properties || Object.hasOwn(r.properties, resource.idField) || r["x-ref"] && r["x-ref"] === resource.schema?.["x-ref"]) return out;
820
- const holder = Object.entries(r.properties).find(([, s]) => s.type === "object" && (s["x-ref"] && s["x-ref"] === resource.schema?.["x-ref"] || s.properties && Object.hasOwn(s.properties, resource.idField)));
818
+ const out = withParents(record3, resource2, op2, params);
819
+ if (!r || r.type !== "object" || !r.properties || Object.hasOwn(r.properties, resource2.idField) || r["x-ref"] && r["x-ref"] === resource2.schema?.["x-ref"]) return out;
820
+ const holder = Object.entries(r.properties).find(([, s]) => s.type === "object" && (s["x-ref"] && s["x-ref"] === resource2.schema?.["x-ref"] || s.properties && Object.hasOwn(s.properties, resource2.idField)));
821
821
  if (!holder) return out;
822
822
  const env = materialize(r, "create", stream, sequence);
823
823
  for (const [k, s] of Object.entries(r.properties)) if (normName(k) === "success" && s.type === "boolean") env[k] = true;
@@ -853,8 +853,8 @@ function listEnvelope(op2, page, info, stream, sequence) {
853
853
  function handleRest(twin, req, data, ctx) {
854
854
  const match = matchOperation(twin, req.method, req.path);
855
855
  if (!match || !match.op.supported) return void 0;
856
- const { op: op2, params } = match, resource = resourceOf(twin, op2), collection = resource.collection;
857
- const rows2 = data[collection] ??= [];
856
+ const { op: op2, params } = match, resource2 = resourceOf(twin, op2), collection = resource2.collection;
857
+ const rows6 = data[collection] ??= [];
858
858
  const stream = streamFor(ctx.seed, `${twin.id}:${collection}:${ctx.sequence}`);
859
859
  const fail = (status, code, message) => {
860
860
  const e = errorBody(twin, op2, status, code, message, ctx.seed);
@@ -877,7 +877,7 @@ function handleRest(twin, req, data, ctx) {
877
877
  }
878
878
  }
879
879
  const id = op2.idParam ? params[op2.idParam] : void 0;
880
- const scoped = rows2.filter((r) => inScope(r, resource, params, op2));
880
+ const scoped = rows6.filter((r) => inScope(r, resource2, params, op2));
881
881
  if (op2.kind === "list") {
882
882
  const filters = [];
883
883
  let size = 20, cursor, cursorName = "";
@@ -904,71 +904,71 @@ function handleRest(twin, req, data, ctx) {
904
904
  }));
905
905
  let start = 0;
906
906
  if (cursor !== void 0) {
907
- const i = matches2.findIndex((r) => String(r[resource.idField]) === cursor);
907
+ const i = matches2.findIndex((r) => String(r[resource2.idField]) === cursor);
908
908
  start = i >= 0 ? i + 1 : cursorName === "page" ? Math.max(0, (Number(cursor) - 1) * size) : Number.isFinite(Number(cursor)) ? Number(cursor) : 0;
909
909
  }
910
- const page = matches2.slice(start, start + size).map((r) => withParents(r, resource, op2, params));
910
+ const page = matches2.slice(start, start + size).map((r) => withParents(r, resource2, op2, params));
911
911
  const more = start + size < matches2.length;
912
- const next2 = more ? cursorName === "startingafter" ? String(page[page.length - 1][resource.idField]) : String(start + size) : void 0;
912
+ const next2 = more ? cursorName === "startingafter" ? String(page[page.length - 1][resource2.idField]) : String(start + size) : void 0;
913
913
  const nextUrl = next2 ? `${req.path}?${new URLSearchParams({ ...req.query, [op2.params.find((p) => normName(p.name) === cursorName)?.name ?? "after"]: next2 })}` : void 0;
914
914
  return { status: op2.status, body: listEnvelope(op2, page, { total: matches2.length, ...next2 ? { next: next2 } : {}, ...nextUrl ? { nextUrl } : {} }, stream, ctx.sequence), collection, operation: "read" };
915
915
  }
916
916
  if (op2.kind === "singleton") {
917
917
  if (req.method === "GET") {
918
- const row3 = scoped[0] ?? materialize(resource.schema ?? op2.response, "seed", streamFor(ctx.seed, `singleton:${twin.id}:${collection}`), 0);
919
- if (!scoped.length && isObj(row3)) rows2.push(row3);
918
+ const row3 = scoped[0] ?? materialize(resource2.schema ?? op2.response, "seed", streamFor(ctx.seed, `singleton:${twin.id}:${collection}`), 0);
919
+ if (!scoped.length && isObj(row3)) rows6.push(row3);
920
920
  return { status: op2.status, body: visible(row3), collection, operation: "read" };
921
921
  }
922
922
  if (req.method === "DELETE") {
923
- rows2.length = 0;
923
+ rows6.length = 0;
924
924
  return { status: op2.status === 200 && !op2.response ? 204 : op2.status, body: op2.response ? {} : null, collection, operation: "write", record: {} };
925
925
  }
926
926
  const row2 = scoped[0] ?? {};
927
927
  overlay(row2, body, op2.body, true);
928
- if (!scoped.length) rows2.push(row2);
928
+ if (!scoped.length) rows6.push(row2);
929
929
  return { status: op2.status, body: visible(row2), collection, operation: "write", record: row2 };
930
930
  }
931
- if (op2.kind === "create" || op2.kind === "upsert" && findRow(scoped, resource, id) < 0) {
932
- if (rows2.length >= 1e4) return fail(429, "capacity", "Twin collection is full");
933
- const record3 = materialize(resource.schema ?? op2.response, "create", stream, ctx.sequence) ?? {};
934
- overlay(record3, body, resource.schema, true);
935
- const supplied = Object.keys(body).find((k) => normName(k) === normName(resource.idField));
936
- if (id !== void 0) record3[resource.idField] = id;
937
- else if (!supplied) record3[resource.idField] = newId(resource, rows2, stream);
938
- else if (findRow(scoped, resource, String(record3[resource.idField])) >= 0) return fail(409, "conflict", `${resource.name} ${record3[resource.idField]} already exists`);
931
+ if (op2.kind === "create" || op2.kind === "upsert" && findRow(scoped, resource2, id) < 0) {
932
+ if (rows6.length >= 1e4) return fail(429, "capacity", "Twin collection is full");
933
+ const record3 = materialize(resource2.schema ?? op2.response, "create", stream, ctx.sequence) ?? {};
934
+ overlay(record3, body, resource2.schema, true);
935
+ const supplied = Object.keys(body).find((k) => normName(k) === normName(resource2.idField));
936
+ if (id !== void 0) record3[resource2.idField] = id;
937
+ else if (!supplied) record3[resource2.idField] = newId(resource2, rows6, stream);
938
+ else if (findRow(scoped, resource2, String(record3[resource2.idField])) >= 0) return fail(409, "conflict", `${resource2.name} ${record3[resource2.idField]} already exists`);
939
939
  for (const p of op2.parentParams ?? []) {
940
- const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
940
+ const field = Object.keys(resource2.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
941
941
  if (field && record3[field] === void 0) record3[field] = params[p];
942
942
  else if (!field) record3[parentKey(p)] = params[p];
943
943
  }
944
- rows2.push(record3);
945
- return { status: op2.kind === "upsert" ? op2.status || 200 : op2.status, body: shape(op2, resource, record3, stream, ctx.sequence, params), collection, operation: "write", record: visible(record3) };
944
+ rows6.push(record3);
945
+ return { status: op2.kind === "upsert" ? op2.status || 200 : op2.status, body: shape(op2, resource2, record3, stream, ctx.sequence, params), collection, operation: "write", record: visible(record3) };
946
946
  }
947
- const index = rows2.findIndex((r) => String(r[resource.idField]) === id && inScope(r, resource, params, op2));
948
- if (index < 0) return { ...fail(404, "not_found", `No such ${singular(resource.name)}: ${id}`), operation: "read" };
949
- const row = rows2[index];
950
- if (op2.kind === "read") return { status: op2.status, body: shape(op2, resource, row, stream, ctx.sequence, params), collection, operation: "read" };
947
+ const index = rows6.findIndex((r) => String(r[resource2.idField]) === id && inScope(r, resource2, params, op2));
948
+ if (index < 0) return { ...fail(404, "not_found", `No such ${singular(resource2.name)}: ${id}`), operation: "read" };
949
+ const row = rows6[index];
950
+ if (op2.kind === "read") return { status: op2.status, body: shape(op2, resource2, row, stream, ctx.sequence, params), collection, operation: "read" };
951
951
  if (op2.kind === "delete") {
952
- rows2.splice(index, 1);
952
+ rows6.splice(index, 1);
953
953
  const props = op2.response?.properties;
954
- const reply = props ? { ...materialize(op2.response, "create", stream, ctx.sequence), ...Object.hasOwn(props, resource.idField) ? { [resource.idField]: row[resource.idField] } : {}, ...props.deleted ? { deleted: true } : {} } : null;
954
+ const reply = props ? { ...materialize(op2.response, "create", stream, ctx.sequence), ...Object.hasOwn(props, resource2.idField) ? { [resource2.idField]: row[resource2.idField] } : {}, ...props.deleted ? { deleted: true } : {} } : null;
955
955
  return { status: reply ? op2.status : op2.status === 200 ? 204 : op2.status, body: reply, collection, operation: "write", record: visible(row) };
956
956
  }
957
957
  if (op2.kind === "action") {
958
958
  const verb = normName(op2.path.split("/").pop() ?? "");
959
- const status = Object.entries(resource.schema?.properties ?? {}).find(([k]) => /^(status|state)$/i.test(k));
959
+ const status = Object.entries(resource2.schema?.properties ?? {}).find(([k]) => /^(status|state)$/i.test(k));
960
960
  const target = status?.[1].enum?.find((v) => typeof v === "string" && (normName(v).startsWith(verb.slice(0, 5)) || normName(v) === verb + "ed" || normName(v) === verb + "d"));
961
961
  if (status && target !== void 0) row[status[0]] = target;
962
- overlay(row, body, resource.schema, true);
963
- for (const [k, s] of Object.entries(resource.schema?.properties ?? {})) if (UPDATED.has(normName(k))) row[k] = stamp(s, ctx.sequence);
964
- return { status: op2.status, body: shape(op2, resource, row, stream, ctx.sequence, params), collection, operation: "write", record: visible(row) };
962
+ overlay(row, body, resource2.schema, true);
963
+ for (const [k, s] of Object.entries(resource2.schema?.properties ?? {})) if (UPDATED.has(normName(k))) row[k] = stamp(s, ctx.sequence);
964
+ return { status: op2.status, body: shape(op2, resource2, row, stream, ctx.sequence, params), collection, operation: "write", record: visible(row) };
965
965
  }
966
- const next = op2.kind === "replace" || op2.kind === "upsert" ? Object.fromEntries(Object.entries(row).filter(([k]) => k === resource.idField || k.startsWith(HIDDEN) || CREATED.has(normName(k)))) : structuredClone(row);
967
- overlay(next, body, resource.schema, op2.kind === "update");
968
- next[resource.idField] = row[resource.idField];
969
- for (const [k, s] of Object.entries(resource.schema?.properties ?? {})) if (UPDATED.has(normName(k))) next[k] = stamp(s, ctx.sequence);
970
- rows2[index] = next;
971
- return { status: op2.status === 201 ? 200 : op2.status, body: shape(op2, resource, next, stream, ctx.sequence, params), collection, operation: "write", record: visible(next) };
966
+ const next = op2.kind === "replace" || op2.kind === "upsert" ? Object.fromEntries(Object.entries(row).filter(([k]) => k === resource2.idField || k.startsWith(HIDDEN) || CREATED.has(normName(k)))) : structuredClone(row);
967
+ overlay(next, body, resource2.schema, op2.kind === "update");
968
+ next[resource2.idField] = row[resource2.idField];
969
+ for (const [k, s] of Object.entries(resource2.schema?.properties ?? {})) if (UPDATED.has(normName(k))) next[k] = stamp(s, ctx.sequence);
970
+ rows6[index] = next;
971
+ return { status: op2.status === 201 ? 200 : op2.status, body: shape(op2, resource2, next, stream, ctx.sequence, params), collection, operation: "write", record: visible(next) };
972
972
  }
973
973
 
974
974
  // src/runtime/enterprise-twins.ts
@@ -989,21 +989,41 @@ var limitOf = (value, fallback, max) => {
989
989
  const n = Number(value);
990
990
  return Number.isInteger(n) && n >= 1 && n <= max ? n : null;
991
991
  };
992
- var nextNumber = (rows2, key2, start) => rows2.reduce((max, r) => Math.max(max, Number(String(r[key2] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
992
+ var nextNumber = (rows6, key2, start) => rows6.reduce((max, r) => Math.max(max, Number(String(r[key2] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
993
993
  var header = (headers, name) => {
994
994
  const v = headers[name];
995
995
  return Array.isArray(v) ? v[0] : v;
996
996
  };
997
997
  function eqFilter(expression, quote2) {
998
998
  const parts = expression.split(/\s+and\s+/i), tests = [];
999
+ const compare = (actual, op2, value) => {
1000
+ const equal = actual === value || typeof value === "number" && String(actual) === String(value);
1001
+ if (op2 === "eq") return equal;
1002
+ if (op2 === "ne") return !equal;
1003
+ if (actual === void 0 || actual === null) return false;
1004
+ let a = actual, b = value;
1005
+ if (typeof a === "string" && typeof b === "string") {
1006
+ const ad = Date.parse(a), bd = Date.parse(b);
1007
+ if (Number.isFinite(ad) && Number.isFinite(bd)) {
1008
+ a = ad;
1009
+ b = bd;
1010
+ }
1011
+ } else if (typeof b === "number" && typeof a === "string" && /^-?\d+(?:\.\d+)?$/.test(a)) a = Number(a);
1012
+ const left = a, right = b;
1013
+ if (left === right) return op2 === "ge" || op2 === "le";
1014
+ return op2 === "ge" ? left > right : op2 === "le" ? left < right : op2 === "gt" ? left > right : left < right;
1015
+ };
999
1016
  for (const part of parts) {
1000
- const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote2}([^${quote2}]*)${quote2}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
1017
+ const any = /^\s*categories\/any\(\s*c\s*:\s*c\s+eq\s+'([^']*)'\s*\)\s*$/i.exec(part);
1018
+ if (any) {
1019
+ tests.push((r) => Array.isArray(r.categories) && r.categories.includes(any[1]));
1020
+ continue;
1021
+ }
1022
+ const m = new RegExp(`^\\s*([\\w.]+)\\s+(eq|ne|ge|le|gt|lt)\\s+(?:${quote2}([^${quote2}]*)${quote2}|(true|false|-?\\d+(?:\\.\\d+)?|null|\\d{4}-\\d{2}-\\d{2}T[\\d:.+-]+Z?))\\s*$`, "i").exec(part);
1001
1023
  if (!m) return null;
1002
- const value = m[2] !== void 0 ? m[2] : m[3] === "null" ? null : m[3] === "true" ? true : m[3] === "false" ? false : Number(m[3]);
1003
- tests.push((r) => {
1004
- const actual = m[1].split(".").reduce((v, k) => v?.[k], r);
1005
- return actual === value || typeof value === "number" && String(actual) === String(value);
1006
- });
1024
+ const op2 = m[2].toLowerCase();
1025
+ const value = m[3] !== void 0 ? m[3] : m[4] === "null" ? null : m[4] === "true" ? true : m[4] === "false" ? false : /^\d{4}-\d{2}-\d{2}T/.test(m[4]) ? m[4] : Number(m[4]);
1026
+ tests.push((r) => compare(m[1].split(".").reduce((v, k) => v?.[k], r), op2, value));
1007
1027
  }
1008
1028
  return (r) => tests.every((t) => t(r));
1009
1029
  }
@@ -1052,18 +1072,18 @@ var salesforce = (method, path, body, query, _headers, data, sequence) => {
1052
1072
  if (!s) return;
1053
1073
  const object3 = s[1], spec = SF_OBJECTS[object3], collection = `/sobjects/${object3}`;
1054
1074
  if (!spec) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
1055
- const rows2 = table(data, collection);
1075
+ const rows6 = table(data, collection);
1056
1076
  if (!s[2] && method === "POST") {
1057
1077
  if (!flat(body)) return;
1058
1078
  const missing = spec.required.filter((f) => body[f] === void 0 || body[f] === null || body[f] === "");
1059
1079
  if (missing.length) return { ...sfError(400, "REQUIRED_FIELD_MISSING", `Required fields are missing: [${missing.join(", ")}]`, missing), collection };
1060
- const id = (spec.prefix + hash(`salesforce:${object3}:${sequence}:${rows2.length}`).slice(0, 12)).toUpperCase().replace(/^00Q/i, "00Q") + "AAA";
1080
+ const id = (spec.prefix + hash(`salesforce:${object3}:${sequence}:${rows6.length}`).slice(0, 12)).toUpperCase().replace(/^00Q/i, "00Q") + "AAA";
1061
1081
  const record4 = { Id: id, ...body, CreatedDate: iso(sequence), LastModifiedDate: iso(sequence), IsDeleted: false };
1062
- rows2.push(record4);
1082
+ rows6.push(record4);
1063
1083
  return write(collection, record4, { id, success: true, errors: [] }, 201);
1064
1084
  }
1065
1085
  if (!s[2]) return;
1066
- const record3 = rows2.find((r) => r.Id === s[2] || String(r.Id).slice(0, 15) === s[2].slice(0, 15));
1086
+ const record3 = rows6.find((r) => r.Id === s[2] || String(r.Id).slice(0, 15) === s[2].slice(0, 15));
1067
1087
  if (!record3) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
1068
1088
  if (method === "GET") return read(collection, sfView(object3, version, record3));
1069
1089
  if (method === "PATCH") {
@@ -1072,7 +1092,7 @@ var salesforce = (method, path, body, query, _headers, data, sequence) => {
1072
1092
  return write(collection, record3, null, 204);
1073
1093
  }
1074
1094
  if (method === "DELETE") {
1075
- rows2.splice(rows2.indexOf(record3), 1);
1095
+ rows6.splice(rows6.indexOf(record3), 1);
1076
1096
  return write(collection, { ...record3, IsDeleted: true }, null, 204);
1077
1097
  }
1078
1098
  };
@@ -1084,7 +1104,7 @@ var servicenow = (method, path, body, query, _headers, data, sequence) => {
1084
1104
  if (!m) return;
1085
1105
  const [, name, sysId] = m, collection = `/${name}`;
1086
1106
  if (!(name in SN_TABLES)) return { ...snError(400, "Invalid table", `Invalid table ${name}`), collection };
1087
- const rows2 = table(data, collection);
1107
+ const rows6 = table(data, collection);
1088
1108
  if (!sysId && method === "GET") {
1089
1109
  const limit = limitOf(query.sysparm_limit, 1e4, 1e4), offset = Number(query.sysparm_offset ?? 0);
1090
1110
  if (limit === null || !Number.isInteger(offset) || offset < 0) return;
@@ -1094,7 +1114,7 @@ var servicenow = (method, path, body, query, _headers, data, sequence) => {
1094
1114
  if (!c || /^(OR|NQ|ORDERBY)/.test(clause)) return;
1095
1115
  tests.push((r) => String(r[c[1]] ?? "") === c[3] === (c[2] === "="));
1096
1116
  }
1097
- const matched = rows2.filter((r) => tests.every((t) => t(r)));
1117
+ const matched = rows6.filter((r) => tests.every((t) => t(r)));
1098
1118
  const fields = query.sysparm_fields?.split(",").map((f) => f.trim());
1099
1119
  const page = matched.slice(offset, offset + limit).map((r) => fields ? Object.fromEntries(fields.map((f) => [f, r[f] ?? ""])) : r);
1100
1120
  return read(collection, { result: page }, 200, { "x-total-count": String(matched.length) });
@@ -1103,19 +1123,19 @@ var servicenow = (method, path, body, query, _headers, data, sequence) => {
1103
1123
  if (!flat(body) || "sys_id" in body) return;
1104
1124
  const prefix = SN_TABLES[name];
1105
1125
  const record4 = {
1106
- sys_id: hash(`servicenow:${name}:${sequence}:${rows2.length}`).slice(0, 32),
1107
- ...prefix ? { number: `${prefix}${String(nextNumber(rows2, "number", 10001)).padStart(7, "0")}` } : {},
1126
+ sys_id: hash(`servicenow:${name}:${sequence}:${rows6.length}`).slice(0, 32),
1127
+ ...prefix ? { number: `${prefix}${String(nextNumber(rows6, "number", 10001)).padStart(7, "0")}` } : {},
1108
1128
  ...name === "incident" ? { state: "1", impact: "3", urgency: "3", priority: "5" } : {},
1109
1129
  ...Object.fromEntries(Object.entries(body).map(([k, v]) => [k, v === null ? "" : String(v)])),
1110
1130
  sys_created_on: snTime(sequence),
1111
1131
  sys_updated_on: snTime(sequence),
1112
1132
  sys_mod_count: "0"
1113
1133
  };
1114
- rows2.push(record4);
1134
+ rows6.push(record4);
1115
1135
  return write(collection, record4, { result: record4 }, 201);
1116
1136
  }
1117
1137
  if (!sysId) return;
1118
- const record3 = rows2.find((r) => r.sys_id === sysId);
1138
+ const record3 = rows6.find((r) => r.sys_id === sysId);
1119
1139
  if (!record3) return { ...snError(404, "No Record found", "Record doesn't exist or ACL restricts the record retrieval"), collection };
1120
1140
  if (method === "GET") return read(collection, { result: record3 });
1121
1141
  if (method === "PATCH" || method === "PUT") {
@@ -1124,7 +1144,7 @@ var servicenow = (method, path, body, query, _headers, data, sequence) => {
1124
1144
  return write(collection, record3, { result: record3 });
1125
1145
  }
1126
1146
  if (method === "DELETE") {
1127
- rows2.splice(rows2.indexOf(record3), 1);
1147
+ rows6.splice(rows6.indexOf(record3), 1);
1128
1148
  return write(collection, record3, null, 204);
1129
1149
  }
1130
1150
  };
@@ -1173,24 +1193,24 @@ var sapView = (set, r) => ({ __metadata: { id: `/sap/opu/odata/sap/${SAP_SETS[se
1173
1193
  var sap = (method, path, body, query, headers, data, sequence) => {
1174
1194
  const m = /^\/sap\/opu\/odata\/sap\/(API_BUSINESS_PARTNER|API_SALES_ORDER_SRV)\/(A_BusinessPartner|A_SalesOrder)(?:\('([^']{1,20})'\))?$/.exec(path);
1175
1195
  if (!m || SAP_SETS[m[2]].service !== m[1]) return;
1176
- const [, , set, key2] = m, collection = `/${set}`, rows2 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
1196
+ const [, , set, key2] = m, collection = `/${set}`, rows6 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
1177
1197
  if (method === "GET") {
1178
1198
  const issued = header(headers, "x-csrf-token")?.toLowerCase() === "fetch" ? { "x-csrf-token": csrf } : void 0;
1179
1199
  if (key2) {
1180
- const record4 = rows2.find((r) => r[SAP_SETS[set].key] === key2);
1200
+ const record4 = rows6.find((r) => r[SAP_SETS[set].key] === key2);
1181
1201
  return record4 ? read(collection, { d: sapView(set, record4) }, 200, issued) : { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection };
1182
1202
  }
1183
1203
  const where = query.$filter ? eqFilter(query.$filter, "'") : () => true;
1184
1204
  const top = limitOf(query.$top, 1e3, 5e3), skip = Number(query.$skip ?? 0);
1185
1205
  if (!where || top === null || !Number.isInteger(skip) || skip < 0) return;
1186
- return read(collection, { d: { results: rows2.filter(where).slice(skip, skip + top).map((r) => sapView(set, r)) } }, 200, issued);
1206
+ return read(collection, { d: { results: rows6.filter(where).slice(skip, skip + top).map((r) => sapView(set, r)) } }, 200, issued);
1187
1207
  }
1188
1208
  if (header(headers, "x-csrf-token") !== csrf) return { ...sapError(403, "403", "CSRF token validation failed", { "x-csrf-token": "Required" }), collection };
1189
1209
  if (method === "POST" && !key2) {
1190
1210
  if (set === "A_BusinessPartner") {
1191
1211
  if (!flat(body) || !["1", "2"].includes(String(body.BusinessPartnerCategory))) return { ...sapError(400, "R11/005", "Enter a valid business partner category (1 = person, 2 = organization)"), collection };
1192
- const record5 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${twinNowMs((EPOCH + sequence) * 1e3)})/`, BusinessPartnerIsBlocked: false };
1193
- rows2.push(record5);
1212
+ const record5 = { BusinessPartner: String(nextNumber(rows6, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${twinNowMs((EPOCH + sequence) * 1e3)})/`, BusinessPartnerIsBlocked: false };
1213
+ rows6.push(record5);
1194
1214
  return write(collection, record5, { d: sapView(set, record5) }, 201);
1195
1215
  }
1196
1216
  const items = isObject(body.to_Item) && Array.isArray(body.to_Item.results) ? body.to_Item.results : null;
@@ -1199,7 +1219,7 @@ var sap = (method, path, body, query, headers, data, sequence) => {
1199
1219
  const total = items.reduce((sum, i) => sum + Number(i.NetAmount ?? 0), 0);
1200
1220
  const { to_Item: _items, ...header_ } = body;
1201
1221
  const record4 = {
1202
- SalesOrder: String(nextNumber(rows2, "SalesOrder", 1)).padStart(10, "0"),
1222
+ SalesOrder: String(nextNumber(rows6, "SalesOrder", 1)).padStart(10, "0"),
1203
1223
  ...header_,
1204
1224
  TransactionCurrency: body.TransactionCurrency ?? "USD",
1205
1225
  TotalNetAmount: total.toFixed(2),
@@ -1207,10 +1227,10 @@ var sap = (method, path, body, query, headers, data, sequence) => {
1207
1227
  CreationDate: `/Date(${twinNowMs((EPOCH + sequence) * 1e3)})/`,
1208
1228
  to_Item: { results: items.map((i, n) => ({ SalesOrderItem: String((n + 1) * 10), ...i })) }
1209
1229
  };
1210
- rows2.push(record4);
1230
+ rows6.push(record4);
1211
1231
  return write(collection, record4, { d: sapView(set, record4) }, 201);
1212
1232
  }
1213
- const record3 = key2 ? rows2.find((r) => r[SAP_SETS[set].key] === key2) : void 0;
1233
+ const record3 = key2 ? rows6.find((r) => r[SAP_SETS[set].key] === key2) : void 0;
1214
1234
  if (!record3) return key2 ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
1215
1235
  if (method === "PATCH" || method === "MERGE") {
1216
1236
  if (!flat(body) || SAP_SETS[set].key in body) return;
@@ -1223,11 +1243,24 @@ var graphId = (seed) => {
1223
1243
  const h = hash(seed);
1224
1244
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
1225
1245
  };
1226
- var graphPage = (rows2, query) => {
1246
+ var graphPage = (rows6, query) => {
1227
1247
  const where = query.$filter ? eqFilter(query.$filter, "'") : () => true, top = limitOf(query.$top, 100, 999);
1228
1248
  if (!where || top === null) return null;
1249
+ let filtered = rows6.filter(where);
1250
+ if (query.$orderby !== void 0) {
1251
+ const [field, direction] = query.$orderby.trim().split(/\s+/);
1252
+ const value = (r) => field.split(".").reduce((v, k) => v?.[k], r);
1253
+ const sign = /^desc$/i.test(direction ?? "") ? -1 : 1;
1254
+ filtered = [...filtered].sort((a, b) => {
1255
+ const left = value(a), right = value(b);
1256
+ if (left === right) return 0;
1257
+ if (left === void 0 || left === null) return 1;
1258
+ if (right === void 0 || right === null) return -1;
1259
+ return sign * (left < right ? -1 : 1);
1260
+ });
1261
+ }
1229
1262
  const select = query.$select?.split(",").map((s) => s.trim());
1230
- return rows2.filter(where).slice(0, top).map((r) => select ? Object.fromEntries([["id", r.id], ...select.map((s) => [s, r[s] ?? null])]) : r);
1263
+ return filtered.slice(0, top).map((r) => select ? Object.fromEntries([["id", r.id], ...select.map((s) => [s, r[s] ?? null])]) : r);
1231
1264
  };
1232
1265
  var teams = (method, path, body, query, _headers, data, sequence) => {
1233
1266
  const m = /^\/v1\.0\/(?:teams\/([\w-]+)\/channels(?:\/([\w:@.%-]+)\/messages(?:\/(\d+)\/replies)?)?|chats\/([\w:@.%-]+)\/messages)$/.exec(path);
@@ -1264,11 +1297,56 @@ var teams = (method, path, body, query, _headers, data, sequence) => {
1264
1297
  return write("/messages", record3, record3, 201);
1265
1298
  };
1266
1299
  var address = (r) => isObject(r) && isObject(r.emailAddress) && typeof r.emailAddress.address === "string" && /^[^@\s]+@[^@\s]+$/.test(r.emailAddress.address);
1300
+ var OUTLOOK_FOLDERS = [
1301
+ { id: "inbox", displayName: "Inbox", parentFolderId: null, childFolderCount: 0, isHidden: false },
1302
+ { id: "drafts", displayName: "Drafts", parentFolderId: null, childFolderCount: 0, isHidden: false },
1303
+ { id: "sentitems", displayName: "Sent Items", parentFolderId: null, childFolderCount: 0, isHidden: false },
1304
+ { id: "deleteditems", displayName: "Deleted Items", parentFolderId: null, childFolderCount: 0, isHidden: false },
1305
+ { id: "archive", displayName: "Archive", parentFolderId: null, childFolderCount: 0, isHidden: false },
1306
+ { id: "outbox", displayName: "Outbox", parentFolderId: null, childFolderCount: 0, isHidden: false },
1307
+ { id: "junkemail", displayName: "Junk Email", parentFolderId: null, childFolderCount: 0, isHidden: false }
1308
+ ];
1309
+ var outlookFolderRows = (messages, data) => {
1310
+ const seeded = table(data, "/mailFolders");
1311
+ const folders = seeded.length ? seeded : OUTLOOK_FOLDERS.map((f) => ({ ...f }));
1312
+ const inFolder = (id) => messages.filter((m) => id === "inbox" ? !m.parentFolderId || m.parentFolderId === "inbox" : m.parentFolderId === id);
1313
+ return folders.map((folder) => {
1314
+ const rows6 = inFolder(String(folder.id));
1315
+ return { ...folder, totalItemCount: rows6.length, unreadItemCount: rows6.filter((m) => m.isRead === false).length };
1316
+ });
1317
+ };
1318
+ var outlookToken = (method, body, data, sequence) => {
1319
+ if (method !== "POST") return;
1320
+ const failToken = (status, error, description) => ({ status, body: { error, error_description: description, trace_id: graphId(`trace:${sequence}`), correlation_id: graphId(`corr:${sequence}`) }, collection: "/tokens" });
1321
+ const grant = String(body.grant_type ?? "");
1322
+ if (grant !== "client_credentials" && grant !== "refresh_token") return failToken(400, "unsupported_grant_type", `AADSTS70003: The grant type '${grant}' is not supported.`);
1323
+ const bounded = (v) => typeof v === "string" && v.length > 0 && v.length <= 256;
1324
+ if (!bounded(body.client_id)) return failToken(400, "invalid_request", "AADSTS900144: The request body must contain the following parameter: client_id.");
1325
+ if (grant === "refresh_token") {
1326
+ if (!bounded(body.refresh_token)) return failToken(400, "invalid_request", "AADSTS900144: The request body must contain the following parameter: refresh_token.");
1327
+ const grants = table(data, "/grants");
1328
+ if (grants.length && !grants.some((g) => g.refresh_token === body.refresh_token && g.active !== false)) return failToken(400, "invalid_grant", "AADSTS70008: The provided authorization grant is expired, revoked, or invalid.");
1329
+ } else if (!bounded(body.client_secret)) return failToken(401, "invalid_client", "AADSTS7000215: Invalid client secret provided.");
1330
+ const expires_in = 3599;
1331
+ const response = {
1332
+ token_type: "Bearer",
1333
+ scope: String(body.scope ?? "https://graph.microsoft.com/.default"),
1334
+ expires_in,
1335
+ ext_expires_in: expires_in,
1336
+ access_token: `synthetic-ms-access-${hash(`outlook:${sequence}:${JSON.stringify(body)}`).slice(0, 24)}`,
1337
+ ...grant === "refresh_token" ? { refresh_token: String(body.refresh_token) } : {}
1338
+ };
1339
+ const record3 = { id: `token_${sequence}`, client_id: body.client_id, grant_type: grant, issued_at: iso(sequence), ...response };
1340
+ table(data, "/tokens").push(record3);
1341
+ return write("/tokens", record3, response);
1342
+ };
1267
1343
  var outlook = (method, path, body, query, _headers, data, sequence) => {
1268
- const m = /^\/v1\.0\/(?:me|users\/[^/]+)\/(sendMail|messages|mailFolders\/(inbox|sentitems)\/messages|messages\/([\w=-]+)(?:\/(reply))?)$/.exec(path);
1269
- if (!m) return;
1270
- const messages = table(data, "/messages"), [, route, folder, id, reply] = m;
1271
- const store = (message, parentFolderId) => {
1344
+ if (/^\/(?:common|organizations|consumers|[^/]+)\/oauth2\/(?:v2\.0\/)?token$/.test(path)) return outlookToken(method, body, data, sequence);
1345
+ const envelope = /^\/v1\.0\/(?:(?:me|users\/[^/]+)\/)?(.+)$/.exec(path);
1346
+ if (!envelope) return;
1347
+ const rest = envelope[1];
1348
+ const messages = table(data, "/messages");
1349
+ const store = (message, parentFolderId, draft = false) => {
1272
1350
  const record4 = {
1273
1351
  id: Buffer.from(hash(`outlook:${sequence}:${messages.length}`).slice(0, 30)).toString("base64url"),
1274
1352
  createdDateTime: iso(sequence),
@@ -1280,7 +1358,7 @@ var outlook = (method, path, body, query, _headers, data, sequence) => {
1280
1358
  ccRecipients: message.ccRecipients ?? [],
1281
1359
  from: { emailAddress: { address: "agent@contoso.test", name: "Agent" } },
1282
1360
  isRead: true,
1283
- isDraft: false,
1361
+ isDraft: draft,
1284
1362
  importance: message.importance ?? "normal",
1285
1363
  parentFolderId,
1286
1364
  conversationId: message.conversationId ?? graphId(`conv:${sequence}`)
@@ -1288,7 +1366,77 @@ var outlook = (method, path, body, query, _headers, data, sequence) => {
1288
1366
  messages.push(record4);
1289
1367
  return record4;
1290
1368
  };
1291
- if (route === "sendMail" && method === "POST") {
1369
+ const notFound2 = (collection) => ({ ...graphError(404, "ErrorItemNotFound", "The specified object was not found in the store.", sequence), collection });
1370
+ const delta = (rows6, collection) => {
1371
+ const token = query.$deltaToken;
1372
+ if (token !== void 0 && !/^\d{1,20}$/.test(token)) return { ...graphError(400, "InvalidRequest", "Invalid delta token.", sequence), collection };
1373
+ const start = token === void 0 ? 0 : Math.min(Number(token), rows6.length);
1374
+ return read(collection, {
1375
+ "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('me')/messages",
1376
+ value: rows6.slice(start).map((r) => ({ "@odata.etag": `W/"${hash(String(r.id)).slice(0, 27)}"`, ...structuredClone(r) })),
1377
+ "@odata.deltaLink": `https://graph.microsoft.com/v1.0/me/messages/delta?$deltaToken=${rows6.length}`
1378
+ });
1379
+ };
1380
+ if (rest === "subscriptions" || /^subscriptions\/[^/]+$/.test(rest)) {
1381
+ const subscriptions = table(data, "/subscriptions");
1382
+ if (rest === "subscriptions") {
1383
+ if (method === "GET") return read("/subscriptions", { value: subscriptions.map((row) => structuredClone(row)) });
1384
+ if (method !== "POST") return;
1385
+ if (Object.keys(body).some((k) => !["changeType", "notificationUrl", "resource", "expirationDateTime", "clientState", "lifecycleNotificationUrl", "includeResourceData", "encryptionCertificate", "encryptionCertificateId", "latestSupportedTlsVersion"].includes(k))) return;
1386
+ if (typeof body.changeType !== "string" || typeof body.notificationUrl !== "string" || typeof body.resource !== "string") return { ...graphError(400, "BadRequest", "changeType, notificationUrl and resource are required.", sequence), collection: "/subscriptions" };
1387
+ if (!/^https?:\/\//.test(body.notificationUrl) || !["created", "updated", "deleted"].includes(body.changeType)) return { ...graphError(400, "InvalidRequest", "notificationUrl must be http(s) and changeType created, updated or deleted.", sequence), collection: "/subscriptions" };
1388
+ const record4 = {
1389
+ id: graphId(`subscription:${sequence}:${subscriptions.length}`),
1390
+ changeType: body.changeType,
1391
+ notificationUrl: body.notificationUrl,
1392
+ resource: body.resource,
1393
+ expirationDateTime: typeof body.expirationDateTime === "string" ? body.expirationDateTime : new Date(twinNowMs((EPOCH + sequence + 3600) * 1e3)).toISOString(),
1394
+ clientState: typeof body.clientState === "string" ? body.clientState : graphId(`clientState:${sequence}`),
1395
+ lifecycleNotificationUrl: body.lifecycleNotificationUrl ?? null,
1396
+ applicationId: "agenttwin-app",
1397
+ creatorId: "agenttwin-user"
1398
+ };
1399
+ subscriptions.push(record4);
1400
+ return write("/subscriptions", record4, record4, 201);
1401
+ }
1402
+ const id2 = decodeURIComponent(rest.slice("subscriptions/".length));
1403
+ const index = subscriptions.findIndex((row) => row.id === id2);
1404
+ if (index < 0) return notFound2("/subscriptions");
1405
+ if (method === "GET") return read("/subscriptions", subscriptions[index]);
1406
+ if (method === "PATCH" || method === "PUT") {
1407
+ if (Object.keys(body).some((k) => k !== "expirationDateTime") || typeof body.expirationDateTime !== "string") return { ...graphError(400, "InvalidRequest", "Only expirationDateTime can be renewed.", sequence), collection: "/subscriptions" };
1408
+ subscriptions[index] = { ...subscriptions[index], expirationDateTime: body.expirationDateTime };
1409
+ return write("/subscriptions", subscriptions[index], subscriptions[index]);
1410
+ }
1411
+ if (method === "DELETE") {
1412
+ const [removed] = subscriptions.splice(index, 1);
1413
+ return write("/subscriptions", removed, null, 204);
1414
+ }
1415
+ return;
1416
+ }
1417
+ if (rest === "mailFolders" && method === "GET") {
1418
+ const page = graphPage(outlookFolderRows(messages, data), query);
1419
+ return page ? read("/mailFolders", { value: page }) : void 0;
1420
+ }
1421
+ const folderMatch = /^mailFolders\/([^/]+)(\/messages(\/delta)?)?$/.exec(rest);
1422
+ if (folderMatch) {
1423
+ const folderId = decodeURIComponent(folderMatch[1]);
1424
+ const folder = outlookFolderRows(messages, data).find((f) => String(f.id) === folderId);
1425
+ if (!folder) return notFound2("/mailFolders");
1426
+ if (!folderMatch[2]) {
1427
+ if (method !== "GET") return;
1428
+ return read("/mailFolders", folder);
1429
+ }
1430
+ const inFolder = messages.filter((m) => folderId === "inbox" ? !m.parentFolderId || m.parentFolderId === "inbox" : m.parentFolderId === folderId);
1431
+ if (folderMatch[3]) {
1432
+ if (method !== "GET") return;
1433
+ return delta(inFolder, "/messages");
1434
+ }
1435
+ if (method !== "GET") return;
1436
+ const page = graphPage(inFolder, query);
1437
+ return page ? read("/messages", { value: page }) : void 0;
1438
+ }
1439
+ if (rest === "sendMail" && method === "POST") {
1292
1440
  const message = body.message;
1293
1441
  if (!isObject(message)) return { ...graphError(400, "ErrorInvalidRequest", "The message is missing.", sequence), collection: "/messages" };
1294
1442
  const recipients = [...message.toRecipients ?? [], ...message.ccRecipients ?? [], ...message.bccRecipients ?? []];
@@ -1296,22 +1444,47 @@ var outlook = (method, path, body, query, _headers, data, sequence) => {
1296
1444
  if (message.attachments?.length) return;
1297
1445
  return write("/messages", store(message, "sentitems"), null, 202);
1298
1446
  }
1299
- if ((route === "messages" || folder) && method === "GET") {
1300
- const page = graphPage(messages.filter((r) => !folder || r.parentFolderId === folder), query);
1301
- return page ? read("/messages", { value: page }) : void 0;
1447
+ if (rest === "messages/delta") {
1448
+ if (method !== "GET") return;
1449
+ return delta(messages, "/messages");
1302
1450
  }
1303
- const record3 = id ? messages.find((r) => r.id === id) : void 0;
1304
- if (!record3) return id ? { ...graphError(404, "ErrorItemNotFound", "The specified object was not found in the store.", sequence), collection: "/messages" } : void 0;
1305
- if (!reply && method === "GET") return read("/messages", record3);
1306
- if (!reply && method === "PATCH") {
1451
+ if (rest === "messages") {
1452
+ if (method === "GET") {
1453
+ const page = graphPage(messages, query);
1454
+ return page ? read("/messages", { value: page }) : void 0;
1455
+ }
1456
+ if (method !== "POST") return;
1457
+ if (!isObject(body) || Object.keys(body).some((k) => !["subject", "body", "toRecipients", "ccRecipients", "bccRecipients", "importance", "conversationId", "isDraft"].includes(k))) return;
1458
+ return write("/messages", store(body, "drafts", true), null, 201);
1459
+ }
1460
+ const messageMatch = /^messages\/([^/]+)(?:\/(move|reply|replyAll|forward))?$/.exec(rest);
1461
+ if (!messageMatch) return;
1462
+ const id = decodeURIComponent(messageMatch[1]), action = messageMatch[2];
1463
+ const record3 = messages.find((r) => r.id === id);
1464
+ if (!record3) return notFound2("/messages");
1465
+ if (!action && method === "GET") return read("/messages", record3);
1466
+ if (!action && method === "PATCH") {
1307
1467
  if (Object.keys(body).some((k) => !["isRead", "categories", "importance", "flag"].includes(k))) return;
1308
- Object.assign(record3, body);
1468
+ Object.assign(record3, body, { lastModifiedDateTime: iso(sequence) });
1309
1469
  return write("/messages", record3, record3);
1310
1470
  }
1311
- if (reply && method === "POST") {
1312
- const to = record3.parentFolderId === "sentitems" ? record3.toRecipients : [record3.from];
1471
+ if (action === "move") {
1472
+ if (method !== "POST" || Object.keys(body).some((k) => k !== "destinationId") || typeof body.destinationId !== "string" || !body.destinationId) return;
1473
+ if (!outlookFolderRows(messages, data).some((f) => String(f.id) === body.destinationId)) return { ...graphError(400, "ErrorInvalidRequest", "The destination folder is not a recognized mail folder.", sequence), collection: "/messages" };
1474
+ record3.parentFolderId = body.destinationId;
1475
+ record3.lastModifiedDateTime = iso(sequence);
1476
+ return write("/messages", record3, record3, 201);
1477
+ }
1478
+ if (action === "reply" || action === "replyAll") {
1479
+ if (method !== "POST" || Object.keys(body).some((k) => k !== "comment")) return;
1480
+ const to = record3.parentFolderId === "sentitems" ? record3.toRecipients : action === "replyAll" ? [record3.from, ...record3.toRecipients ?? [], ...record3.ccRecipients ?? []] : [record3.from];
1313
1481
  return write("/messages", store({ subject: `RE: ${record3.subject}`, body: { contentType: "text", content: String(body.comment ?? "") }, toRecipients: to, conversationId: record3.conversationId }, "sentitems"), null, 202);
1314
1482
  }
1483
+ if (action === "forward") {
1484
+ if (method !== "POST" || Object.keys(body).some((k) => !["comment", "toRecipients"].includes(k))) return;
1485
+ if (!Array.isArray(body.toRecipients) || !body.toRecipients.length || !body.toRecipients.every(address)) return { ...graphError(400, "ErrorInvalidRecipients", "At least one recipient isn't valid.", sequence), collection: "/messages" };
1486
+ return write("/messages", store({ subject: `FW: ${record3.subject}`, body: { contentType: "text", content: String(body.comment ?? "") }, toRecipients: body.toRecipients, conversationId: record3.conversationId }, "sentitems"), null, 202);
1487
+ }
1315
1488
  };
1316
1489
  var entra = (method, path, body, query, _headers, data, sequence) => {
1317
1490
  const m = /^\/v1\.0\/(users|groups)(?:\/([^/]+))?(?:\/members(?:\/([\w-]+))?(\/\$ref)?)?$/.exec(path);
@@ -1386,17 +1559,17 @@ var okta = (method, path, body, query, _headers, data, sequence) => {
1386
1559
  if (method === "GET") {
1387
1560
  const limit = limitOf(query.limit, 200, 200);
1388
1561
  if (limit === null) return;
1389
- let rows2 = users;
1562
+ let rows6 = users;
1390
1563
  if (query.filter) {
1391
1564
  const where = eqFilter(query.filter, '"');
1392
1565
  if (!where) return;
1393
- rows2 = rows2.filter(where);
1566
+ rows6 = rows6.filter(where);
1394
1567
  }
1395
1568
  if (query.q) {
1396
1569
  const q = query.q.toLowerCase();
1397
- rows2 = rows2.filter((u) => ["firstName", "lastName", "email", "login"].some((f) => String(u.profile?.[f] ?? "").toLowerCase().startsWith(q)));
1570
+ rows6 = rows6.filter((u) => ["firstName", "lastName", "email", "login"].some((f) => String(u.profile?.[f] ?? "").toLowerCase().startsWith(q)));
1398
1571
  }
1399
- return read("/users", rows2.slice(0, limit));
1572
+ return read("/users", rows6.slice(0, limit));
1400
1573
  }
1401
1574
  if (method !== "POST") return;
1402
1575
  const profile = body.profile;
@@ -1603,9 +1776,9 @@ var snowflake = (method, path, body, _query, _headers, data, sequence) => {
1603
1776
  const missing = (name) => ({ status: 422, collection: "/statements", body: { code: "002003", message: `SQL compilation error:
1604
1777
  Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCase()}' does not exist or not authorized.`, sqlState: "02000", statementHandle: handle } });
1605
1778
  const known2 = (name) => Object.hasOwn(data, `/${name}`) && name !== "STATEMENTS";
1606
- const result = (columns, rows2, dml) => ({
1607
- resultSetMetaData: { numRows: rows2.length, format: "jsonv2", partitionInfo: [{ rowCount: rows2.length }], rowType: columns.map((name) => ({ name: dml ?? name, type: dml ? "fixed" : "text", nullable: !dml })) },
1608
- data: rows2.map((r) => r.map((v) => v === null || v === void 0 ? null : String(v))),
1779
+ const result = (columns, rows6, dml) => ({
1780
+ resultSetMetaData: { numRows: rows6.length, format: "jsonv2", partitionInfo: [{ rowCount: rows6.length }], rowType: columns.map((name) => ({ name: dml ?? name, type: dml ? "fixed" : "text", nullable: !dml })) },
1781
+ data: rows6.map((r) => r.map((v) => v === null || v === void 0 ? null : String(v))),
1609
1782
  code: "090001",
1610
1783
  statementStatusUrl: `/api/v2/statements/${handle}`,
1611
1784
  requestId: graphId(`sf-req:${sequence}`),
@@ -1624,15 +1797,15 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
1624
1797
  if (!known2(name)) return missing(name);
1625
1798
  const where = sqlWhere(s[3], bindings, counter);
1626
1799
  if (!where) return;
1627
- let rows2 = data[`/${name}`].filter(where);
1800
+ let rows6 = data[`/${name}`].filter(where);
1628
1801
  if (s[4]) {
1629
1802
  const col = ident(s[4]), dir = s[5]?.toUpperCase() === "DESC" ? -1 : 1;
1630
- rows2 = [...rows2].sort((a, b) => (a[col] > b[col] ? 1 : a[col] < b[col] ? -1 : 0) * dir);
1803
+ rows6 = [...rows6].sort((a, b) => (a[col] > b[col] ? 1 : a[col] < b[col] ? -1 : 0) * dir);
1631
1804
  }
1632
- if (s[6]) rows2 = rows2.slice(0, Number(s[6]));
1805
+ if (s[6]) rows6 = rows6.slice(0, Number(s[6]));
1633
1806
  const columns = s[1].trim() === "*" ? [...new Set(data[`/${name}`].flatMap((r) => Object.keys(r)))] : s[1].split(",").map((c) => ident(c.trim()));
1634
1807
  if (columns.some((c) => !/^[\w$]+$/.test(c))) return;
1635
- return remember(`/${name}`, result(columns, rows2.map((r) => columns.map((c) => r[c] ?? null))), "read");
1808
+ return remember(`/${name}`, result(columns, rows6.map((r) => columns.map((c) => r[c] ?? null))), "read");
1636
1809
  }
1637
1810
  if (s = /^INSERT\s+INTO\s+("?[\w$]+"?)\s*\(([^)]+)\)\s*VALUES\s*(.+)$/is.exec(statement)) {
1638
1811
  const name = ident(s[1]);
@@ -1681,15 +1854,15 @@ var nsLink = (type, id) => [{ rel: "self", href: `/services/rest/record/v1/${typ
1681
1854
  var netsuite = (method, path, body, query, _headers, data, sequence) => {
1682
1855
  const m = /^\/services\/rest\/record\/v1\/(\w+)(?:\/(\d+))?$/.exec(path);
1683
1856
  if (!m || !NS_TYPES.includes(m[1])) return;
1684
- const [, type, id] = m, collection = `/${type}`, rows2 = table(data, collection);
1857
+ const [, type, id] = m, collection = `/${type}`, rows6 = table(data, collection);
1685
1858
  if (!id && method === "GET") {
1686
1859
  const limit = limitOf(query.limit, 1e3, 1e3), offset = Number(query.offset ?? 0);
1687
1860
  if (limit === null || !Number.isInteger(offset) || offset < 0) return;
1688
- let matched = rows2;
1861
+ let matched = rows6;
1689
1862
  if (query.q) {
1690
1863
  const tests = query.q.split(/\s+AND\s+/i).map((part) => /^\s*(\w+)\s+(IS|IS_NOT)\s+"([^"]*)"\s*$/i.exec(part));
1691
1864
  if (tests.some((t) => !t)) return;
1692
- matched = rows2.filter((r) => tests.every((t) => String(r[t[1]] ?? "") === t[3] === (t[2].toUpperCase() === "IS")));
1865
+ matched = rows6.filter((r) => tests.every((t) => String(r[t[1]] ?? "") === t[3] === (t[2].toUpperCase() === "IS")));
1693
1866
  }
1694
1867
  const page = matched.slice(offset, offset + limit);
1695
1868
  return read(collection, { links: [], count: page.length, hasMore: offset + limit < matched.length, items: page.map((r) => ({ links: nsLink(type, r.id), id: r.id })), offset, totalResults: matched.length });
@@ -1706,12 +1879,12 @@ var netsuite = (method, path, body, query, _headers, data, sequence) => {
1706
1879
  if (!lines?.length || !lines.every((l) => isObject(l) && isObject(l.item) && Number(l.quantity) > 0)) return { ...nsError(400, "Bad Request", "You must enter at least one line item for this transaction.", "USER_ERROR"), collection };
1707
1880
  total = lines.reduce((sum, l) => sum + Number(l.quantity) * Number(l.rate ?? 0), 0);
1708
1881
  }
1709
- const newId2 = String(nextNumber(rows2, "id", 1001));
1882
+ const newId2 = String(nextNumber(rows6, "id", 1001));
1710
1883
  const record4 = { id: newId2, ...body, ...total !== void 0 ? { total, currency: body.currency ?? { id: "1", refName: "USD" }, tranId: `${type === "salesOrder" ? "SO" : type === "invoice" ? "INV" : "BILL"}${newId2}` } : {}, dateCreated: iso(sequence), lastModifiedDate: iso(sequence) };
1711
- rows2.push(record4);
1884
+ rows6.push(record4);
1712
1885
  return write(collection, record4, null, 204, { location: `/services/rest/record/v1/${type}/${newId2}` });
1713
1886
  }
1714
- const record3 = id ? rows2.find((r) => r.id === id) : void 0;
1887
+ const record3 = id ? rows6.find((r) => r.id === id) : void 0;
1715
1888
  if (!record3) return { ...nsError(404, "Record Not Found", "The record instance does not exist. Provide a valid record instance ID.", "NONEXISTENT_ID"), collection };
1716
1889
  if (method === "GET") return read(collection, { links: nsLink(type, record3.id), ...record3 });
1717
1890
  if (method === "PATCH") {
@@ -1720,7 +1893,7 @@ var netsuite = (method, path, body, query, _headers, data, sequence) => {
1720
1893
  return write(collection, record3, null, 204);
1721
1894
  }
1722
1895
  if (method === "DELETE") {
1723
- rows2.splice(rows2.indexOf(record3), 1);
1896
+ rows6.splice(rows6.indexOf(record3), 1);
1724
1897
  return write(collection, record3, null, 204);
1725
1898
  }
1726
1899
  };
@@ -1829,7 +2002,7 @@ var ENTERPRISE_OPTIONAL_COLLECTIONS = {
1829
2002
  workday: ["/workers", "/timeOffRequests"],
1830
2003
  sap: ["/A_BusinessPartner", "/A_SalesOrder"],
1831
2004
  "microsoft-teams": ["/channels", "/chats", "/messages"],
1832
- outlook: ["/messages"],
2005
+ outlook: ["/messages", "/mailFolders", "/subscriptions", "/tokens", "/grants"],
1833
2006
  "entra-id": ["/users", "/groups", "/groupMembers"],
1834
2007
  okta: ["/users", "/groups", "/groupMemberships"],
1835
2008
  confluence: ["/pages", "/spaces", "/comments"],
@@ -1842,6 +2015,7 @@ var FREEFORM_COLLECTION_ADAPTERS = ["snowflake"];
1842
2015
  function enterpriseAuth(adapter, headers, url, token) {
1843
2016
  if (adapter === "okta") return headers.authorization === `SSWS ${token}`;
1844
2017
  if (adapter === "pagerduty") return headers.authorization === `Token token=${token}` || new URL(url, "http://localhost").pathname === "/v2/enqueue";
2018
+ if (adapter === "outlook") return /\/oauth2\/(?:v2\.0\/)?token$/.test(new URL(url, "http://localhost").pathname);
1845
2019
  return false;
1846
2020
  }
1847
2021
  var unsupported = (body) => ({ ...body, forwardedToProduction: false });
@@ -1893,10 +2067,10 @@ var ENTERPRISE_CONTRACTS = {
1893
2067
  limitations: ["No adaptive card rendering, mentions resolution, reactions, edits, deletes, meetings or change notifications"]
1894
2068
  },
1895
2069
  outlook: {
1896
- version: "1.0.0",
1897
- authentication: "Bearer run-scoped test token (Graph access token shape)",
1898
- operations: [op("POST", "/v1.0/me/sendMail (or /users/<id>/sendMail)", "send mail (202); stored in sentitems", ["400 ErrorInvalidRecipients"]), op("GET", "/v1.0/me/messages, /me/mailFolders/<inbox|sentitems>/messages", "list with $filter eq, $top, $select"), op("GET|PATCH", "/v1.0/me/messages/<id>", "read / update isRead, categories, importance, flag", ["404 ErrorItemNotFound"]), op("POST", "/v1.0/me/messages/<id>/reply", "reply (202)")],
1899
- limitations: ["No attachments, drafts, forward, rules, calendar or delta queries; inbound mail exists only as seeded records"]
2070
+ version: "1.1.0",
2071
+ authentication: "Bearer run-scoped test token (Graph access token shape); OAuth token endpoint posts form-encoded client credentials",
2072
+ operations: [op("POST", "/v1.0/me/sendMail (or /users/<id>/sendMail)", "send mail (202); stored in sentitems", ["400 ErrorInvalidRecipients"]), op("GET", "/v1.0/me/messages, /me/mailFolders/<id>/messages, /users/<id>/messages", "list with $filter eq, $top, $select"), op("POST", "/v1.0/me/messages", "create a draft message (201)"), op("GET|PATCH", "/v1.0/me/messages/<id>", "read / update isRead, categories, importance, flag", ["404 ErrorItemNotFound"]), op("POST", "/v1.0/me/messages/<id>/{reply|replyAll|forward}", "reply, reply-all or forward (202)", ["400 ErrorInvalidRecipients"]), op("POST", "/v1.0/me/messages/<id>/move", "move to a recognized mail folder (201)", ["400 ErrorInvalidRequest"]), op("GET", "/v1.0/me/messages/delta, /me/mailFolders/<id>/messages/delta", "delta page with @odata.deltaLink; $deltaToken resumes after the messages already returned"), op("GET", "/v1.0/me/mailFolders[/<id>]", "list or read folders with computed totalItemCount/unreadItemCount"), op("GET|POST", "/v1.0/subscriptions", "list / create a change subscription (201)", ["400 BadRequest"]), op("GET|PATCH|DELETE", "/v1.0/subscriptions/<id>", "read / renew expirationDateTime / delete (204)", ["404 ErrorItemNotFound"]), op("POST", "/<tenant>/oauth2/v2.0/token", "client_credentials and refresh_token grants issue synthetic access tokens", ["400 invalid_grant", "400 unsupported_grant_type", "401 invalid_client"])],
2073
+ limitations: ["No attachments, calendar, rules or change-notification delivery; inbound mail exists only as seeded records", "Delta tokens are synthetic mailbox positions, not Graph change tracking; $filter supports eq/ne/ge/le/gt/lt, dotted paths and categories/any(c:c eq), with $top, $select and $orderby; $search, $expand and paging beyond $top are not modelled", "Tokens are synthetic and are not validated by the Graph routes"]
1900
2074
  },
1901
2075
  "entra-id": {
1902
2076
  version: "1.0.0",
@@ -2110,6 +2284,16 @@ var CONTRACTS = {
2110
2284
  { method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
2111
2285
  { method: "POST", endpoint: "/gmail/v1/users/me/labels", effect: "create a user label", parameters: ["name", "labelListVisibility", "messageListVisibility", "color"], errors: ["400 invalid name", "409 name exists"] },
2112
2286
  { method: "POST", endpoint: "/gmail/v1/users/me/{messages|threads}/<id>/modify", effect: "add and remove labels on a message or every message of a thread; bumps the mailbox historyId", parameters: ["addLabelIds", "removeLabelIds"], errors: ["400 Invalid label", "404 not found"] },
2287
+ { method: "POST", endpoint: "/gmail/v1/users/me/messages/batchModify", effect: "add and remove labels on up to 1000 message ids (204)", parameters: ["ids", "addLabelIds", "removeLabelIds"], errors: ["400 ids required", "400 Invalid label"] },
2288
+ { method: "POST", endpoint: "/gmail/v1/users/me/{messages|threads}/<id>/trash", effect: "add TRASH and remove INBOX on a message or every message of a thread; returns the updated record", parameters: [], errors: ["404 not found"] },
2289
+ { method: "POST", endpoint: "/gmail/v1/users/me/{messages|threads}/<id>/untrash", effect: "remove TRASH and add INBOX on a message or every message of a thread; returns the updated record", parameters: [], errors: ["404 not found"] },
2290
+ { method: "GET", endpoint: "/gmail/v1/users/me/labels/<id>", effect: "retrieve one label", parameters: [], errors: ["404 not found"] },
2291
+ { method: "PATCH/PUT", endpoint: "/gmail/v1/users/me/labels/<id>", effect: "update a user label (name, visibility, color); system labels are fixed", parameters: ["name", "labelListVisibility", "messageListVisibility", "color"], errors: ["400 Invalid label", "409 name exists"] },
2292
+ { method: "DELETE", endpoint: "/gmail/v1/users/me/labels/<id>", effect: "delete a user label and remove it from every message (204)", parameters: [], errors: ["400 system label", "404 not found"] },
2293
+ { method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>/attachments/<attachmentId>", effect: "read the base64url data of an attachment a seeded message payload part names", parameters: [], errors: ["404 not found"] },
2294
+ { method: "GET|POST", endpoint: "/gmail/v1/users/me/settings/filters", effect: "list filters / create one with criteria and action", parameters: ["criteria", "action"], errors: ["400 criteria and action required"] },
2295
+ { method: "DELETE", endpoint: "/gmail/v1/users/me/settings/filters/<id>", effect: "delete a filter (204)", parameters: [], errors: ["404 not found"] },
2296
+ { method: "GET", endpoint: "/gmail/v1/users/me/settings/forwardingAddresses", effect: "list seeded forwarding addresses", parameters: [], errors: [] },
2113
2297
  { method: "GET", endpoint: "/gmail/v1/users/me/threads", effect: "list threads, newest first, excluding SPAM/TRASH", parameters: ["q (from:/to: address terms, OR-joined)", "maxResults", "labelIds"], errors: ["400 validation"] },
2114
2298
  { method: "GET", endpoint: "/gmail/v1/users/me/threads/<id>", effect: "retrieve a thread with its messages, oldest first", parameters: ["format=full"], errors: ["404 NOT_FOUND"] },
2115
2299
  { method: "GET", endpoint: "/gmail/v1/users/me/history", effect: "messagesAdded records for messages whose historyId is after startHistoryId", parameters: ["startHistoryId", "historyTypes", "maxResults"], errors: ["400 validation"] },
@@ -2127,7 +2311,7 @@ var CONTRACTS = {
2127
2311
  { method: "POST", endpoint: "/gmail/v1/users/me/drafts/send", effect: "send a draft: its message becomes SENT in the same thread and the draft is removed", parameters: ["id", "message.raw", "message.threadId (same thread only)"], errors: ["400 missing id, invalid MIME or no recipient", "404 unknown draft"] },
2128
2312
  { method: "POST", endpoint: "/batch/gmail/v1", effect: "multipart batch of up to 100 body-less GET messages/<id> or threads/<id> requests", parameters: ["multipart/mixed body"], errors: ["400 malformed batch"] }
2129
2313
  ],
2130
- limitations: ["Bounded Gmail v1 subset: send, messages list/get, labels, threads list/get, sendAs list, drafts create/list/get/update/delete/send (JSON and media upload), history list, messages insert, watch/stop with loopback Pub/Sub push and read-only batch", "Sends and drafts accept folded/UTF-8 encoded headers, quoted-printable/base64 bodies and text or multipart/alternative text+html, without attachments", "Thread search supports only from:/to: address terms; no pageToken or history paging, label-change history, modify or trash; Pub/Sub push is delivered once with no retry, ack deadline or ordering guarantees, and only to loopback endpoints", "Draft records add flat threadId, to, subject, inReplyTo and references evidence fields for assertions", "Unknown fields and operations return 501 and make coverage incomplete"]
2314
+ limitations: ["Bounded Gmail v1 subset: send, messages list/get/modify/batchModify/trash/untrash/insert/attachments.get, labels list/get/create/update/delete, threads list/get/modify/trash/untrash, sendAs and forwardingAddresses list, settings.filters list/create/delete, drafts create/list/get/update/delete/send (JSON and media upload), history list, watch/stop with loopback Pub/Sub push and read-only batch", "Sends and drafts accept folded/UTF-8 encoded headers, quoted-printable/base64 bodies and text or multipart/alternative text+html, without attachments", "Search supports from:/to: address terms, rfc822msgid: and plain terms matched against the snippet and Subject/From/To headers; pageToken is a synthetic zero-based offset, and label changes appear in history as the changed message rather than separate labelsAdded/labelsRemoved records; Pub/Sub push is delivered once with no retry, ack deadline or ordering guarantees, and only to loopback endpoints", "Draft records add flat threadId, to, subject, inReplyTo and references evidence fields for assertions", "attachments.get serves attachment ids on seeded message payloads only: multipart/mixed MIME is still refused, so sent/inserted messages cannot carry attachments", "Unknown fields and operations return 501 and make coverage incomplete"]
2131
2315
  },
2132
2316
  "upstash-redis": {
2133
2317
  version: "1.0.0",
@@ -2139,6 +2323,51 @@ var CONTRACTS = {
2139
2323
  ],
2140
2324
  limitations: ["Commands run on AgentTwin's in-process Redis engine (strings, hashes, lists, sets, sorted sets, expiry), not Redis itself", "Keys are mirrored in /keys as {key, type, value, expireAt?} rows", "EVAL/EVALSHA/scripts, blocking pops, pub/sub subscriptions, MULTI/EXEC/WATCH inside a request and any engine-unknown command return 501", "Expiry uses the host clock; no replication, persistence, ACLs or read-your-writes sync tokens"]
2141
2325
  },
2326
+ posthog: {
2327
+ version: "1.0.0",
2328
+ authentication: "Bearer run-scoped test token; the project api_key travels in the body",
2329
+ operations: [
2330
+ { method: "POST", endpoint: "/capture, /e, /i/v0/e", effect: "append one event to /events and answer {status:1}", parameters: ["event", "distinct_id", "properties", "timestamp"], errors: ["400 event and distinct_id required"] },
2331
+ { method: "POST", endpoint: "/batch", effect: "append every event in batch to /events", parameters: ["batch[].event", "batch[].distinct_id", "batch[].properties"], errors: ["400 batch must be a non-empty array", "400 entry missing event/distinct_id"] },
2332
+ { method: "POST", endpoint: "/decide", effect: "feature flag values for a person, from seeded /feature_flags", parameters: ["api_key", "distinct_id", "groups"], errors: ["400 api_key required"] },
2333
+ { method: "POST", endpoint: "/flags", effect: "flag detail map in the /flags response shape", parameters: ["api_key", "distinct_id"], errors: ["400 api_key required"] }
2334
+ ],
2335
+ limitations: ["Events and flag definitions are world state; nothing is forwarded", "No person profiles, session recordings, cohorts, capture gzip decoding, export or query endpoints", "Feature flags evaluate seeded active/enabled flags only; no condition sets, variants or percentage rollout", "Unknown routes and fields return 501 and make coverage incomplete"]
2336
+ },
2337
+ tinybird: {
2338
+ version: "1.0.0",
2339
+ authentication: "Bearer run-scoped test token; an existing Tinybird token is accepted as the run token",
2340
+ operations: [
2341
+ { method: "POST", endpoint: "/v0/events?name=<datasource>", effect: "append NDJSON or JSON events; answers successful_rows and quarantined_rows", parameters: ["name", "wait", "mode=append|replace"], errors: ["400 name required", "400 invalid NDJSON/JSON"] },
2342
+ { method: "POST", endpoint: "/v0/datasources?name=<datasource>", effect: "append rows through the classic Data Sources API", parameters: ["name", "mode=append|replace", "data"], errors: ["400 name required", "400 invalid body"] },
2343
+ { method: "GET", endpoint: "/v0/pipes/<pipe>.json", effect: "query stored events, or the seeded /pipe:<name> rows, with equality filters and limit", parameters: ["datasource", "limit", "offset"], errors: ["400 invalid limit"] },
2344
+ { method: "GET", endpoint: "/v0/datasources, /v0/pipes", effect: "list datasources and pipes the twin holds", parameters: [], errors: [] }
2345
+ ],
2346
+ limitations: ["Events are kept in world collections, not a ClickHouse-backed Tinybird workspace", "No pipe SQL, transforms, copies, jobs, tokens, workspaces or materialized views; CSV/TSV bodies are refused", "Pipe queries support equality filters and limit only; no aggregations or joins", "Unknown routes and parameters return 501 and make coverage incomplete"]
2347
+ },
2348
+ lemonsqueezy: {
2349
+ version: "1.0.0",
2350
+ authentication: "Bearer run-scoped test token; JSON:API bodies",
2351
+ operations: [
2352
+ { method: "POST|GET", endpoint: "/v1/checkouts", effect: "create a checkout with a synthetic url, or list them", parameters: ["data.attributes.store_id", "data.attributes.variant_id"], errors: ["400 store_id/variant_id required", "404 not found"] },
2353
+ { method: "GET", endpoint: "/v1/checkouts/<id>", effect: "retrieve a checkout", parameters: [], errors: ["404 Not Found"] },
2354
+ { method: "POST|GET", endpoint: "/v1/subscriptions", effect: "record a subscription, or list them", parameters: ["data.attributes.store_id", "data.attributes.status"], errors: ["400 store_id required"] },
2355
+ { method: "GET|PATCH", endpoint: "/v1/subscriptions/<id>", effect: "read / update status or cancelled", parameters: ["data.attributes.status", "data.attributes.cancelled"], errors: ["404 Not Found", "400 invalid status"] }
2356
+ ],
2357
+ limitations: ["Checkouts and subscriptions only; licenses, orders, customers, stores, variants and discount endpoints are not modelled", "No webhook delivery to the application: lemonSqueezySignature() computes the X-Signature value for an envelope the test supplies", "JSON:API pagination links are synthetic; status transitions are not validated against Lemon Squeezy rules", "Unknown routes and fields return 501 and make coverage incomplete"]
2358
+ },
2359
+ qstash: {
2360
+ version: "1.0.0",
2361
+ authentication: "Bearer run-scoped test token (the QStash token header)",
2362
+ operations: [
2363
+ { method: "POST", endpoint: "/v2/publish/<destination-url>", effect: "record a message with its forwarded headers and schedule options; answers {messageId}", parameters: ["Upstash-Forward-*", "Upstash-Retries", "Upstash-Delay", "Upstash-Not-Before", "Upstash-Cron", "Upstash-Callback"], errors: ["400 destination must be http(s)"] },
2364
+ { method: "GET|DELETE", endpoint: "/v2/messages[/<id>]", effect: "list, read or cancel recorded messages", parameters: [], errors: ["404 message not found"] },
2365
+ { method: "POST", endpoint: "/v2/schedules/<destination-url>", effect: "record a schedule; answers {scheduleId}", parameters: ["Upstash-Cron", "Upstash-Not-Before"], errors: ["400 destination must be http(s)", "400 invalid cron"] },
2366
+ { method: "GET|DELETE", endpoint: "/v2/schedules[/<id>]", effect: "list, read or delete schedules", parameters: [], errors: ["404 schedule not found"] },
2367
+ { method: "GET|POST", endpoint: "/v2/signing-keys", effect: "read or rotate the current/next signing keys", parameters: [], errors: [] }
2368
+ ],
2369
+ limitations: ["Messages and schedules are recorded, not delivered to their destinations", "Signing keys are synthetic and not tied to a real QStash account; qstashSignature() computes the Upstash-Signature JWT for a receiver check", "No flow control, deduplication, callbacks invocation, DLQ or queue logs", "Unknown routes and fields return 501 and make coverage incomplete"]
2370
+ },
2142
2371
  "google-calendar": {
2143
2372
  version: "1.1.0",
2144
2373
  authentication: "Bearer run-scoped test token; Google-style OAuth2 Bearer header",
@@ -2414,7 +2643,11 @@ var RUNTIMES = /^(?:\/[\w./-]+\/)?(?:node|python[0-9.]*|uv|poetry|pipenv|go|ruby
2414
2643
  var ADAPTER_OPTIONAL_COLLECTIONS = {
2415
2644
  slack: ["/users"],
2416
2645
  stripe: ["/v1/charges", "/v1/refunds", "/v1/events", "/v1/subscription_items", "/v1/products", "/v1/prices"],
2417
- gmail: ["/gmail/v1/users/me/drafts", "/gmail/v1/users/me/settings/sendAs", "/gmail/v1/users/me/watch", "/pubsub/subscriptions", "/pubsub/messages"],
2646
+ gmail: ["/gmail/v1/users/me/drafts", "/gmail/v1/users/me/settings/sendAs", "/gmail/v1/users/me/settings/filters", "/gmail/v1/users/me/settings/forwardingAddresses", "/gmail/v1/users/me/watch", "/pubsub/subscriptions", "/pubsub/messages"],
2647
+ posthog: ["/feature_flags"],
2648
+ tinybird: ["/datasources", "/pipes"],
2649
+ lemonsqueezy: ["/v1/subscriptions", "/v1/orders", "/v1/webhooks"],
2650
+ qstash: ["/schedules", "/signing-keys"],
2418
2651
  ...ENTERPRISE_OPTIONAL_COLLECTIONS
2419
2652
  };
2420
2653
  var ADAPTER_COLLECTIONS = {
@@ -2437,6 +2670,10 @@ var ADAPTER_COLLECTIONS = {
2437
2670
  composio: ["/connected_accounts", "/tools", "/messages"],
2438
2671
  "google-oauth": ["/clients", "/grants", "/tokens"],
2439
2672
  "upstash-redis": ["/keys"],
2673
+ posthog: ["/events"],
2674
+ tinybird: ["/events"],
2675
+ lemonsqueezy: ["/v1/checkouts"],
2676
+ qstash: ["/messages"],
2440
2677
  zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"],
2441
2678
  // Enterprise twins: any subset of their optional collections; Snowflake tables are free-form.
2442
2679
  ...Object.fromEntries(ENTERPRISE_ADAPTERS.filter((a) => !FREEFORM_COLLECTION_ADAPTERS.includes(a)).map((a) => [a, []]))
@@ -2478,7 +2715,7 @@ function parseWorld(value) {
2478
2715
  if (!object(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid(`service names must be unique lowercase identifiers (${object(service) && typeof service.name === "string" ? services.has(service.name) ? `${service.name} appears twice` : `${JSON.stringify(service.name)} is not one` : "a service has no name"})`);
2479
2716
  const item = service;
2480
2717
  if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
2481
- if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "openai", "anthropic", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", "upstash-redis", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter) && !isPackAdapter(item.adapter)) invalid("unsupported service adapter");
2718
+ if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "openai", "anthropic", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", "upstash-redis", "posthog", "tinybird", "lemonsqueezy", "qstash", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter) && !isPackAdapter(item.adapter)) invalid("unsupported service adapter");
2482
2719
  const paths = /* @__PURE__ */ new Set();
2483
2720
  for (const entry of item.collections) {
2484
2721
  if (!object(entry) || typeof entry.path !== "string" || !/^\/[a-zA-Z0-9_./-]+$/.test(entry.path) || entry.path.includes("//") || /(^|\/)\.\.?(\/|$)/.test(entry.path) || paths.has(entry.path)) invalid("collection paths must be unique absolute HTTP paths");
@@ -3066,9 +3303,9 @@ require('node:module').syncBuiltinESMExports();
3066
3303
 
3067
3304
  // src/runtime/stripe-adapter.ts
3068
3305
  var stripeError = (status, code, message, param) => ({ status, body: { error: { type: "invalid_request_error", code, message, ...param ? { param } : {} } } });
3069
- function nextId(rows2, prefix, sequence) {
3306
+ function nextId(rows6, prefix, sequence) {
3070
3307
  let suffix = sequence;
3071
- while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
3308
+ while (rows6.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
3072
3309
  return `${prefix}_at_${suffix}`;
3073
3310
  }
3074
3311
  function chargeFor(intent, data, sequence) {
@@ -3127,18 +3364,18 @@ function refundOperation(method, id, params, data, sequence) {
3127
3364
  if (events) events.push({ id: nextId(events, "evt", sequence), object: "event", type: "charge.refunded", created: twinNowSeconds(17e8), livemode: false, data: { object: structuredClone(charge) } });
3128
3365
  return { status: 200, body: refund, collection, record: structuredClone(refund), operation: "write" };
3129
3366
  }
3130
- function readOnlyOperation(method, resource, id, params, data) {
3131
- const collection = `/v1/${resource}`, rows2 = data[collection];
3132
- if (!rows2 || method !== "GET") return void 0;
3367
+ function readOnlyOperation(method, resource2, id, params, data) {
3368
+ const collection = `/v1/${resource2}`, rows6 = data[collection];
3369
+ if (!rows6 || method !== "GET") return void 0;
3133
3370
  if (id) {
3134
3371
  if (Object.keys(params).length) return void 0;
3135
- const row = rows2.find((r) => r.id === id);
3136
- return row ? { status: 200, body: row, collection, operation: "read" } : { ...stripeError(404, "resource_missing", `No such ${resource.slice(0, -1)}: '${id}'`), collection };
3372
+ const row = rows6.find((r) => r.id === id);
3373
+ return row ? { status: 200, body: row, collection, operation: "read" } : { ...stripeError(404, "resource_missing", `No such ${resource2.slice(0, -1)}: '${id}'`), collection };
3137
3374
  }
3138
3375
  if (Object.keys(params).some((k) => !["limit", "type"].includes(k))) return void 0;
3139
3376
  const limit = params.limit === void 0 ? 10 : Number(params.limit);
3140
3377
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...stripeError(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
3141
- const ordered = [...rows2].reverse().filter((r) => params.type === void 0 || r.type === params.type);
3378
+ const ordered = [...rows6].reverse().filter((r) => params.type === void 0 || r.type === params.type);
3142
3379
  return { status: 200, body: { object: "list", data: ordered.slice(0, limit), has_more: ordered.length > limit, url: collection }, collection, operation: "read" };
3143
3380
  }
3144
3381
  function subscriptionItemOperation(method, id, params, data) {
@@ -3203,21 +3440,21 @@ function stripeOperation(method, path, params, data, sequence) {
3203
3440
  if (other) return other[1] === "refunds" ? refundOperation(method, other[2], params, data, sequence) : readOnlyOperation(method, other[1], other[2], params, data);
3204
3441
  const match = /^\/v1\/(customers|payment_intents)(?:\/([^/]+))?(?:\/(confirm))?$/.exec(path);
3205
3442
  if (!match || !["GET", "POST"].includes(method)) return void 0;
3206
- const [, resource, id, action] = match, collection = `/v1/${resource}`, rows2 = data[collection];
3207
- const allowed = method === "GET" ? id ? [] : ["limit", "starting_after"] : resource === "customers" && !id ? ["email", "name", "description", "phone", "metadata"] : resource === "payment_intents" && !id ? ["amount", "currency", "customer", "payment_method", "confirm", "automatic_payment_methods", "payment_method_types", "description", "metadata", "receipt_email", "return_url", "statement_descriptor", "capture_method", "off_session"] : action === "confirm" ? ["payment_method"] : void 0;
3208
- if (!allowed || resource === "customers" && action || resource === "payment_intents" && method === "GET" && !id) return void 0;
3443
+ const [, resource2, id, action] = match, collection = `/v1/${resource2}`, rows6 = data[collection];
3444
+ const allowed = method === "GET" ? id ? [] : ["limit", "starting_after"] : resource2 === "customers" && !id ? ["email", "name", "description", "phone", "metadata"] : resource2 === "payment_intents" && !id ? ["amount", "currency", "customer", "payment_method", "confirm", "automatic_payment_methods", "payment_method_types", "description", "metadata", "receipt_email", "return_url", "statement_descriptor", "capture_method", "off_session"] : action === "confirm" ? ["payment_method"] : void 0;
3445
+ if (!allowed || resource2 === "customers" && action || resource2 === "payment_intents" && method === "GET" && !id) return void 0;
3209
3446
  if (Object.keys(params).some((k) => !allowed.includes(k.replace(/\[.*$/, "")))) return void 0;
3210
3447
  if (method === "GET" && !id) {
3211
3448
  const limit = params.limit === void 0 ? 10 : Number(params.limit);
3212
3449
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...error(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
3213
- const ordered = [...rows2].reverse();
3450
+ const ordered = [...rows6].reverse();
3214
3451
  const index = params.starting_after === void 0 ? -1 : ordered.findIndex((r) => r.id === params.starting_after);
3215
3452
  if (params.starting_after !== void 0 && index === -1) return { ...error(400, "resource_missing", "No such starting_after customer", "starting_after"), collection };
3216
3453
  const page = ordered.slice(index + 1, index + 1 + limit);
3217
3454
  return { status: 200, body: { object: "list", data: page, has_more: ordered.length > index + 1 + limit, url: collection }, collection, operation: "read" };
3218
3455
  }
3219
- const row = id ? rows2.find((r) => r.id === id) : void 0;
3220
- if (id && !row) return { ...error(404, "resource_missing", `No such ${resource}: '${id}'`), collection };
3456
+ const row = id ? rows6.find((r) => r.id === id) : void 0;
3457
+ if (id && !row) return { ...error(404, "resource_missing", `No such ${resource2}: '${id}'`), collection };
3221
3458
  if (method === "GET") return { status: 200, body: row, collection, operation: "read" };
3222
3459
  if (action === "confirm") {
3223
3460
  if (row.status === "succeeded") return { status: 200, body: row, collection, operation: "replay" };
@@ -3244,11 +3481,11 @@ function stripeOperation(method, path, params, data, sequence) {
3244
3481
  }
3245
3482
  cursor[path2.at(-1)] = value;
3246
3483
  }
3247
- const prefix = resource === "customers" ? "cus" : "pi";
3484
+ const prefix = resource2 === "customers" ? "cus" : "pi";
3248
3485
  let suffix = sequence;
3249
- while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
3250
- const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: twinNowSeconds(17e8), livemode: false };
3251
- if (resource === "customers") {
3486
+ while (rows6.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
3487
+ const created2 = { id: `${prefix}_at_${suffix}`, object: resource2 === "customers" ? "customer" : "payment_intent", created: twinNowSeconds(17e8), livemode: false };
3488
+ if (resource2 === "customers") {
3252
3489
  if (params.email !== void 0 && typeof params.email !== "string") return { ...error(400, "parameter_invalid", "email must be a string", "email"), collection };
3253
3490
  Object.assign(created2, { email: null, name: null, description: null, metadata: {}, ...nested });
3254
3491
  } else {
@@ -3262,14 +3499,14 @@ function stripeOperation(method, path, params, data, sequence) {
3262
3499
  if (confirm && !params.payment_method) return { ...error(400, "parameter_missing", "Missing payment_method", "payment_method"), collection };
3263
3500
  Object.assign(created2, { amount, currency: params.currency, customer: params.customer ?? null, payment_method: params.payment_method ?? null, status: confirm && params.payment_method === "pm_card_visa" ? "succeeded" : !confirm && params.payment_method ? "requires_confirmation" : "requires_payment_method", last_payment_error: confirm && params.payment_method === "pm_card_chargeDeclined" ? { code: "card_declined", message: "Your card was declined." } : null });
3264
3501
  }
3265
- if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
3266
- if (resource === "payment_intents") {
3502
+ if (rows6.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
3503
+ if (resource2 === "payment_intents") {
3267
3504
  for (const key2 of ["description", "receipt_email", "statement_descriptor", "capture_method"]) if (nested[key2] !== void 0) created2[key2] = nested[key2];
3268
3505
  }
3269
- if (resource === "payment_intents") created2.metadata = typeof nested.metadata === "object" && nested.metadata ? nested.metadata : {};
3270
- rows2.push(created2);
3506
+ if (resource2 === "payment_intents") created2.metadata = typeof nested.metadata === "object" && nested.metadata ? nested.metadata : {};
3507
+ rows6.push(created2);
3271
3508
  if (created2.status === "succeeded") chargeFor(created2, data, sequence);
3272
- const declined = resource === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
3509
+ const declined = resource2 === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
3273
3510
  return { status: declined ? 402 : 200, body: declined ? { error: { type: "card_error", code: "card_declined", decline_code: "generic_decline", message: "Your card was declined.", payment_intent: structuredClone(created2) } } : created2, collection, record: structuredClone(created2), operation: "write" };
3274
3511
  }
3275
3512
 
@@ -3508,8 +3745,8 @@ var composioOperation = (method, path, params, _headers, data, sequence) => {
3508
3745
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) return;
3509
3746
  if (params.cursor !== void 0 && (typeof params.cursor !== "string" || !/^at_\d{1,4}$/.test(params.cursor))) return;
3510
3747
  const start = params.cursor ? Number(String(params.cursor).slice(3)) : 0;
3511
- const rows2 = accounts.filter((row) => row.status !== "DELETED" && (!users || users.includes(String(row.user_id))) && (!statuses || statuses.includes(String(row.status))) && (!toolkits || object2(row.toolkit) && toolkits.includes(String(row.toolkit.slug))));
3512
- return { status: 200, collection: "/connected_accounts", operation: "read", body: { items: structuredClone(rows2.slice(start, start + limit)), next_cursor: start + limit < rows2.length ? "at_" + (start + limit) : null, total_pages: Math.ceil(rows2.length / limit), current_page: Math.floor(start / limit) + 1, total_items: rows2.length } };
3748
+ const rows6 = accounts.filter((row) => row.status !== "DELETED" && (!users || users.includes(String(row.user_id))) && (!statuses || statuses.includes(String(row.status))) && (!toolkits || object2(row.toolkit) && toolkits.includes(String(row.toolkit.slug))));
3749
+ return { status: 200, collection: "/connected_accounts", operation: "read", body: { items: structuredClone(rows6.slice(start, start + limit)), next_cursor: start + limit < rows6.length ? "at_" + (start + limit) : null, total_pages: Math.ceil(rows6.length / limit), current_page: Math.floor(start / limit) + 1, total_items: rows6.length } };
3513
3750
  }
3514
3751
  const account = /^connected_accounts\/([A-Za-z0-9_-]+)$/.exec(suffix);
3515
3752
  if (method === "DELETE" && account) {
@@ -4011,7 +4248,7 @@ var InProcessRedis = class {
4011
4248
  return Number(s);
4012
4249
  }
4013
4250
  command(name, a) {
4014
- const now = Date.now(), ok2 = encode.simple("OK"), key2 = a[0];
4251
+ const now5 = Date.now(), ok2 = encode.simple("OK"), key2 = a[0];
4015
4252
  const str2 = (k) => this.get(k, "string");
4016
4253
  const bulks = (list2) => encode.array(list2.map((v) => encode.bulk(v ?? null)));
4017
4254
  const setString = (k, v, expireAt) => this.data.set(k, { type: "string", value: v, ...expireAt !== void 0 ? { expireAt } : {} });
@@ -4055,7 +4292,7 @@ var InProcessRedis = class {
4055
4292
  case "config":
4056
4293
  return (a[0] ?? "").toLowerCase() === "get" ? encode.array([]) : ok2;
4057
4294
  case "time":
4058
- return bulks([String(Math.floor(now / 1e3)), String(now % 1e3 * 1e3)]);
4295
+ return bulks([String(Math.floor(now5 / 1e3)), String(now5 % 1e3 * 1e3)]);
4059
4296
  case "dbsize":
4060
4297
  return encode.int([...this.data.keys()].filter((k) => this.live(k)).length);
4061
4298
  case "flushdb":
@@ -4072,8 +4309,8 @@ var InProcessRedis = class {
4072
4309
  else if (o === "xx") xx = true;
4073
4310
  else if (o === "get") get = true;
4074
4311
  else if (o === "keepttl") keep = true;
4075
- else if (o === "ex") expireAt = now + this.int(a[++i]) * 1e3;
4076
- else if (o === "px") expireAt = now + this.int(a[++i]);
4312
+ else if (o === "ex") expireAt = now5 + this.int(a[++i]) * 1e3;
4313
+ else if (o === "px") expireAt = now5 + this.int(a[++i]);
4077
4314
  else if (o === "exat") expireAt = this.int(a[++i]) * 1e3;
4078
4315
  else if (o === "pxat") expireAt = this.int(a[++i]);
4079
4316
  else return encode.error("ERR syntax error");
@@ -4090,10 +4327,10 @@ var InProcessRedis = class {
4090
4327
  setString(key2, a[1]);
4091
4328
  return encode.int(1);
4092
4329
  case "setex":
4093
- setString(key2, a[2], now + this.int(a[1]) * 1e3);
4330
+ setString(key2, a[2], now5 + this.int(a[1]) * 1e3);
4094
4331
  return ok2;
4095
4332
  case "psetex":
4096
- setString(key2, a[2], now + this.int(a[1]));
4333
+ setString(key2, a[2], now5 + this.int(a[1]));
4097
4334
  return ok2;
4098
4335
  case "getset": {
4099
4336
  const old = str2(key2);
@@ -4158,8 +4395,8 @@ var InProcessRedis = class {
4158
4395
  const e = this.live(key2);
4159
4396
  if (!e) return encode.int(0);
4160
4397
  const n = this.int(a[1]);
4161
- e.expireAt = name === "expire" ? now + n * 1e3 : name === "pexpire" ? now + n : name === "expireat" ? n * 1e3 : n;
4162
- if (e.expireAt <= now) this.data.delete(key2);
4398
+ e.expireAt = name === "expire" ? now5 + n * 1e3 : name === "pexpire" ? now5 + n : name === "expireat" ? n * 1e3 : n;
4399
+ if (e.expireAt <= now5) this.data.delete(key2);
4163
4400
  return encode.int(1);
4164
4401
  }
4165
4402
  case "ttl":
@@ -4167,7 +4404,7 @@ var InProcessRedis = class {
4167
4404
  const e = this.live(key2);
4168
4405
  if (!e) return encode.int(-2);
4169
4406
  if (e.expireAt === void 0) return encode.int(-1);
4170
- const ms = e.expireAt - now;
4407
+ const ms = e.expireAt - now5;
4171
4408
  return encode.int(name === "ttl" ? Math.round(ms / 1e3) : ms);
4172
4409
  }
4173
4410
  case "persist": {
@@ -4444,62 +4681,62 @@ function toRow(key2, entry) {
4444
4681
  }
4445
4682
  var caches = /* @__PURE__ */ new WeakMap();
4446
4683
  var GLOBAL_WRITES = /* @__PURE__ */ new Set(["flushdb", "flushall"]);
4447
- var consistent = (rows2, cache2) => rows2.length === cache2.mirror.length && rows2.every((r, i) => r === cache2.mirror[i]);
4448
- function resync(rows2, cache2) {
4449
- const now = Date.now();
4450
- for (const [k, e] of cache2.engine.data) if (e.expireAt !== void 0 && e.expireAt <= now) cache2.engine.data.delete(k);
4451
- rows2.splice(0, rows2.length, ...[...cache2.engine.data].map(([k, e]) => toRow(k, e)));
4452
- cache2.mirror = rows2.slice();
4684
+ var consistent = (rows6, cache2) => rows6.length === cache2.mirror.length && rows6.every((r, i) => r === cache2.mirror[i]);
4685
+ function resync(rows6, cache2) {
4686
+ const now5 = Date.now();
4687
+ for (const [k, e] of cache2.engine.data) if (e.expireAt !== void 0 && e.expireAt <= now5) cache2.engine.data.delete(k);
4688
+ rows6.splice(0, rows6.length, ...[...cache2.engine.data].map(([k, e]) => toRow(k, e)));
4689
+ cache2.mirror = rows6.slice();
4453
4690
  cache2.index = new Map([...cache2.engine.data.keys()].map((k, i) => [k, i]));
4454
- cache2.nextExpiry = rows2.reduce((min, r) => r.expireAt !== void 0 && r.expireAt < min ? r.expireAt : min, Infinity);
4691
+ cache2.nextExpiry = rows6.reduce((min, r) => r.expireAt !== void 0 && r.expireAt < min ? r.expireAt : min, Infinity);
4455
4692
  }
4456
- function remove(rows2, cache2, key2) {
4693
+ function remove(rows6, cache2, key2) {
4457
4694
  const at = cache2.index.get(key2);
4458
4695
  if (at === void 0) return;
4459
4696
  cache2.index.delete(key2);
4460
- const last = rows2.length - 1;
4697
+ const last = rows6.length - 1;
4461
4698
  if (at !== last) {
4462
- rows2[at] = rows2[last];
4463
- cache2.mirror[at] = rows2[last];
4464
- cache2.index.set(toBytes(rows2[at].key), at);
4699
+ rows6[at] = rows6[last];
4700
+ cache2.mirror[at] = rows6[last];
4701
+ cache2.index.set(toBytes(rows6[at].key), at);
4465
4702
  }
4466
- rows2.pop();
4703
+ rows6.pop();
4467
4704
  cache2.mirror.pop();
4468
4705
  }
4469
- function syncKey(rows2, cache2, key2, now) {
4706
+ function syncKey(rows6, cache2, key2, now5) {
4470
4707
  const entry = cache2.engine.data.get(key2);
4471
- if (!entry || entry.expireAt !== void 0 && entry.expireAt <= now) {
4708
+ if (!entry || entry.expireAt !== void 0 && entry.expireAt <= now5) {
4472
4709
  if (entry) cache2.engine.data.delete(key2);
4473
- remove(rows2, cache2, key2);
4710
+ remove(rows6, cache2, key2);
4474
4711
  return;
4475
4712
  }
4476
4713
  const row = toRow(key2, entry);
4477
4714
  const at = cache2.index.get(key2);
4478
4715
  if (at === void 0) {
4479
- cache2.index.set(key2, rows2.length);
4480
- rows2.push(row);
4716
+ cache2.index.set(key2, rows6.length);
4717
+ rows6.push(row);
4481
4718
  cache2.mirror.push(row);
4482
4719
  } else {
4483
- rows2[at] = row;
4720
+ rows6[at] = row;
4484
4721
  cache2.mirror[at] = row;
4485
4722
  }
4486
4723
  if (row.expireAt !== void 0) cache2.nextExpiry = Math.min(cache2.nextExpiry, row.expireAt);
4487
4724
  }
4488
- function engineFor(rows2) {
4489
- const cached2 = caches.get(rows2);
4490
- if (cached2 && consistent(rows2, cached2)) return cached2;
4725
+ function engineFor(rows6) {
4726
+ const cached2 = caches.get(rows6);
4727
+ if (cached2 && consistent(rows6, cached2)) return cached2;
4491
4728
  const engine = new InProcessRedis();
4492
- for (const row of rows2) {
4729
+ for (const row of rows6) {
4493
4730
  const entry = row && typeof row.key === "string" ? toEntry(row) : void 0;
4494
4731
  if (!entry) {
4495
- caches.delete(rows2);
4732
+ caches.delete(rows6);
4496
4733
  return { error: `ERR invalid seeded key row ${JSON.stringify(row?.key)}` };
4497
4734
  }
4498
4735
  engine.data.set(toBytes(row.key), entry);
4499
4736
  }
4500
4737
  const cache2 = { engine, mirror: [], index: /* @__PURE__ */ new Map(), nextExpiry: Infinity };
4501
- resync(rows2, cache2);
4502
- caches.set(rows2, cache2);
4738
+ resync(rows6, cache2);
4739
+ caches.set(rows6, cache2);
4503
4740
  return cache2;
4504
4741
  }
4505
4742
  function upstashReply(reply, base64) {
@@ -4529,17 +4766,17 @@ function upstashRedisOperation(method, path, params, headers, data, _sequence, r
4529
4766
  if (!Array.isArray(commands) || !commands.length || commands.length > 1e3 || !commands.every(valid)) return { status: 400, body: { error: "ERR command must be a non-empty array of strings" }, collection: UPSTASH_KEYS };
4530
4767
  const args = commands.map((c) => c.map((a) => toBytes(String(a))));
4531
4768
  if (args.some((c) => REJECTED.has(c[0].toLowerCase()))) return void 0;
4532
- const rows2 = data[UPSTASH_KEYS];
4533
- const cache2 = engineFor(rows2);
4769
+ const rows6 = data[UPSTASH_KEYS];
4770
+ const cache2 = engineFor(rows6);
4534
4771
  if ("error" in cache2) return { status: 500, body: { error: cache2.error }, collection: UPSTASH_KEYS };
4535
4772
  const { engine } = cache2;
4536
4773
  engine.unsupported.length = 0;
4537
4774
  const replies = args.map((c) => engine.run(c));
4538
4775
  if (engine.unsupported.length) {
4539
- caches.delete(rows2);
4776
+ caches.delete(rows6);
4540
4777
  return void 0;
4541
4778
  }
4542
- const now = Date.now();
4779
+ const now5 = Date.now();
4543
4780
  const touched = /* @__PURE__ */ new Set();
4544
4781
  let full = false;
4545
4782
  for (const c of args) {
@@ -4547,8 +4784,8 @@ function upstashRedisOperation(method, path, params, headers, data, _sequence, r
4547
4784
  if (GLOBAL_WRITES.has(name) || !keys.length && (WRITE_COMMANDS.has(name) || /^eval/.test(name))) full = true;
4548
4785
  for (const k of keys) touched.add(k);
4549
4786
  }
4550
- if (full || cache2.nextExpiry <= now) resync(rows2, cache2);
4551
- else for (const k of touched) syncKey(rows2, cache2, k, now);
4787
+ if (full || cache2.nextExpiry <= now5) resync(rows6, cache2);
4788
+ else for (const k of touched) syncKey(rows6, cache2, k, now5);
4552
4789
  const encoding = headers["upstash-encoding"];
4553
4790
  const base64 = typeof encoding === "string" && encoding.toLowerCase() === "base64";
4554
4791
  const results = replies.map((r) => upstashReply(r, base64));
@@ -4561,6 +4798,324 @@ function upstashRedisOperation(method, path, params, headers, data, _sequence, r
4561
4798
  return { status: 200, body: results, collection: UPSTASH_KEYS, operation: wrote ? "write" : "read", record: record3 };
4562
4799
  }
4563
4800
 
4801
+ // src/runtime/posthog-twin.ts
4802
+ var EVENTS = "/events";
4803
+ var FLAGS = "/feature_flags";
4804
+ var rows = (data, path) => data[path] ??= [];
4805
+ var now = () => new Date(twinNowMs(17e11)).toISOString();
4806
+ var eventRows = (data) => rows(data, EVENTS);
4807
+ var flagRows = (data) => rows(data, FLAGS);
4808
+ var eventName = (value) => typeof value === "string" && value.trim() ? value : void 0;
4809
+ var distinctId = (event) => {
4810
+ const direct = event.distinct_id ?? event.distinctId;
4811
+ const properties = event.properties;
4812
+ const nested = properties && typeof properties === "object" && !Array.isArray(properties) ? properties.distinct_id : void 0;
4813
+ return typeof direct === "string" && direct ? direct : typeof nested === "string" && nested ? nested : void 0;
4814
+ };
4815
+ var validProperties = (value) => value === void 0 || !!value && typeof value === "object" && !Array.isArray(value);
4816
+ var append = (data, event, sequence) => {
4817
+ const name = eventName(event.event), id = distinctId(event);
4818
+ if (!name || !id) return void 0;
4819
+ if (!validProperties(event.properties)) return void 0;
4820
+ const record3 = {
4821
+ uuid: `ph_${sequence}_${eventRows(data).length}`,
4822
+ event: name,
4823
+ distinct_id: id,
4824
+ properties: event.properties ?? {},
4825
+ timestamp: typeof event.timestamp === "string" ? event.timestamp : now(),
4826
+ sentAt: now(),
4827
+ sequence
4828
+ };
4829
+ eventRows(data).push(record3);
4830
+ return record3;
4831
+ };
4832
+ var flagsFor = (data) => Object.fromEntries(flagRows(data).map((flag) => {
4833
+ const key2 = String(flag.key ?? flag.name ?? "");
4834
+ return [key2, flag.active === true || flag.enabled === true];
4835
+ }).filter(([key2]) => key2));
4836
+ var flagPayloads = (data) => Object.fromEntries(flagRows(data).filter((flag) => flag.payload !== void 0).map((flag) => [String(flag.key ?? flag.name ?? ""), flag.payload]));
4837
+ var posthogOperation = (method, path, params, _headers, data, sequence) => {
4838
+ const route = path.replace(/\/+$/, "") || "/";
4839
+ const respond = (status, body, record3, operation = "read") => ({ status, body, collection: EVENTS, ...record3 ? { record: structuredClone(record3), operation } : { operation } });
4840
+ if (method === "POST" && (route === "/capture" || route === "/e" || route === "/i/v0/e")) {
4841
+ const record3 = append(data, params, sequence);
4842
+ if (!record3) return { status: 400, body: { status: 0, error: "event and distinct_id are required" }, collection: EVENTS };
4843
+ return respond(200, { status: 1 }, record3, "write");
4844
+ }
4845
+ if (method === "POST" && route === "/batch") {
4846
+ const batch = Array.isArray(params.batch) ? params.batch : void 0;
4847
+ if (!batch || !batch.length) return { status: 400, body: { status: 0, error: "batch must be a non-empty array" }, collection: EVENTS };
4848
+ const records = [];
4849
+ for (const item of batch) {
4850
+ if (!item || typeof item !== "object" || Array.isArray(item)) return { status: 400, body: { status: 0, error: "batch entries must be objects" }, collection: EVENTS };
4851
+ const record3 = append(data, item, sequence + records.length);
4852
+ if (!record3) return { status: 400, body: { status: 0, error: "every batch entry needs event and distinct_id" }, collection: EVENTS };
4853
+ records.push(record3);
4854
+ }
4855
+ return { status: 200, body: { status: 1 }, collection: EVENTS, operation: "write", record: { events: records.map((r) => r.event), count: records.length } };
4856
+ }
4857
+ if (method === "POST" && (route === "/decide" || route === "/flags")) {
4858
+ const key2 = typeof params.api_key === "string" ? params.api_key : typeof params.token === "string" ? params.token : void 0;
4859
+ if (!key2) return { status: 400, body: { error: "api_key is required" }, collection: FLAGS };
4860
+ const flags = flagsFor(data), payloads = flagPayloads(data);
4861
+ if (route === "/decide") {
4862
+ return respond(200, { config: { enable_collect_everything: true }, toolbarParams: {}, isAuthenticated: false, supportedCompression: ["gzip", "gzip-js"], featureFlags: flags, featureFlagPayloads: payloads, errorsWhileComputingFlags: false, sessionRecording: false, autocapture_opt_out: true, capturePerformance: false, editorParams: {}, quotas: {} });
4863
+ }
4864
+ return respond(200, { flags: Object.fromEntries(Object.entries(flags).map(([flag, enabled]) => [flag, { key: flag, enabled, variant: null, reason: { code: enabled ? "condition_match" : "no_condition_match", description: enabled ? "Matched condition set 1" : "No matching condition set", condition_index: enabled ? 0 : void 0 }, metadata: { id: 1, version: 1, payload: payloads[flag] ?? null, description: null } }])), errorsWhileComputingFlags: false, config: { enable_collect_everything: true } });
4865
+ }
4866
+ if (method === "GET" && route === "/") return respond(200, { status: "ok" });
4867
+ return void 0;
4868
+ };
4869
+
4870
+ // src/runtime/tinybird-twin.ts
4871
+ var EVENTS2 = "/events";
4872
+ var rows2 = (data, path) => data[path] ??= [];
4873
+ var now2 = () => new Date(twinNowMs(17e11)).toISOString();
4874
+ var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4875
+ function parseBody(raw, params) {
4876
+ if (raw !== void 0 && raw.trim()) {
4877
+ const text2 = raw.trim();
4878
+ try {
4879
+ if (text2.startsWith("[")) {
4880
+ const parsed = JSON.parse(text2);
4881
+ return Array.isArray(parsed) ? parsed.filter(isObject2) : "the body must be a JSON object or array";
4882
+ }
4883
+ if (text2.startsWith("{")) return text2.includes("\n") ? text2.split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line)) : [JSON.parse(text2)];
4884
+ return "CSV and TSV bodies are outside the Tinybird twin subset; send NDJSON or JSON";
4885
+ } catch {
4886
+ return "the body is not valid NDJSON or JSON";
4887
+ }
4888
+ }
4889
+ if (Array.isArray(params.data)) return params.data.filter(isObject2);
4890
+ if (isObject2(params.data)) return [params.data];
4891
+ return "the request has no rows";
4892
+ }
4893
+ var fieldType = (value) => typeof value === "number" ? "Float64" : typeof value === "boolean" ? "Bool" : "String";
4894
+ var tinybirdOperation = (method, path, params, _headers, data, sequence, raw) => {
4895
+ const EVENTS_API = "/v0/events", DATASOURCES = "/v0/datasources";
4896
+ if (method === "POST" && (path === EVENTS_API || path === DATASOURCES)) {
4897
+ const datasource = typeof params.name === "string" && params.name ? params.name : void 0;
4898
+ if (!datasource) return { status: 400, body: { error: "You need to provide a value for 'name'", documentation: "https://www.tinybird.co/docs/api-reference" }, collection: EVENTS2 };
4899
+ const parsed = parseBody(raw, params);
4900
+ if (typeof parsed === "string") return { status: 400, body: { error: parsed }, collection: EVENTS2 };
4901
+ if (params.mode !== void 0 && params.mode !== "append" && params.mode !== "replace") return void 0;
4902
+ const target = rows2(data, EVENTS2);
4903
+ if (params.mode === "replace") target.splice(0, Infinity, ...target.filter((row) => row.datasource !== datasource));
4904
+ for (const row of parsed) target.push({ ...structuredClone(row), datasource, timestamp: typeof row.timestamp === "string" ? row.timestamp : now2(), _file: `${datasource}-${sequence}` });
4905
+ return { status: 202, body: { successful_rows: parsed.length, quarantined_rows: 0 }, collection: EVENTS2, operation: "write", record: { datasource, rows: parsed.length } };
4906
+ }
4907
+ if (method === "GET" && path === DATASOURCES) {
4908
+ const seeded = rows2(data, "/datasources");
4909
+ const names = new Set([...seeded.map((row) => String(row.name)), ...rows2(data, EVENTS2).map((row) => String(row.datasource))].filter(Boolean));
4910
+ return { status: 200, body: { datasources: [...names].map((name) => seeded.find((row) => row.name === name) ?? { name, type: "datasource" }) }, collection: DATASOURCES };
4911
+ }
4912
+ if (method === "GET" && path === "/v0/pipes") {
4913
+ const seeded = rows2(data, "/pipes");
4914
+ return { status: 200, body: { pipes: seeded.length ? seeded : [...new Set(rows2(data, EVENTS2).map((row) => String(row.datasource)))].filter(Boolean).map((name) => ({ name, type: "endpoint" })) }, collection: "/pipes" };
4915
+ }
4916
+ const pipe = /^\/v0\/pipes\/([^/]+?)(?:\.json)?$/.exec(path);
4917
+ if (pipe && method === "GET") {
4918
+ const name = decodeURIComponent(pipe[1]);
4919
+ const seeded = rows2(data, `/pipe:${name}`);
4920
+ const all = rows2(data, EVENTS2);
4921
+ const controls = /* @__PURE__ */ new Set(["format", "limit", "offset", "page", "token", "sql", "q"]);
4922
+ let result = seeded.length ? seeded.map((row) => structuredClone(row)) : all.filter((row) => (params.datasource === void 0 || row.datasource === params.datasource) && Object.entries(params).every(([key2, value]) => controls.has(key2) || String(row[key2] ?? "") === String(value))).map((row) => structuredClone(row));
4923
+ if (params.limit !== void 0) {
4924
+ const limit = Number(params.limit);
4925
+ if (!Number.isInteger(limit) || limit < 0) return { status: 400, body: { error: "limit must be a non-negative integer" }, collection: EVENTS2 };
4926
+ result = result.slice(0, limit);
4927
+ }
4928
+ const sample = result[0] ?? {};
4929
+ return { status: 200, body: { meta: Object.keys(sample).map((field) => ({ name: field, type: fieldType(sample[field]) })), data: result, rows: result.length, statistics: { elapsed: 1e-3, rows_read: result.length, bytes_read: JSON.stringify(result).length } }, collection: EVENTS2 };
4930
+ }
4931
+ return void 0;
4932
+ };
4933
+
4934
+ // src/runtime/lemonsqueezy-twin.ts
4935
+ import { createHmac } from "crypto";
4936
+ var CHECKOUTS = "/v1/checkouts";
4937
+ var SUBSCRIPTIONS = "/v1/subscriptions";
4938
+ var rows3 = (data, path) => data[path] ??= [];
4939
+ var now3 = () => new Date(twinNowMs(17e11)).toISOString();
4940
+ var isObject3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4941
+ var SUBSCRIPTION_STATUSES = ["on_trial", "active", "paused", "past_due", "unpaid", "cancelled", "expired"];
4942
+ var jsonApiError = (status, collection, title, detail) => ({
4943
+ status,
4944
+ collection,
4945
+ body: { errors: [{ status: String(status), title, detail }] }
4946
+ });
4947
+ var resource = (type, id, attributes) => ({
4948
+ type,
4949
+ id,
4950
+ attributes,
4951
+ links: { self: `https://api.lemonsqueezy.com/v1/${type}/${id}` }
4952
+ });
4953
+ var lemonsqueezyOperation = (method, path, params, _headers, data, sequence) => {
4954
+ const checkout = /^\/v1\/checkouts(?:\/([^/]+))?$/.exec(path);
4955
+ if (checkout) {
4956
+ const id = checkout[1] && decodeURIComponent(checkout[1]);
4957
+ if (method === "GET" && !id) {
4958
+ const all = rows3(data, CHECKOUTS);
4959
+ const page = typeof params["page[number]"] === "string" ? Math.max(1, Number(params["page[number]"]) || 1) : 1;
4960
+ const size = typeof params["page[size]"] === "string" ? Math.min(100, Math.max(1, Number(params["page[size]"]) || 10)) : 10;
4961
+ const selected = all.slice((page - 1) * size, page * size);
4962
+ return { status: 200, body: { meta: { page: { currentPage: page, perPage: size, lastPage: Math.max(1, Math.ceil(all.length / size)), total: all.length } }, data: selected.map((row) => resource("checkouts", String(row.id), row.attributes)) }, collection: CHECKOUTS };
4963
+ }
4964
+ if (method === "GET") {
4965
+ const found = rows3(data, CHECKOUTS).find((row) => row.id === id);
4966
+ return found ? { status: 200, body: { data: resource("checkouts", String(id), found.attributes) }, collection: CHECKOUTS } : jsonApiError(404, CHECKOUTS, "Not Found", `The requested checkout ${id} could not be found.`);
4967
+ }
4968
+ if (method !== "POST") return void 0;
4969
+ const input = params.data;
4970
+ if (!isObject3(input) || input.type !== "checkouts" || !isObject3(input.attributes)) return jsonApiError(400, CHECKOUTS, "Bad Request", "data.type must be checkouts with an attributes object.");
4971
+ const attributes = input.attributes;
4972
+ if (Object.keys(attributes).some((key2) => !["store_id", "variant_id", "custom_price", "product_options", "checkout_options", "checkout_data", "expires_at", "preview"].includes(key2))) return void 0;
4973
+ if (typeof attributes.store_id !== "number" || typeof attributes.variant_id !== "number") return jsonApiError(400, CHECKOUTS, "Unprocessable Entity", "store_id and variant_id are required integers.");
4974
+ const newId2 = String(rows3(data, CHECKOUTS).length + 1);
4975
+ const record3 = { id: newId2, attributes: { ...structuredClone(attributes), status: "pending", url: `https://agenttwin.lemonsqueezy.com/checkout/buy/${newId2}`, created_at: now3(), updated_at: now3(), test_mode: true } };
4976
+ rows3(data, CHECKOUTS).push(record3);
4977
+ return { status: 201, body: { data: resource("checkouts", newId2, record3.attributes), links: { self: `https://api.lemonsqueezy.com/v1/checkouts/${newId2}` } }, collection: CHECKOUTS, operation: "write", record: record3 };
4978
+ }
4979
+ const subscription = /^\/v1\/subscriptions(?:\/([^/]+))?$/.exec(path);
4980
+ if (subscription) {
4981
+ const id = subscription[1] && decodeURIComponent(subscription[1]);
4982
+ if (method === "GET" && !id) {
4983
+ const all = rows3(data, SUBSCRIPTIONS);
4984
+ return { status: 200, body: { data: all.map((row) => resource("subscriptions", String(row.id), row.attributes)) }, collection: SUBSCRIPTIONS };
4985
+ }
4986
+ if (method === "GET") {
4987
+ const found = rows3(data, SUBSCRIPTIONS).find((row) => row.id === id);
4988
+ return found ? { status: 200, body: { data: resource("subscriptions", String(id), found.attributes) }, collection: SUBSCRIPTIONS } : jsonApiError(404, SUBSCRIPTIONS, "Not Found", `The requested subscription ${id} could not be found.`);
4989
+ }
4990
+ if (method === "POST") {
4991
+ const input = params.data;
4992
+ if (!isObject3(input) || input.type !== "subscriptions" || !isObject3(input.attributes)) return jsonApiError(400, SUBSCRIPTIONS, "Unprocessable Entity", "data.type must be subscriptions with an attributes object.");
4993
+ const attributes = input.attributes;
4994
+ if (typeof attributes.store_id !== "number") return jsonApiError(400, SUBSCRIPTIONS, "Unprocessable Entity", "data.attributes.store_id is required.");
4995
+ const newId2 = String(rows3(data, SUBSCRIPTIONS).length + 1);
4996
+ const status = typeof attributes.status === "string" && SUBSCRIPTION_STATUSES.includes(attributes.status) ? attributes.status : "active";
4997
+ const record3 = { id: newId2, attributes: { ...structuredClone(attributes), status, cancelled: status === "cancelled", created_at: now3(), updated_at: now3(), renews_at: now3(), test_mode: true } };
4998
+ rows3(data, SUBSCRIPTIONS).push(record3);
4999
+ return { status: 201, body: { data: resource("subscriptions", newId2, record3.attributes) }, collection: SUBSCRIPTIONS, operation: "write", record: record3 };
5000
+ }
5001
+ if (method === "PATCH") {
5002
+ const index = rows3(data, SUBSCRIPTIONS).findIndex((row) => row.id === id);
5003
+ if (index < 0) return jsonApiError(404, SUBSCRIPTIONS, "Not Found", `The requested subscription ${id} could not be found.`);
5004
+ const input = params.data;
5005
+ if (!isObject3(input) || !isObject3(input.attributes)) return void 0;
5006
+ const changes = input.attributes;
5007
+ if (Object.keys(changes).some((key2) => !["status", "cancelled", "pause"].includes(key2))) return void 0;
5008
+ const attributes = rows3(data, SUBSCRIPTIONS)[index].attributes;
5009
+ if (changes.status !== void 0 && (typeof changes.status !== "string" || !SUBSCRIPTION_STATUSES.includes(changes.status))) return jsonApiError(400, SUBSCRIPTIONS, "Unprocessable Entity", `status must be one of ${SUBSCRIPTION_STATUSES.join(", ")}.`);
5010
+ if (changes.status !== void 0) attributes.status = changes.status;
5011
+ if (changes.cancelled !== void 0) attributes.cancelled = changes.cancelled === true;
5012
+ if (attributes.status === "cancelled") attributes.cancelled = true;
5013
+ attributes.updated_at = now3();
5014
+ return { status: 200, body: { data: resource("subscriptions", String(id), attributes) }, collection: SUBSCRIPTIONS, operation: "write", record: rows3(data, SUBSCRIPTIONS)[index] };
5015
+ }
5016
+ return void 0;
5017
+ }
5018
+ return void 0;
5019
+ };
5020
+
5021
+ // src/runtime/qstash-twin.ts
5022
+ import { createHmac as createHmac2 } from "crypto";
5023
+ var MESSAGES = "/messages";
5024
+ var SCHEDULES = "/schedules";
5025
+ var SIGNING = "/signing-keys";
5026
+ var rows4 = (data, path) => data[path] ??= [];
5027
+ var now4 = () => new Date(twinNowMs(17e11)).toISOString();
5028
+ var header3 = (headers, name) => {
5029
+ const value = headers[name];
5030
+ return Array.isArray(value) ? value[0] : value;
5031
+ };
5032
+ var forwarded = (headers) => Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase().startsWith("upstash-forward-")).map(([name, value]) => [name.slice("upstash-forward-".length), Array.isArray(value) ? value[0] : value]));
5033
+ var numberHeader = (value) => value !== void 0 && /^\d{1,9}$/.test(value) ? Number(value) : void 0;
5034
+ var base64url = (value) => Buffer.from(value).toString("base64url");
5035
+ var signingKeys = (data) => {
5036
+ const keys = rows4(data, SIGNING);
5037
+ if (!keys.length) keys.push({ id: "current", current: "sig_current_agenttwin", next: "sig_next_agenttwin" });
5038
+ return keys[0];
5039
+ };
5040
+ var qstashOperation = (method, path, params, headers, data, sequence, raw) => {
5041
+ const publish = /^\/v2\/publish\/(.+)$/.exec(path);
5042
+ if (publish) {
5043
+ if (method !== "POST") return void 0;
5044
+ const destination = decodeURIComponent(publish[1]);
5045
+ if (!/^https?:\/\//.test(destination)) return { status: 400, body: { error: "destination must be an http(s) URL" }, collection: MESSAGES };
5046
+ const record3 = {
5047
+ messageId: `msg_${sequence}_${rows4(data, MESSAGES).length}`,
5048
+ destination,
5049
+ body: raw && raw.trim() ? raw : params,
5050
+ headers: forwarded(headers),
5051
+ method: header3(headers, "upstash-method") ?? "POST",
5052
+ retries: numberHeader(header3(headers, "upstash-retries")) ?? 3,
5053
+ delay: numberHeader(header3(headers, "upstash-delay")),
5054
+ notBefore: header3(headers, "upstash-not-before"),
5055
+ cron: header3(headers, "upstash-cron"),
5056
+ callback: header3(headers, "upstash-callback"),
5057
+ failureCallback: header3(headers, "upstash-failure-callback"),
5058
+ createdAt: now4(),
5059
+ status: "pending"
5060
+ };
5061
+ rows4(data, MESSAGES).push(record3);
5062
+ return { status: 200, body: { messageId: record3.messageId }, collection: MESSAGES, operation: "write", record: record3 };
5063
+ }
5064
+ const schedule = /^\/v2\/schedules\/(.+)$/.exec(path);
5065
+ if (schedule && method === "POST") {
5066
+ const destination = decodeURIComponent(schedule[1]);
5067
+ if (!/^https?:\/\//.test(destination)) return { status: 400, body: { error: "destination must be an http(s) URL" }, collection: SCHEDULES };
5068
+ const cron = header3(headers, "upstash-cron");
5069
+ if (cron !== void 0 && !/^\S+(\s+\S+){4,5}$/.test(cron)) return { status: 400, body: { error: "Upstash-Cron must be a cron expression" }, collection: SCHEDULES };
5070
+ const record3 = {
5071
+ scheduleId: `sched_${sequence}_${rows4(data, SCHEDULES).length}`,
5072
+ destination,
5073
+ cron: cron ?? null,
5074
+ notBefore: header3(headers, "upstash-not-before") ?? null,
5075
+ body: raw && raw.trim() ? raw : params,
5076
+ headers: forwarded(headers),
5077
+ createdAt: now4(),
5078
+ status: "active"
5079
+ };
5080
+ rows4(data, SCHEDULES).push(record3);
5081
+ return { status: 200, body: { scheduleId: record3.scheduleId }, collection: SCHEDULES, operation: "write", record: record3 };
5082
+ }
5083
+ if (path === "/v2/schedules" && method === "GET") return { status: 200, body: { schedules: rows4(data, SCHEDULES).map((row) => structuredClone(row)) }, collection: SCHEDULES };
5084
+ const scheduleId = /^\/v2\/schedules\/([^/]+)$/.exec(path);
5085
+ if (scheduleId) {
5086
+ const id = decodeURIComponent(scheduleId[1]), list2 = rows4(data, SCHEDULES), index = list2.findIndex((row) => row.scheduleId === id);
5087
+ if (index < 0) return { status: 404, body: { error: "schedule not found" }, collection: SCHEDULES };
5088
+ if (method === "GET") return { status: 200, body: structuredClone(list2[index]), collection: SCHEDULES };
5089
+ if (method === "DELETE") {
5090
+ const [removed] = list2.splice(index, 1);
5091
+ return { status: 200, body: { deleted: removed.scheduleId }, collection: SCHEDULES, operation: "write", record: { deleted: removed.scheduleId } };
5092
+ }
5093
+ return void 0;
5094
+ }
5095
+ if (path === "/v2/messages" && method === "GET") return { status: 200, body: { messages: rows4(data, MESSAGES).map((row) => structuredClone(row)) }, collection: MESSAGES };
5096
+ const messageId = /^\/v2\/messages\/([^/]+)$/.exec(path);
5097
+ if (messageId) {
5098
+ const id = decodeURIComponent(messageId[1]), list2 = rows4(data, MESSAGES), index = list2.findIndex((row) => row.messageId === id);
5099
+ if (index < 0) return { status: 404, body: { error: "message not found" }, collection: MESSAGES };
5100
+ if (method === "GET") return { status: 200, body: structuredClone(list2[index]), collection: MESSAGES };
5101
+ if (method === "DELETE") {
5102
+ const [removed] = list2.splice(index, 1);
5103
+ return { status: 200, body: { deleted: removed.messageId }, collection: MESSAGES, operation: "write", record: { deleted: removed.messageId } };
5104
+ }
5105
+ return void 0;
5106
+ }
5107
+ if (path === "/v2/signing-keys") {
5108
+ if (method === "GET") return { status: 200, body: { ...signingKeys(data) }, collection: SIGNING };
5109
+ if (method === "POST") {
5110
+ const keys = signingKeys(data);
5111
+ keys.next = keys.current;
5112
+ keys.current = `sig_${sequence}_${base64url(String(sequence)).replace(/[^A-Za-z0-9]/g, "").slice(0, 16)}`;
5113
+ return { status: 200, body: { current: keys.current, next: keys.next }, collection: SIGNING, operation: "write", record: { current: keys.current, next: keys.next } };
5114
+ }
5115
+ }
5116
+ return void 0;
5117
+ };
5118
+
4564
5119
  // src/runtime/gmail-mime.ts
4565
5120
  function parseGmailRaw(raw) {
4566
5121
  if (!/^[A-Za-z0-9_-]+={0,2}$/.test(raw)) return { error: "raw must be a base64url MIME message", unsupported: false };
@@ -4578,10 +5133,10 @@ function parseGmailRaw(raw) {
4578
5133
  if (headers.some((h) => h.name.toLowerCase() === match[1].toLowerCase())) return { error: "Duplicate MIME headers are outside the verified subset", unsupported: true };
4579
5134
  headers.push({ name: match[1], value: match[2] });
4580
5135
  }
4581
- const header3 = (name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
4582
- if (!header3("to")) return { error: "MIME To header is required", unsupported: false };
4583
- if (header3("content-type") && !/^text\/plain(?:\s*;\s*charset=(?:"?utf-8"?|"?us-ascii"?))?$/i.test(header3("content-type"))) return { error: "Only text/plain UTF-8 MIME is supported", unsupported: true };
4584
- if (header3("content-transfer-encoding") && !/^(7bit|8bit)$/i.test(header3("content-transfer-encoding"))) return { error: "Encoded MIME bodies are outside the verified subset", unsupported: true };
5136
+ const header4 = (name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
5137
+ if (!header4("to")) return { error: "MIME To header is required", unsupported: false };
5138
+ if (header4("content-type") && !/^text\/plain(?:\s*;\s*charset=(?:"?utf-8"?|"?us-ascii"?))?$/i.test(header4("content-type"))) return { error: "Only text/plain UTF-8 MIME is supported", unsupported: true };
5139
+ if (header4("content-transfer-encoding") && !/^(7bit|8bit)$/i.test(header4("content-transfer-encoding"))) return { error: "Encoded MIME bodies are outside the verified subset", unsupported: true };
4585
5140
  const text2 = mime.slice(boundary + 4);
4586
5141
  return { headers, text: text2, encodedBody: Buffer.from(text2).toString("base64url"), bytes: bytes.length };
4587
5142
  }
@@ -4785,13 +5340,13 @@ var detUuid = (seed) => {
4785
5340
  const s = hex.join("");
4786
5341
  return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
4787
5342
  };
4788
- var rows = (data, collection) => data[collection];
5343
+ var rows5 = (data, collection) => data[collection];
4789
5344
  var notFound = (collection, body) => ({ status: 404, body, collection });
4790
5345
  var badRequest = (collection, body) => ({ status: 400, body, collection });
4791
5346
  var ok = (collection, body, operation = "read") => ({ status: 200, body, collection, operation });
4792
5347
  var created = (collection, body, record3) => ({ status: 201, body, collection, record: structuredClone(record3), operation: "write" });
4793
5348
  var write2 = (status, collection, body, record3) => ({ status, body, collection, record: structuredClone(record3), operation: "write" });
4794
- var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
5349
+ var isObject4 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4795
5350
  var str = (v) => typeof v === "string" ? v : void 0;
4796
5351
  var pagination = (params, limitDefault, limitMax) => {
4797
5352
  if (params.limit !== void 0 && (!Number.isInteger(Number(params.limit)) || Number(params.limit) < 1 || Number(params.limit) > limitMax)) return void 0;
@@ -4810,18 +5365,18 @@ var boundedInt = (value, min, max) => {
4810
5365
  };
4811
5366
  function githubOperation(method, path, params, _headers, data, sequence) {
4812
5367
  const errors = (status, message, extra) => ({ status, body: { message, documentation_url: "https://docs.github.com/rest", ...extra ?? {} }, collection: "/repos" });
4813
- if (path === "/repos") return method === "GET" ? ok("/repos", rows(data, "/repos").map((row) => structuredClone(row))) : void 0;
5368
+ if (path === "/repos") return method === "GET" ? ok("/repos", rows5(data, "/repos").map((row) => structuredClone(row))) : void 0;
4814
5369
  const match = /^\/repos\/([^/]+)\/([^/]+)(?:\/(issues|pulls|check-runs)(?:\/(\d+))?(?:\/(comments|merge))?)?$/.exec(path);
4815
5370
  if (!match) return void 0;
4816
- const [, owner, name, resource, id, sub] = match;
5371
+ const [, owner, name, resource2, id, sub] = match;
4817
5372
  const repo = `${owner}/${name}`;
4818
- if (!rows(data, "/repos").some((r) => r.name === repo || r.full_name === repo)) return notFound("/repos", { message: "Not Found", documentation_url: "https://docs.github.com/rest" });
4819
- if (!resource) {
5373
+ if (!rows5(data, "/repos").some((r) => r.name === repo || r.full_name === repo)) return notFound("/repos", { message: "Not Found", documentation_url: "https://docs.github.com/rest" });
5374
+ if (!resource2) {
4820
5375
  if (method !== "GET") return void 0;
4821
- const repository = rows(data, "/repos").find((r) => r.name === repo || r.full_name === repo);
5376
+ const repository = rows5(data, "/repos").find((r) => r.name === repo || r.full_name === repo);
4822
5377
  return ok("/repos", structuredClone(repository));
4823
5378
  }
4824
- if (resource === "check-runs") {
5379
+ if (resource2 === "check-runs") {
4825
5380
  if (method !== "POST" || id) return void 0;
4826
5381
  if (typeof params.name !== "string" || !params.name || typeof params.head_sha !== "string" || !params.head_sha) return errors(422, "Validation Failed", { errors: [{ resource: "CheckRun", field: "name", code: "missing_field" }] });
4827
5382
  const allowed = ["name", "head_sha", "status", "conclusion"];
@@ -4829,11 +5384,11 @@ function githubOperation(method, path, params, _headers, data, sequence) {
4829
5384
  if (params.status !== void 0 && !["queued", "in_progress", "completed"].includes(String(params.status))) return errors(422, "Validation Failed", { errors: [{ resource: "CheckRun", field: "status", code: "invalid" }] });
4830
5385
  if (params.conclusion !== void 0 && !["success", "failure", "neutral", "cancelled", "skipped", "timed_out"].includes(String(params.conclusion))) return errors(422, "Validation Failed", { errors: [{ resource: "CheckRun", field: "conclusion", code: "invalid" }] });
4831
5386
  const run2 = { id: `github_at_${sequence}`, name: params.name, head_sha: params.head_sha, status: str(params.status) ?? (params.conclusion !== void 0 ? "completed" : "queued"), conclusion: params.conclusion === void 0 ? null : params.conclusion, repo, html_url: null, started_at: iso2(), completed_at: params.conclusion === void 0 ? null : iso2() };
4832
- rows(data, "/check-runs").push(run2);
5387
+ rows5(data, "/check-runs").push(run2);
4833
5388
  return created("/check-runs", structuredClone(run2), run2);
4834
5389
  }
4835
- if (resource === "issues") {
4836
- const inRepo = rows(data, "/issues").filter((r) => r.repo === repo);
5390
+ if (resource2 === "issues") {
5391
+ const inRepo = rows5(data, "/issues").filter((r) => r.repo === repo);
4837
5392
  if (method === "GET" && !id && !sub) {
4838
5393
  if (Object.keys(params).some((k) => !["state", "page", "per_page"].includes(k))) return void 0;
4839
5394
  const page = pagination(params, 30, 100);
@@ -4850,7 +5405,7 @@ function githubOperation(method, path, params, _headers, data, sequence) {
4850
5405
  if (typeof params.title !== "string" || !params.title) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "title", code: "missing_field" }] });
4851
5406
  if (params.labels !== void 0 && (!Array.isArray(params.labels) || !params.labels.every((l) => typeof l === "string"))) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "labels", code: "invalid" }] });
4852
5407
  const issue2 = { id: `github_at_${sequence}`, number: inRepo.reduce((max, r) => Math.max(max, Number(r.number) || 0), 0) + 1, repo, title: params.title, body: str(params.body) ?? null, state: "open", user: { login: "agenttwin-test" }, labels: Array.isArray(params.labels) ? structuredClone(params.labels) : [], comments: 0, created_at: iso2(), updated_at: iso2(), closed_at: null };
4853
- rows(data, "/issues").push(issue2);
5408
+ rows5(data, "/issues").push(issue2);
4854
5409
  return created("/issues", structuredClone(issue2), issue2);
4855
5410
  }
4856
5411
  const issue = id ? inRepo.find((r) => String(r.number) === id) : void 0;
@@ -4875,14 +5430,14 @@ function githubOperation(method, path, params, _headers, data, sequence) {
4875
5430
  if (typeof params.body !== "string" || !params.body) return errors(422, "Validation Failed", { errors: [{ resource: "IssueComment", field: "body", code: "missing_field" }] });
4876
5431
  if (Object.keys(params).some((k) => k !== "body")) return void 0;
4877
5432
  const comment = { id: `github_at_${sequence}`, repo, issue_number: issue.number, body: params.body, user: { login: "agenttwin-test" }, created_at: iso2(), updated_at: iso2() };
4878
- rows(data, "/comments").push(comment);
5433
+ rows5(data, "/comments").push(comment);
4879
5434
  return created("/comments", structuredClone(comment), comment);
4880
5435
  }
4881
- if (method === "GET" && sub === "comments") return ok("/comments", rows(data, "/comments").filter((c) => c.repo === repo && c.issue_number === issue.number).map((row) => structuredClone(row)));
5436
+ if (method === "GET" && sub === "comments") return ok("/comments", rows5(data, "/comments").filter((c) => c.repo === repo && c.issue_number === issue.number).map((row) => structuredClone(row)));
4882
5437
  return void 0;
4883
5438
  }
4884
- if (resource === "pulls") {
4885
- const inRepo = rows(data, "/pulls").filter((r) => r.repo === repo);
5439
+ if (resource2 === "pulls") {
5440
+ const inRepo = rows5(data, "/pulls").filter((r) => r.repo === repo);
4886
5441
  const pull = id ? inRepo.find((r) => String(r.number) === id) : void 0;
4887
5442
  if (method === "GET" && !id && !sub) {
4888
5443
  if (Object.keys(params).some((k) => k !== "state")) return void 0;
@@ -4916,45 +5471,45 @@ function linearOperation(method, path, params, _headers, data, sequence) {
4916
5471
  const isMutation = /\bmutation\b/.test(query.slice(0, query.indexOf("{") + 1));
4917
5472
  const root = new RegExp(isMutation ? "\\bmutation\\b[^{]*\\{\\s*(\\w+)" : "\\bquery\\b[^{]*\\{\\s*(\\w+)").exec(query);
4918
5473
  if (!root) return void 0;
4919
- const variables = isObject2(params.variables) ? params.variables : {};
5474
+ const variables = isObject4(params.variables) ? params.variables : {};
4920
5475
  const arg2 = (name) => variables[name] ?? (new RegExp(`\\b${name}\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(query)?.[1] !== void 0 ? JSON.parse(`"${new RegExp(`\\b${name}\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(query)[1]}"`) : void 0);
4921
5476
  const input = variables.input ?? void 0;
4922
5477
  if (!isMutation) {
4923
5478
  if (root[1] === "viewer") {
4924
5479
  if (Object.keys(variables).length) return void 0;
4925
- return ok("/users", { data: { viewer: rows(data, "/users")[0] ?? { id: "linear_at_viewer", name: "Test User", email: "user@example.test", displayName: "Test User" } } });
5480
+ return ok("/users", { data: { viewer: rows5(data, "/users")[0] ?? { id: "linear_at_viewer", name: "Test User", email: "user@example.test", displayName: "Test User" } } });
4926
5481
  }
4927
5482
  if (root[1] === "issues") {
4928
5483
  if (Object.keys(variables).length) return void 0;
4929
- return ok("/issues", { data: { issues: { nodes: rows(data, "/issues").map((row) => structuredClone(row)) } } });
5484
+ return ok("/issues", { data: { issues: { nodes: rows5(data, "/issues").map((row) => structuredClone(row)) } } });
4930
5485
  }
4931
5486
  if (root[1] === "projects") {
4932
5487
  if (Object.keys(variables).length) return void 0;
4933
- return ok("/projects", { data: { projects: { nodes: rows(data, "/projects").map((row) => structuredClone(row)) } } });
5488
+ return ok("/projects", { data: { projects: { nodes: rows5(data, "/projects").map((row) => structuredClone(row)) } } });
4934
5489
  }
4935
5490
  if (root[1] === "issue") {
4936
- const issue = rows(data, "/issues").find((r) => r.id === arg2("id"));
5491
+ const issue = rows5(data, "/issues").find((r) => r.id === arg2("id"));
4937
5492
  if (Object.keys(variables).some((k) => k !== "id") || arg2("id") === void 0) return void 0;
4938
5493
  return issue ? ok("/issues", { data: { issue: structuredClone(issue) } }) : notFoundNode("Issue");
4939
5494
  }
4940
5495
  if (root[1] === "project") {
4941
- const project = rows(data, "/projects").find((r) => r.id === arg2("id"));
5496
+ const project = rows5(data, "/projects").find((r) => r.id === arg2("id"));
4942
5497
  if (Object.keys(variables).some((k) => k !== "id") || arg2("id") === void 0) return void 0;
4943
5498
  return project ? ok("/projects", { data: { project: structuredClone(project) } }) : notFoundNode("Project");
4944
5499
  }
4945
5500
  return void 0;
4946
5501
  }
4947
5502
  if (root[1] === "issueCreate") {
4948
- if (!isObject2(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
5503
+ if (!isObject4(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
4949
5504
  if (Object.keys(input).some((k) => !["title", "description", "state", "assigneeId", "projectId", "priority", "teamId", "stateId", "labelIds", "parentId", "dueDate", "estimate", "cycleId", "subscriberIds"].includes(k))) return void 0;
4950
5505
  if (typeof input.title !== "string" || !input.title) return { status: 200, body: { data: null, errors: [{ message: "Issue title required" }] }, collection: "/issues" };
4951
5506
  const issue = { id: `linear_at_${sequence}`, title: input.title, description: str(input.description) ?? null, state: str(input.state) ?? "todo", assigneeId: str(input.assigneeId) ?? null, projectId: str(input.projectId) ?? null, priority: input.priority === void 0 ? 0 : input.priority, ...str(input.teamId) ? { teamId: str(input.teamId) } : {}, createdAt: iso2(), updatedAt: iso2() };
4952
- rows(data, "/issues").push(issue);
5507
+ rows5(data, "/issues").push(issue);
4953
5508
  return write2(200, "/issues", { data: { issueCreate: { success: true, lastSyncId: sequence, issue: structuredClone(issue) } } }, issue);
4954
5509
  }
4955
5510
  if (root[1] === "issueUpdate") {
4956
- if (!isObject2(input) || arg2("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
4957
- const issue = rows(data, "/issues").find((r) => r.id === arg2("id"));
5511
+ if (!isObject4(input) || arg2("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
5512
+ const issue = rows5(data, "/issues").find((r) => r.id === arg2("id"));
4958
5513
  if (!issue) return notFoundNode("Issue");
4959
5514
  if (Object.keys(input).some((k) => !["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k))) return void 0;
4960
5515
  for (const [k, v] of Object.entries(input)) if (["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k)) issue[k] = v;
@@ -4962,23 +5517,23 @@ function linearOperation(method, path, params, _headers, data, sequence) {
4962
5517
  return write2(200, "/issues", { data: { issueUpdate: { success: true, issue: structuredClone(issue) } } }, issue);
4963
5518
  }
4964
5519
  if (root[1] === "commentCreate") {
4965
- if (!isObject2(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
5520
+ if (!isObject4(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
4966
5521
  if (Object.keys(input).some((k) => !["issueId", "body"].includes(k))) return void 0;
4967
- const issue = rows(data, "/issues").find((r) => r.id === input.issueId);
5522
+ const issue = rows5(data, "/issues").find((r) => r.id === input.issueId);
4968
5523
  if (!issue) return notFoundNode("Issue");
4969
5524
  if (typeof input.body !== "string" || !input.body) return { status: 200, body: { data: null, errors: [{ message: "Comment body required" }] }, collection: "/comments" };
4970
- const comment = { id: `linear_at_${sequence}`, issueId: input.issueId, body: input.body, userId: rows(data, "/users")[0]?.id ?? "linear_at_viewer", createdAt: iso2() };
4971
- rows(data, "/comments").push(comment);
5525
+ const comment = { id: `linear_at_${sequence}`, issueId: input.issueId, body: input.body, userId: rows5(data, "/users")[0]?.id ?? "linear_at_viewer", createdAt: iso2() };
5526
+ rows5(data, "/comments").push(comment);
4972
5527
  return write2(200, "/comments", { data: { commentCreate: { success: true, comment: structuredClone(comment) } } }, comment);
4973
5528
  }
4974
5529
  return void 0;
4975
5530
  }
4976
5531
  var notionPropValue = (property) => {
4977
- if (!isObject2(property)) return property;
5532
+ if (!isObject4(property)) return property;
4978
5533
  if (property.title !== void 0) return Array.isArray(property.title) ? property.title.map((t) => t?.plain_text ?? t?.text?.content ?? "").join("") : property.title;
4979
5534
  if (property.rich_text !== void 0) return Array.isArray(property.rich_text) ? property.rich_text.map((t) => t?.plain_text ?? t?.text?.content ?? "").join("") : property.rich_text;
4980
- if (property.select !== void 0) return isObject2(property.select) ? property.select.name : property.select;
4981
- if (property.status !== void 0) return isObject2(property.status) ? property.status.name : property.status;
5535
+ if (property.select !== void 0) return isObject4(property.select) ? property.select.name : property.select;
5536
+ if (property.status !== void 0) return isObject4(property.status) ? property.status.name : property.status;
4982
5537
  return property.number ?? property.checkbox ?? property.url ?? property.email ?? property.phone_number ?? null;
4983
5538
  };
4984
5539
  var notionPage = (id, parent, properties, archived = false) => ({ object: "page", id, created_time: iso2(), last_edited_time: iso2(), created_by: null, last_edited_by: null, cover: null, icon: null, parent, archived, properties, url: null });
@@ -4990,24 +5545,24 @@ function notionOperation(method, path, params, headers, data, sequence) {
4990
5545
  if (path === "/v1/pages") {
4991
5546
  if (method !== "POST") return void 0;
4992
5547
  if (Object.keys(params).some((k) => !["parent", "properties"].includes(k))) return void 0;
4993
- const parent = isObject2(params.parent) ? params.parent : void 0;
5548
+ const parent = isObject4(params.parent) ? params.parent : void 0;
4994
5549
  if (!parent || str(parent.database_id) === void 0 || Object.keys(parent).some((k) => k !== "database_id")) return notionError("/pages", 400, "validation_error", "Bounded Notion twin supports database parents only: provide parent.database_id.");
4995
- const database = rows(data, "/databases").find((d) => d.id === parent.database_id);
5550
+ const database = rows5(data, "/databases").find((d) => d.id === parent.database_id);
4996
5551
  if (!database) return notionError("/pages", 404, "object_not_found", "Could not find database with ID.");
4997
- if (!isObject2(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be defined.");
5552
+ if (!isObject4(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be defined.");
4998
5553
  const page = notionPage(detUuid(`page:${sequence}`), { type: "database_id", database_id: database.id }, structuredClone(params.properties));
4999
- rows(data, "/pages").push(page);
5554
+ rows5(data, "/pages").push(page);
5000
5555
  return { status: 200, body: structuredClone(page), collection: "/pages", record: structuredClone(page), operation: "write" };
5001
5556
  }
5002
5557
  const pageMatch = /^\/v1\/pages\/([^/]+)$/.exec(path);
5003
5558
  if (pageMatch) {
5004
- const page = rows(data, "/pages").find((p) => p.id === pageMatch[1]);
5559
+ const page = rows5(data, "/pages").find((p) => p.id === pageMatch[1]);
5005
5560
  if (!page) return notionError("/pages", 404, "object_not_found", "Could not find page with ID.");
5006
5561
  if (method === "GET") return ok("/pages", structuredClone(page));
5007
5562
  if (method === "PATCH") {
5008
5563
  if (Object.keys(params).some((k) => !["properties", "archived", "in_trash"].includes(k))) return void 0;
5009
5564
  if (params.properties !== void 0) {
5010
- if (!isObject2(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be an object.");
5565
+ if (!isObject4(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be an object.");
5011
5566
  Object.assign(page.properties, structuredClone(params.properties));
5012
5567
  }
5013
5568
  if (params.archived !== void 0) {
@@ -5021,7 +5576,7 @@ function notionOperation(method, path, params, headers, data, sequence) {
5021
5576
  }
5022
5577
  const databaseMatch = /^\/v1\/databases\/([^/]+)(?:\/(query))?$/.exec(path);
5023
5578
  if (databaseMatch) {
5024
- const database = rows(data, "/databases").find((d) => d.id === databaseMatch[1]);
5579
+ const database = rows5(data, "/databases").find((d) => d.id === databaseMatch[1]);
5025
5580
  if (!database) return notionError("/databases", 404, "object_not_found", "Could not find database with ID.");
5026
5581
  if (!databaseMatch[2]) {
5027
5582
  if (method !== "GET") return void 0;
@@ -5035,13 +5590,13 @@ function notionOperation(method, path, params, headers, data, sequence) {
5035
5590
  if (!Number.isInteger(params.page_size) || Number(params.page_size) < 1 || Number(params.page_size) > 100) return notionError("/databases", 400, "validation_error", "page_size must be an integer between 1 and 100.");
5036
5591
  limit = Number(params.page_size);
5037
5592
  }
5038
- const pages = rows(data, "/pages").filter((p) => p.parent && p.parent.database_id === database.id);
5593
+ const pages = rows5(data, "/pages").filter((p) => p.parent && p.parent.database_id === database.id);
5039
5594
  if (params.filter !== void 0) {
5040
5595
  const filter = params.filter;
5041
- if (!isObject2(filter) || Object.keys(filter).length !== 2 || typeof filter.property !== "string") return void 0;
5596
+ if (!isObject4(filter) || Object.keys(filter).length !== 2 || typeof filter.property !== "string") return void 0;
5042
5597
  const [condition] = Object.keys(filter).filter((k) => k !== "property");
5043
5598
  if (!["title", "rich_text", "number", "select", "status", "checkbox"].includes(condition)) return void 0;
5044
- const expected = isObject2(filter[condition]) ? filter[condition].equals : void 0;
5599
+ const expected = isObject4(filter[condition]) ? filter[condition].equals : void 0;
5045
5600
  if (expected === void 0 || Object.keys(filter[condition]).length !== 1) return void 0;
5046
5601
  const property = filter.property;
5047
5602
  const results = pages.filter((p) => notionPropValue(p.properties[property]) === expected);
@@ -5054,15 +5609,15 @@ function notionOperation(method, path, params, headers, data, sequence) {
5054
5609
  if (method !== "PATCH" || blockMatch[2] !== "children") return void 0;
5055
5610
  if (Object.keys(params).some((k) => k !== "children")) return void 0;
5056
5611
  if (!Array.isArray(params.children) || !params.children.length || params.children.length > 100) return notionError("/blocks", 400, "validation_error", "children should be an array of 1\u2013100 block objects.");
5057
- if (!params.children.every(isObject2)) return notionError("/blocks", 400, "validation_error", "children should be block objects.");
5612
+ if (!params.children.every(isObject4)) return notionError("/blocks", 400, "validation_error", "children should be block objects.");
5058
5613
  if (params.children.some((c) => typeof c.type !== "string" || !c.type)) return notionError("/blocks", 400, "validation_error", "Each child block requires a type.");
5059
- const page = rows(data, "/pages").find((p) => p.id === blockMatch[1]);
5060
- const block = rows(data, "/blocks").find((b) => b.id === blockMatch[1]);
5614
+ const page = rows5(data, "/pages").find((p) => p.id === blockMatch[1]);
5615
+ const block = rows5(data, "/blocks").find((b) => b.id === blockMatch[1]);
5061
5616
  if (!page && !block) return notionError("/blocks", 404, "object_not_found", "Could not find block with ID.");
5062
5617
  const parent = page ? { type: "page_id", page_id: page.id } : { type: "block_id", block_id: block.id };
5063
5618
  const createdBlocks = params.children.map((child, index) => {
5064
5619
  const record3 = { object: "block", id: detUuid(`block:${sequence}:${index}`), parent, type: child.type, created_time: iso2(), last_edited_time: iso2(), has_children: false, archived: false, block: structuredClone(child) };
5065
- rows(data, "/blocks").push(record3);
5620
+ rows5(data, "/blocks").push(record3);
5066
5621
  return record3;
5067
5622
  });
5068
5623
  return write2(200, "/blocks", { object: "list", results: structuredClone(createdBlocks), has_more: false, next_cursor: null, type: "block", block: {} }, createdBlocks[createdBlocks.length - 1]);
@@ -5075,8 +5630,8 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5075
5630
  if (!match) return void 0;
5076
5631
  const [, object3, search, id] = match;
5077
5632
  const collection = `/crm/v3/objects/${object3}`;
5078
- const properties = isObject2(params.properties) ? params.properties : void 0;
5079
- const validProperties = (value) => Object.values(value).every((v) => ["string", "number", "boolean", "object"].includes(v === null ? "object" : typeof v));
5633
+ const properties = isObject4(params.properties) ? params.properties : void 0;
5634
+ const validProperties2 = (value) => Object.values(value).every((v) => ["string", "number", "boolean", "object"].includes(v === null ? "object" : typeof v));
5080
5635
  if (search) {
5081
5636
  if (method !== "POST" || id) return void 0;
5082
5637
  if (Object.keys(params).some((k) => !["query", "filterGroups", "limit", "after", "properties", "sorts"].includes(k))) return void 0;
@@ -5086,7 +5641,7 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5086
5641
  const searchAfter = boundedInt(params.after, 0, Number.MAX_SAFE_INTEGER);
5087
5642
  if (searchAfter === null) return badRequest(collection, { status: "error", message: "Unable to process: after must be a nonnegative integer offset", category: "VALIDATION_ERROR" });
5088
5643
  const limit = searchLimit ?? 10, after = searchAfter ?? 0;
5089
- let filtered = rows(data, collection);
5644
+ let filtered = rows5(data, collection);
5090
5645
  if (params.query !== void 0) {
5091
5646
  if (typeof params.query !== "string") return void 0;
5092
5647
  const needle = params.query.toLowerCase();
@@ -5095,9 +5650,9 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5095
5650
  if (params.filterGroups !== void 0) {
5096
5651
  if (!Array.isArray(params.filterGroups) || params.filterGroups.length !== 1) return void 0;
5097
5652
  const group = params.filterGroups[0];
5098
- if (!isObject2(group) || Object.keys(group).some((k) => k !== "filters") || !Array.isArray(group.filters) || !group.filters.length || group.filters.length > 3) return void 0;
5653
+ if (!isObject4(group) || Object.keys(group).some((k) => k !== "filters") || !Array.isArray(group.filters) || !group.filters.length || group.filters.length > 3) return void 0;
5099
5654
  for (const filter of group.filters) {
5100
- if (!isObject2(filter) || Object.keys(filter).some((k) => !["propertyName", "operator", "value"].includes(k)) || typeof filter.propertyName !== "string" || filter.operator !== "EQ" || filter.value === void 0) return void 0;
5655
+ if (!isObject4(filter) || Object.keys(filter).some((k) => !["propertyName", "operator", "value"].includes(k)) || typeof filter.propertyName !== "string" || filter.operator !== "EQ" || filter.value === void 0) return void 0;
5101
5656
  const propertyName = filter.propertyName;
5102
5657
  filtered = filtered.filter((r) => r.properties[propertyName] === filter.value);
5103
5658
  }
@@ -5112,20 +5667,20 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5112
5667
  if (listLimit === null) return badRequest(collection, { status: "error", message: "Unable to process: limit must be between 1 and 100", category: "VALIDATION_ERROR" });
5113
5668
  const listAfter = boundedInt(params.after, 0, Number.MAX_SAFE_INTEGER);
5114
5669
  if (listAfter === null) return badRequest(collection, { status: "error", message: "Unable to process: after must be a nonnegative integer offset", category: "VALIDATION_ERROR" });
5115
- const page = rows(data, collection).slice(listAfter ?? 0, (listAfter ?? 0) + (listLimit ?? 10));
5116
- return ok(collection, { total: rows(data, collection).length, results: page.map((r) => hubspotEnvelope(r)) });
5670
+ const page = rows5(data, collection).slice(listAfter ?? 0, (listAfter ?? 0) + (listLimit ?? 10));
5671
+ return ok(collection, { total: rows5(data, collection).length, results: page.map((r) => hubspotEnvelope(r)) });
5117
5672
  }
5118
5673
  if (method !== "POST") return void 0;
5119
- if (Object.keys(params).some((k) => k !== "properties" && k !== "associations") || params.associations !== void 0 && !Array.isArray(params.associations) || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: `Invalid input JSON on line 1: Unable to process JSON: properties required for ${object3}`, category: "VALIDATION_ERROR" });
5120
- const record4 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso2(), updatedAt: iso2() };
5121
- rows(data, collection).push(record4);
5674
+ if (Object.keys(params).some((k) => k !== "properties" && k !== "associations") || params.associations !== void 0 && !Array.isArray(params.associations) || !properties || !validProperties2(properties)) return badRequest(collection, { status: "error", message: `Invalid input JSON on line 1: Unable to process JSON: properties required for ${object3}`, category: "VALIDATION_ERROR" });
5675
+ const record4 = { id: uniqueId(rows5(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso2(), updatedAt: iso2() };
5676
+ rows5(data, collection).push(record4);
5122
5677
  return created(collection, hubspotEnvelope(record4), record4);
5123
5678
  }
5124
- const record3 = rows(data, collection).find((r) => r.id === id);
5679
+ const record3 = rows5(data, collection).find((r) => r.id === id);
5125
5680
  if (!record3) return { status: 404, body: { status: "error", message: `Object not found: ${object3} with id ${id}`, category: "OBJECT_NOT_FOUND" }, collection };
5126
5681
  if (method === "GET") return ok(collection, hubspotEnvelope(record3));
5127
5682
  if (method === "PATCH") {
5128
- if (Object.keys(params).some((k) => k !== "properties") || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: "Unable to process JSON: properties object required", category: "VALIDATION_ERROR" });
5683
+ if (Object.keys(params).some((k) => k !== "properties") || !properties || !validProperties2(properties)) return badRequest(collection, { status: "error", message: "Unable to process JSON: properties object required", category: "VALIDATION_ERROR" });
5129
5684
  Object.assign(record3.properties, structuredClone(properties));
5130
5685
  record3.updatedAt = iso2();
5131
5686
  return write2(200, collection, hubspotEnvelope(record3), record3);
@@ -5137,10 +5692,10 @@ var shopifySlug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").rep
5137
5692
  function shopifyOperation(method, path, params, _headers, data, sequence) {
5138
5693
  const match = new RegExp(`^/admin/api/${SHOPIFY_VERSION}/(products|orders|customers)(?:/(\\d+))?\\.json$`).exec(path);
5139
5694
  if (!match) return void 0;
5140
- const [, resource, id] = match;
5141
- const collection = `/admin/${resource}`;
5142
- const wrap = resource === "products" ? "product" : resource === "orders" ? "order" : "customer";
5143
- const rowsIn2 = rows(data, collection);
5695
+ const [, resource2, id] = match;
5696
+ const collection = `/admin/${resource2}`;
5697
+ const wrap = resource2 === "products" ? "product" : resource2 === "orders" ? "order" : "customer";
5698
+ const rowsIn2 = rows5(data, collection);
5144
5699
  const notFoundShopify = () => notFound(collection, { errors: "Not Found" });
5145
5700
  const enriched = (record4) => ({ ...structuredClone(record4), created_at: record4.created_at ?? iso2(), updated_at: iso2() });
5146
5701
  if (!id) {
@@ -5153,22 +5708,22 @@ function shopifyOperation(method, path, params, _headers, data, sequence) {
5153
5708
  if (!Number.isInteger(Number(params.since_id)) || Number(params.since_id) < 0) return badRequest(collection, { errors: "since_id must be a nonnegative integer" });
5154
5709
  filtered = filtered.filter((r) => Number(r.id) > Number(params.since_id));
5155
5710
  }
5156
- return ok(collection, { [`${resource}`]: filtered.slice(0, page.limit).map(enriched) });
5711
+ return ok(collection, { [`${resource2}`]: filtered.slice(0, page.limit).map(enriched) });
5157
5712
  }
5158
5713
  if (method !== "POST") return void 0;
5159
- if (Object.keys(params).some((k) => k !== wrap) || !isObject2(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
5714
+ if (Object.keys(params).some((k) => k !== wrap) || !isObject4(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
5160
5715
  const body = params[wrap];
5161
- if (resource === "products" && (typeof body.title !== "string" || !body.title)) return { status: 422, body: { errors: { title: ["can't be blank"] } }, collection };
5162
- if (resource === "orders") {
5163
- if (!Array.isArray(body.line_items) || !body.line_items.length || !body.line_items.every(isObject2)) return { status: 422, body: { errors: { line_items: ["can't be blank"] } }, collection };
5716
+ if (resource2 === "products" && (typeof body.title !== "string" || !body.title)) return { status: 422, body: { errors: { title: ["can't be blank"] } }, collection };
5717
+ if (resource2 === "orders") {
5718
+ if (!Array.isArray(body.line_items) || !body.line_items.length || !body.line_items.every(isObject4)) return { status: 422, body: { errors: { line_items: ["can't be blank"] } }, collection };
5164
5719
  if (body.line_items.some((item) => Object.keys(item).some((k) => !["title", "quantity", "price", "sku"].includes(k)))) return void 0;
5165
5720
  }
5166
- const allowed = { products: ["title", "body_html", "vendor", "product_type", "status", "tags", "variants", "options"], orders: ["email", "phone", "line_items", "financial_status", "fulfillment_status", "note", "total_price", "currency"], customers: ["first_name", "last_name", "email", "phone", "note", "tags"] }[resource];
5721
+ const allowed = { products: ["title", "body_html", "vendor", "product_type", "status", "tags", "variants", "options"], orders: ["email", "phone", "line_items", "financial_status", "fulfillment_status", "note", "total_price", "currency"], customers: ["first_name", "last_name", "email", "phone", "note", "tags"] }[resource2];
5167
5722
  if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
5168
- const record4 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource] + sequence), created_at: iso2(), updated_at: iso2() };
5169
- if (resource === "products") Object.assign(record4, { title: body.title, body_html: body.body_html ?? null, vendor: body.vendor ?? null, product_type: body.product_type ?? null, handle: shopifySlug(String(body.title)), status: str(body.status) ?? "active", tags: body.tags ?? "", variants: Array.isArray(body.variants) ? structuredClone(body.variants) : [], options: Array.isArray(body.options) ? structuredClone(body.options) : [], image: null, images: [] });
5170
- if (resource === "orders") Object.assign(record4, { email: body.email ?? null, phone: body.phone ?? null, note: body.note ?? null, line_items: structuredClone(body.line_items), total_price: typeof body.total_price === "string" ? body.total_price : Number(Array.isArray(body.line_items) ? body.line_items.reduce((sum, item) => sum + Number(item.price ?? 0) * Number(item.quantity ?? 1), 0) : 0).toFixed(2), currency: str(body.currency) ?? "USD", financial_status: str(body.financial_status) ?? "pending", fulfillment_status: body.fulfillment_status ?? null });
5171
- if (resource === "customers") Object.assign(record4, { first_name: body.first_name ?? null, last_name: body.last_name ?? null, email: body.email ?? null, phone: body.phone ?? null, note: body.note ?? null, tags: body.tags ?? "", state: "enabled", verified_email: true, accepts_marketing: false });
5723
+ const record4 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource2] + sequence), created_at: iso2(), updated_at: iso2() };
5724
+ if (resource2 === "products") Object.assign(record4, { title: body.title, body_html: body.body_html ?? null, vendor: body.vendor ?? null, product_type: body.product_type ?? null, handle: shopifySlug(String(body.title)), status: str(body.status) ?? "active", tags: body.tags ?? "", variants: Array.isArray(body.variants) ? structuredClone(body.variants) : [], options: Array.isArray(body.options) ? structuredClone(body.options) : [], image: null, images: [] });
5725
+ if (resource2 === "orders") Object.assign(record4, { email: body.email ?? null, phone: body.phone ?? null, note: body.note ?? null, line_items: structuredClone(body.line_items), total_price: typeof body.total_price === "string" ? body.total_price : Number(Array.isArray(body.line_items) ? body.line_items.reduce((sum, item) => sum + Number(item.price ?? 0) * Number(item.quantity ?? 1), 0) : 0).toFixed(2), currency: str(body.currency) ?? "USD", financial_status: str(body.financial_status) ?? "pending", fulfillment_status: body.fulfillment_status ?? null });
5726
+ if (resource2 === "customers") Object.assign(record4, { first_name: body.first_name ?? null, last_name: body.last_name ?? null, email: body.email ?? null, phone: body.phone ?? null, note: body.note ?? null, tags: body.tags ?? "", state: "enabled", verified_email: true, accepts_marketing: false });
5172
5727
  rowsIn2.push(record4);
5173
5728
  return created(collection, { [wrap]: enriched(record4) }, record4);
5174
5729
  }
@@ -5176,12 +5731,12 @@ function shopifyOperation(method, path, params, _headers, data, sequence) {
5176
5731
  if (!record3) return notFoundShopify();
5177
5732
  if (method === "GET") return ok(collection, { [wrap]: enriched(record3) });
5178
5733
  if (method === "PUT") {
5179
- if (Object.keys(params).some((k) => k !== wrap) || !isObject2(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
5734
+ if (Object.keys(params).some((k) => k !== wrap) || !isObject4(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
5180
5735
  const body = params[wrap];
5181
- const allowed = { products: ["title", "body_html", "vendor", "product_type", "status", "tags"], orders: ["email", "phone", "note", "financial_status", "fulfillment_status"], customers: ["first_name", "last_name", "email", "phone", "note", "tags"] }[resource];
5736
+ const allowed = { products: ["title", "body_html", "vendor", "product_type", "status", "tags"], orders: ["email", "phone", "note", "financial_status", "fulfillment_status"], customers: ["first_name", "last_name", "email", "phone", "note", "tags"] }[resource2];
5182
5737
  if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
5183
5738
  for (const [k, v] of Object.entries(body)) record3[k] = v;
5184
- if (resource === "products" && body.title !== void 0) record3.handle = shopifySlug(String(body.title));
5739
+ if (resource2 === "products" && body.title !== void 0) record3.handle = shopifySlug(String(body.title));
5185
5740
  record3.updated_at = iso2();
5186
5741
  return write2(200, collection, { [wrap]: enriched(record3) }, record3);
5187
5742
  }
@@ -5194,22 +5749,22 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
5194
5749
  if (!id) {
5195
5750
  if (method === "GET") {
5196
5751
  if (Object.keys(params).some((k) => k !== "name")) return void 0;
5197
- const filtered = params.name === void 0 ? rows(data, "/monitors") : rows(data, "/monitors").filter((m) => typeof params.name === "string" && String(m.name).includes(params.name));
5752
+ const filtered = params.name === void 0 ? rows5(data, "/monitors") : rows5(data, "/monitors").filter((m) => typeof params.name === "string" && String(m.name).includes(params.name));
5198
5753
  return ok("/monitors", filtered.map((row) => structuredClone(row)));
5199
5754
  }
5200
5755
  if (method !== "POST") return void 0;
5201
5756
  if (Object.keys(params).some((k) => !["name", "type", "query", "message", "tags", "options", "priority"].includes(k))) return void 0;
5202
5757
  if (typeof params.name !== "string" || !params.name || typeof params.type !== "string" || !params.type || typeof params.query !== "string" || !params.query) return badRequest("/monitors", { errors: ["The value provided for parameter 'name', 'type' or 'query' is invalid"] });
5203
- const monitor2 = { id: sequence, name: params.name, type: params.type, query: params.query, message: str(params.message) ?? "", tags: Array.isArray(params.tags) ? structuredClone(params.tags) : [], options: isObject2(params.options) ? structuredClone(params.options) : {}, priority: params.priority === void 0 ? null : params.priority, overall_state: "OK", creator: { name: "agenttwin@example.test", handle: "agenttwin@example.test" }, created: iso2(), modified: iso2() };
5204
- rows(data, "/monitors").push(monitor2);
5758
+ const monitor2 = { id: sequence, name: params.name, type: params.type, query: params.query, message: str(params.message) ?? "", tags: Array.isArray(params.tags) ? structuredClone(params.tags) : [], options: isObject4(params.options) ? structuredClone(params.options) : {}, priority: params.priority === void 0 ? null : params.priority, overall_state: "OK", creator: { name: "agenttwin@example.test", handle: "agenttwin@example.test" }, created: iso2(), modified: iso2() };
5759
+ rows5(data, "/monitors").push(monitor2);
5205
5760
  return { status: 200, body: structuredClone(monitor2), collection: "/monitors", record: structuredClone(monitor2), operation: "write" };
5206
5761
  }
5207
- const monitor = rows(data, "/monitors").find((m) => String(m.id) === id);
5762
+ const monitor = rows5(data, "/monitors").find((m) => String(m.id) === id);
5208
5763
  if (!monitor) return notFound("/monitors", { errors: ["Monitor not found"] });
5209
5764
  if (method === "GET" && !mute) return ok("/monitors", structuredClone(monitor));
5210
5765
  if (method === "POST" && mute === "mute") {
5211
5766
  if (Object.keys(params).some((k) => !["scope", "end"].includes(k))) return void 0;
5212
- const options = isObject2(monitor.options) ? monitor.options : {};
5767
+ const options = isObject4(monitor.options) ? monitor.options : {};
5213
5768
  monitor.options = { ...options, muted: true };
5214
5769
  monitor.modified = iso2();
5215
5770
  return write2(200, "/monitors", structuredClone(monitor), monitor);
@@ -5221,14 +5776,14 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
5221
5776
  if (Object.keys(params).some((k) => !["title", "text", "tags", "priority", "alert_type", "source"].includes(k))) return void 0;
5222
5777
  if (typeof params.title !== "string" || !params.title || typeof params.text !== "string" || !params.text) return badRequest("/events", { errors: ["The value provided for parameter 'title' or 'text' is invalid"] });
5223
5778
  const event = { id: sequence, title: params.title, text: params.text, tags: Array.isArray(params.tags) ? structuredClone(params.tags) : [], priority: params.priority === void 0 ? "normal" : params.priority, alert_type: str(params.alert_type) ?? "info", source: str(params.source) ?? "agenttwin", date_happened: twinNowSeconds(EPOCH2), device_name: null, host: null, resource: `/api/v1/events/${sequence}`, url: null, status: "ok" };
5224
- rows(data, "/events").push(event);
5779
+ rows5(data, "/events").push(event);
5225
5780
  return { status: 200, body: { status: "ok", event: structuredClone(event) }, collection: "/events", record: structuredClone(event), operation: "write" };
5226
5781
  }
5227
5782
  if (method === "GET") {
5228
5783
  if (Object.keys(params).some((k) => !["start", "end", "priority", "tags", "sources"].includes(k))) return void 0;
5229
5784
  if (params.start === void 0 || params.end === void 0) return badRequest("/events", { errors: ["start and end parameters are required"] });
5230
5785
  if (!Number.isInteger(Number(params.start)) || !Number.isInteger(Number(params.end))) return badRequest("/events", { errors: ["start and end parameters must be integers"] });
5231
- let filtered = rows(data, "/events").filter((e) => Number(e.date_happened) >= Number(params.start) && Number(e.date_happened) <= Number(params.end));
5786
+ let filtered = rows5(data, "/events").filter((e) => Number(e.date_happened) >= Number(params.start) && Number(e.date_happened) <= Number(params.end));
5232
5787
  if (params.priority !== void 0) filtered = filtered.filter((e) => e.priority === params.priority);
5233
5788
  if (params.tags !== void 0) {
5234
5789
  if (typeof params.tags !== "string") return void 0;
@@ -5248,7 +5803,7 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
5248
5803
  if (to <= from) return badRequest("/api/v1/query", { errors: ["to must be after from"] });
5249
5804
  const parsed = /^(?:avg|min|max|sum):([a-zA-Z0-9_.]+)\{[^}]*\}$/.exec(params.query);
5250
5805
  if (!parsed) return badRequest("/api/v1/query", { errors: ["query must look like avg:metric.name{scope}"] });
5251
- const metric = rows(data, "/metrics").find((m) => m.metric === parsed[1]);
5806
+ const metric = rows5(data, "/metrics").find((m) => m.metric === parsed[1]);
5252
5807
  const pointlist = metric ? metric.points.filter(([ts]) => ts >= from && ts <= to) : [];
5253
5808
  return ok("/metrics", { status: "ok", from_date: from * 1e3, to_date: to * 1e3, query: params.query, series: [{ metric: parsed[1], display_name: parsed[1].split(".").pop(), unit: null, pointlist: pointlist.map(([ts, value]) => [ts * 1e3, value]), scope: null, expression: params.query }] });
5254
5809
  }
@@ -5265,8 +5820,8 @@ var PUBSUB_SUBSCRIPTIONS = "/pubsub/subscriptions";
5265
5820
  var PUBSUB_MESSAGES = "/pubsub/messages";
5266
5821
  var gmailHeader = (message, name) => (message.payload?.headers ?? []).find((h) => h.name.toLowerCase() === name)?.value;
5267
5822
  var gmailDate = (message) => Number(message.internalDate ?? 0);
5268
- function startingRows(adapter, path, rows2, nowMs) {
5269
- const copy = structuredClone(rows2);
5823
+ function startingRows(adapter, path, rows6, nowMs) {
5824
+ const copy = structuredClone(rows6);
5270
5825
  if (adapter !== "gmail" || path !== GMAIL_MESSAGES) return copy;
5271
5826
  const at = nowMs - 6e4;
5272
5827
  for (const message of copy) {
@@ -5285,16 +5840,32 @@ var gmailLabelKnown = (data) => {
5285
5840
  return (id) => GMAIL_SYSTEM_LABELS.has(id) || seeded.has(id);
5286
5841
  };
5287
5842
  var gmailHistoryId = (messages) => messages.reduce((max, m) => BigInt(String(m.historyId ?? 0)) > BigInt(max) ? String(m.historyId) : max, "0");
5843
+ var gmailNextHistoryId = (data) => String(BigInt(gmailHistoryId(rowsIn(data, GMAIL_MESSAGES))) + 1n);
5288
5844
  function gmailQueryMatcher(q) {
5289
- const clauses = q.trim().split(/\s+OR\s+/);
5290
- const parsed = [];
5291
- for (const clause of clauses) {
5292
- const terms = clause.trim().split(/\s+/).map((token) => /^(from|to):([^\s()"]+@[^\s()"]+)$/i.exec(token));
5293
- if (!terms.length || terms.some((t) => !t)) return void 0;
5294
- parsed.push(terms.map((t) => ({ field: t[1].toLowerCase(), address: t[2].toLowerCase() })));
5295
- }
5296
- return (message) => parsed.some((terms) => terms.every((t) => headerAddresses(gmailHeader(message, t.field)).includes(t.address)));
5845
+ const clauses = q.trim().split(/\s+OR\s+/).map((clause) => clause.trim()).filter(Boolean);
5846
+ if (!clauses.length) return () => true;
5847
+ const text2 = (message) => [message.snippet, gmailHeader(message, "subject"), gmailHeader(message, "from"), gmailHeader(message, "to")].filter((v) => typeof v === "string").join(" ").toLowerCase();
5848
+ const matchers = clauses.map((clause) => {
5849
+ const tests = clause.split(/\s+/).map((token) => {
5850
+ const messageId = /^rfc822msgid:(.+)$/i.exec(token);
5851
+ if (messageId) {
5852
+ const want2 = messageId[1].replace(/[<>]/g, "").toLowerCase();
5853
+ return (message) => String(gmailHeader(message, "message-id") ?? "").replace(/[<>]/g, "").toLowerCase() === want2;
5854
+ }
5855
+ const address2 = /^(from|to):(.+)$/i.exec(token);
5856
+ if (address2) {
5857
+ const want2 = address2[2].toLowerCase();
5858
+ return (message) => headerAddresses(gmailHeader(message, address2[1].toLowerCase())).some((found) => found.includes(want2));
5859
+ }
5860
+ const want = token.toLowerCase();
5861
+ return (message) => text2(message).includes(want);
5862
+ });
5863
+ return (message) => tests.every((test) => test(message));
5864
+ });
5865
+ return (message) => matchers.some((match) => match(message));
5297
5866
  }
5867
+ var gmailPageOffset = (value, total) => value === void 0 ? 0 : typeof value === "string" && /^\d{1,9}$/.test(value) && Number(value) <= total ? Number(value) : void 0;
5868
+ var gmailLabelFilter = (params) => params.labelIds === void 0 ? [] : Array.isArray(params.labelIds) ? params.labelIds.map(String) : [String(params.labelIds)];
5298
5869
  function gmailBatch(params, headers, data, sequence, raw) {
5299
5870
  if (raw === void 0 || Object.keys(params).length) return void 0;
5300
5871
  const contentType2 = headers["content-type"];
@@ -5375,9 +5946,29 @@ function gmailDraftWrite(data, raw, threadIdInput, sequence, index) {
5375
5946
  return gmailStoreDraft(data, mime, threadId, sequence, index);
5376
5947
  }
5377
5948
  function gmailOperation(method, path, params, headers, data, sequence, raw) {
5378
- const MESSAGES = GMAIL_MESSAGES, LABELS = "/gmail/v1/users/me/labels";
5379
- const fail = (status, message) => googleError(MESSAGES, status, message);
5949
+ const MESSAGES2 = GMAIL_MESSAGES, LABELS = "/gmail/v1/users/me/labels";
5950
+ const fail = (status, message) => googleError(MESSAGES2, status, message);
5380
5951
  if (path === "/batch/gmail/v1") return method === "POST" ? gmailBatch(params, headers, data, sequence, raw) : void 0;
5952
+ if (path === `${MESSAGES2}/batchModify`) {
5953
+ if (method !== "POST" || Object.keys(params).some((k) => !["ids", "addLabelIds", "removeLabelIds"].includes(k))) return void 0;
5954
+ if (!Array.isArray(params.ids) || !params.ids.length || params.ids.some((id) => typeof id !== "string" || !id)) return fail(400, "ids must be a non-empty array of message ids.");
5955
+ if (params.ids.length > 1e3) return fail(400, "ids must contain at most 1000 message ids.");
5956
+ const list2 = (v) => v === void 0 ? [] : Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
5957
+ const add = list2(params.addLabelIds), remove2 = list2(params.removeLabelIds);
5958
+ if (!add || !remove2) return fail(400, "Invalid label list.");
5959
+ const known2 = gmailLabelKnown(data), unknown = [...add, ...remove2].find((id) => !known2(id));
5960
+ if (unknown) return fail(400, `Invalid label: ${unknown}`);
5961
+ const targets = rowsIn(data, MESSAGES2).filter((m) => params.ids.includes(String(m.id)));
5962
+ const next = gmailNextHistoryId(data);
5963
+ for (const message of targets) {
5964
+ const labels = new Set(message.labelIds ?? []);
5965
+ for (const l of add) labels.add(l);
5966
+ for (const l of remove2) labels.delete(l);
5967
+ message.labelIds = [...labels];
5968
+ message.historyId = next;
5969
+ }
5970
+ return { status: 204, body: null, collection: MESSAGES2, operation: "write", record: { batchModify: params.ids.length, matched: targets.length, addLabelIds: add, removeLabelIds: remove2 } };
5971
+ }
5381
5972
  const uploadMatch = /^\/upload\/gmail\/v1\/users\/me\/drafts(?:\/([^/]+))?$/.exec(path);
5382
5973
  if (uploadMatch) {
5383
5974
  const id = uploadMatch[1] === void 0 ? void 0 : decodeURIComponent(uploadMatch[1]);
@@ -5399,25 +5990,52 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5399
5990
  return gmailDraftWrite(data, upload.raw, threadId === null ? void 0 : threadId, sequence, index);
5400
5991
  }
5401
5992
  if (path === GMAIL_THREADS) {
5402
- if (method !== "GET" || Object.keys(params).some((k) => !["q", "maxResults", "labelIds"].includes(k))) return void 0;
5993
+ if (method !== "GET" || Object.keys(params).some((k) => !["q", "maxResults", "labelIds", "pageToken", "includeSpamTrash"].includes(k))) return void 0;
5403
5994
  if (params.q !== void 0 && typeof params.q !== "string") return googleError(GMAIL_THREADS, 400, "q must be a string.");
5995
+ if (params.includeSpamTrash !== void 0 && !["true", "false", true, false].includes(params.includeSpamTrash)) return googleError(GMAIL_THREADS, 400, "includeSpamTrash must be true or false.");
5404
5996
  const matcher = params.q === void 0 || params.q === "" ? () => true : gmailQueryMatcher(params.q);
5405
5997
  if (!matcher) return void 0;
5406
5998
  const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
5407
5999
  if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(GMAIL_THREADS, 400, "maxResults must be an integer from 1 to 500.");
5408
- const labels = params.labelIds === void 0 ? [] : Array.isArray(params.labelIds) ? params.labelIds.map(String) : [String(params.labelIds)];
6000
+ const labels = gmailLabelFilter(params), spamTrash = params.includeSpamTrash === true || params.includeSpamTrash === "true";
5409
6001
  const latest = /* @__PURE__ */ new Map();
5410
- for (const message of rowsIn(data, MESSAGES)) {
6002
+ for (const message of rowsIn(data, MESSAGES2)) {
5411
6003
  const ids = Array.isArray(message.labelIds) ? message.labelIds : [];
5412
- if (ids.includes("SPAM") || ids.includes("TRASH") || !labels.every((l) => ids.includes(l)) || !matcher(message)) continue;
6004
+ if (!spamTrash && (ids.includes("SPAM") || ids.includes("TRASH")) || !labels.every((l) => ids.includes(l)) || !matcher(message)) continue;
5413
6005
  const thread = String(message.threadId ?? message.id);
5414
6006
  if (!latest.has(thread) || gmailDate(message) > gmailDate(latest.get(thread))) latest.set(thread, message);
5415
6007
  }
5416
- const threads = [...latest.entries()].sort((a, b) => gmailDate(b[1]) - gmailDate(a[1])).slice(0, max).map(([id]) => {
6008
+ const ordered = [...latest.entries()].sort((a, b) => gmailDate(b[1]) - gmailDate(a[1]));
6009
+ const offset = gmailPageOffset(params.pageToken, ordered.length);
6010
+ if (offset === void 0) return void 0;
6011
+ const threads = ordered.slice(offset, offset + max).map(([id]) => {
5417
6012
  const messages = gmailThreadMessages(data, id);
5418
6013
  return { id, snippet: messages.at(-1)?.snippet ?? "", historyId: gmailHistoryId(messages) };
5419
6014
  });
5420
- return ok(GMAIL_THREADS, threads.length ? { threads, resultSizeEstimate: threads.length } : { resultSizeEstimate: 0 });
6015
+ const nextPageToken = offset + max < ordered.length ? String(offset + max) : void 0;
6016
+ return ok(GMAIL_THREADS, { ...threads.length ? { threads } : {}, resultSizeEstimate: ordered.length, ...nextPageToken ? { nextPageToken } : {} });
6017
+ }
6018
+ const trashMatch = /^\/gmail\/v1\/users\/me\/(messages|threads)\/([^/]+)\/(trash|untrash)$/.exec(path);
6019
+ if (trashMatch) {
6020
+ if (method !== "POST" || Object.keys(params).length) return void 0;
6021
+ const [, kind, rawId, action] = trashMatch, id = decodeURIComponent(rawId);
6022
+ const targets = kind === "messages" ? rowsIn(data, MESSAGES2).filter((m) => m.id === id) : rowsIn(data, MESSAGES2).filter((m) => m.threadId === id);
6023
+ if (!targets.length) return googleError(kind === "messages" ? MESSAGES2 : GMAIL_THREADS, 404, "Requested entity was not found.");
6024
+ const next = gmailNextHistoryId(data);
6025
+ for (const message of targets) {
6026
+ const labels = new Set(message.labelIds ?? []);
6027
+ if (action === "trash") {
6028
+ labels.delete("INBOX");
6029
+ labels.add("TRASH");
6030
+ } else {
6031
+ labels.delete("TRASH");
6032
+ labels.add("INBOX");
6033
+ }
6034
+ message.labelIds = [...labels];
6035
+ message.historyId = next;
6036
+ }
6037
+ const body = kind === "messages" ? structuredClone(targets[0]) : { id, historyId: next, messages: targets.map((m) => structuredClone(m)) };
6038
+ return { status: 200, body, collection: kind === "messages" ? MESSAGES2 : GMAIL_THREADS, operation: "write", record: { id, action } };
5421
6039
  }
5422
6040
  const threadMatch = /^\/gmail\/v1\/users\/me\/threads\/([^/]+)$/.exec(path);
5423
6041
  if (threadMatch) {
@@ -5427,23 +6045,55 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5427
6045
  return ok(GMAIL_THREADS, { id: decodeURIComponent(threadMatch[1]), historyId: gmailHistoryId(messages), messages: structuredClone(messages) });
5428
6046
  }
5429
6047
  if (path === "/gmail/v1/users/me/history") {
5430
- if (method !== "GET" || Object.keys(params).some((k) => !["startHistoryId", "historyTypes", "maxResults"].includes(k))) return void 0;
6048
+ if (method !== "GET" || Object.keys(params).some((k) => !["startHistoryId", "historyTypes", "maxResults", "pageToken"].includes(k))) return void 0;
5431
6049
  if (params.historyTypes !== void 0 && !["messageAdded", "labelAdded", "labelRemoved"].includes(String(params.historyTypes))) return void 0;
5432
- if (typeof params.startHistoryId !== "string" || !/^\d{1,20}$/.test(params.startHistoryId)) return googleError(MESSAGES, 400, "startHistoryId is required.");
6050
+ if (typeof params.startHistoryId !== "string" || !/^\d{1,20}$/.test(params.startHistoryId)) return googleError(MESSAGES2, 400, "startHistoryId is required.");
5433
6051
  const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
5434
- if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(MESSAGES, 400, "maxResults must be an integer from 1 to 500.");
6052
+ if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(MESSAGES2, 400, "maxResults must be an integer from 1 to 500.");
5435
6053
  const start = BigInt(params.startHistoryId);
5436
- const all = rowsIn(data, MESSAGES);
6054
+ const all = rowsIn(data, MESSAGES2);
5437
6055
  const added = all.filter((m) => BigInt(String(m.historyId ?? 0)) > start).sort((a, b) => BigInt(String(a.historyId)) < BigInt(String(b.historyId)) ? -1 : 1);
5438
- if (added.length > max) return void 0;
5439
- const history = added.map((m) => ({ id: String(m.historyId), messages: [{ id: m.id, threadId: m.threadId }], messagesAdded: [{ message: { id: m.id, threadId: m.threadId, labelIds: structuredClone(m.labelIds ?? []) } }] }));
6056
+ const offset = params.pageToken === void 0 ? 0 : typeof params.pageToken === "string" && /^\d{1,9}$/.test(params.pageToken) ? Number(params.pageToken) : NaN;
6057
+ if (!Number.isInteger(offset) || offset < 0 || offset > added.length) return void 0;
6058
+ const page = added.slice(offset, offset + max);
6059
+ const history = page.map((m) => ({ id: String(m.historyId), messages: [{ id: m.id, threadId: m.threadId }], messagesAdded: [{ message: { id: m.id, threadId: m.threadId, labelIds: structuredClone(m.labelIds ?? []) } }] }));
5440
6060
  const latest = gmailHistoryId(all);
5441
- return ok(MESSAGES, { ...history.length ? { history } : {}, historyId: BigInt(latest) > start ? latest : params.startHistoryId });
6061
+ const nextPageToken = offset + max < added.length ? String(offset + max) : void 0;
6062
+ return ok(MESSAGES2, { ...history.length ? { history } : {}, historyId: BigInt(latest) > start ? latest : params.startHistoryId, ...nextPageToken ? { nextPageToken } : {} });
5442
6063
  }
5443
6064
  if (path === GMAIL_SEND_AS) {
5444
6065
  if (method !== "GET" || Object.keys(params).length) return void 0;
5445
6066
  return ok(GMAIL_SEND_AS, { sendAs: rowsIn(data, GMAIL_SEND_AS).map((row) => structuredClone(row)) });
5446
6067
  }
6068
+ if (path === "/gmail/v1/users/me/settings/forwardingAddresses") {
6069
+ if (method !== "GET" || Object.keys(params).length) return void 0;
6070
+ return ok("/gmail/v1/users/me/settings/forwardingAddresses", { forwardingAddresses: rowsIn(data, "/gmail/v1/users/me/settings/forwardingAddresses").map((row) => structuredClone(row)) });
6071
+ }
6072
+ if (path === "/gmail/v1/users/me/settings/filters") {
6073
+ if (method === "GET") {
6074
+ if (Object.keys(params).length) return void 0;
6075
+ return ok("/gmail/v1/users/me/settings/filters", { filter: rowsIn(data, "/gmail/v1/users/me/settings/filters").map((row) => structuredClone(row)) });
6076
+ }
6077
+ if (method !== "POST") return void 0;
6078
+ if (Object.keys(params).some((k) => !["criteria", "action"].includes(k))) return void 0;
6079
+ const criteria = params.criteria, action = params.action;
6080
+ if (!isObject4(criteria) || !isObject4(action)) return googleError("/gmail/v1/users/me/settings/filters", 400, "criteria and action must be objects.");
6081
+ if (Object.keys(criteria).some((k) => !["from", "to", "subject", "query", "negatedQuery", "hasAttachment", "excludeChats", "size", "sizeComparison"].includes(k))) return void 0;
6082
+ if (Object.keys(action).some((k) => !["addLabelIds", "removeLabelIds", "forward"].includes(k))) return void 0;
6083
+ const filters = rowsIn(data, "/gmail/v1/users/me/settings/filters");
6084
+ const filter = { id: `Filter_${filters.length + 1}`, criteria: structuredClone(criteria), action: structuredClone(action) };
6085
+ filters.push(filter);
6086
+ return { status: 200, body: structuredClone(filter), collection: "/gmail/v1/users/me/settings/filters", operation: "write", record: filter };
6087
+ }
6088
+ const filterMatch = /^\/gmail\/v1\/users\/me\/settings\/filters\/([^/]+)$/.exec(path);
6089
+ if (filterMatch) {
6090
+ if (method !== "DELETE" || Object.keys(params).length) return void 0;
6091
+ const filters = rowsIn(data, "/gmail/v1/users/me/settings/filters");
6092
+ const index = filters.findIndex((f) => f.id === decodeURIComponent(filterMatch[1]));
6093
+ if (index < 0) return googleError("/gmail/v1/users/me/settings/filters", 404, "Requested entity was not found.");
6094
+ const [removed] = filters.splice(index, 1);
6095
+ return { status: 204, body: null, collection: "/gmail/v1/users/me/settings/filters", operation: "write", record: { id: removed.id, deleted: true } };
6096
+ }
5447
6097
  if (path === GMAIL_WATCH) {
5448
6098
  if (method !== "POST" || Object.keys(params).some((k) => !["topicName", "labelIds", "labelFilterBehavior", "labelFilterAction"].includes(k))) return void 0;
5449
6099
  if (typeof params.topicName !== "string" || !/^projects\/[^/]+\/topics\/[^/]+$/.test(params.topicName)) return googleError(GMAIL_WATCH, 400, "Invalid topicName: expected projects/<project>/topics/<topic>.");
@@ -5470,7 +6120,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5470
6120
  if (typeof params.id !== "string" || !params.id) return sendFail(400, "Draft id is required.");
5471
6121
  const drafts = rowsIn(data, GMAIL_DRAFTS), index = drafts.findIndex((d) => d.id === params.id);
5472
6122
  if (index < 0) return sendFail(404, "Requested entity was not found.");
5473
- const messages = rowsIn(data, MESSAGES), draft = drafts[index];
6123
+ const messages = rowsIn(data, MESSAGES2), draft = drafts[index];
5474
6124
  const message = messages.find((m) => m.id === draft.message.id);
5475
6125
  if (!message) return sendFail(404, "Requested entity was not found.");
5476
6126
  let update;
@@ -5490,7 +6140,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5490
6140
  if (!headerAddresses(payload.headers?.find((h) => h.name.toLowerCase() === "to")?.value).length) return sendFail(400, "Invalid To header: a sent draft needs at least one recipient.");
5491
6141
  drafts.splice(index, 1);
5492
6142
  Object.assign(message, update ? { payload: update.payload, snippet: update.snippet, sizeEstimate: update.bytes } : {}, { labelIds: ["SENT"], internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) });
5493
- return withPush(write2(200, MESSAGES, { id: message.id, threadId: message.threadId, labelIds: ["SENT"] }, { ...structuredClone(message), sentFromDraft: draft.id }), gmailPublish(data, ["SENT"], sequence));
6143
+ return withPush(write2(200, MESSAGES2, { id: message.id, threadId: message.threadId, labelIds: ["SENT"] }, { ...structuredClone(message), sentFromDraft: draft.id }), gmailPublish(data, ["SENT"], sequence));
5494
6144
  }
5495
6145
  const draftMatch = /^\/gmail\/v1\/users\/me\/drafts\/([^/]+)$/.exec(path);
5496
6146
  if (draftMatch) {
@@ -5499,7 +6149,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5499
6149
  if (method === "GET") {
5500
6150
  if (Object.keys(params).some((k) => k !== "format") || params.format !== void 0 && params.format !== "full") return void 0;
5501
6151
  if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
5502
- const draft = drafts[index], message = rowsIn(data, MESSAGES).find((m) => m.id === draft.message.id);
6152
+ const draft = drafts[index], message = rowsIn(data, MESSAGES2).find((m) => m.id === draft.message.id);
5503
6153
  return ok(GMAIL_DRAFTS, { id, message: structuredClone(message ?? draft.message) });
5504
6154
  }
5505
6155
  if (method === "PUT") {
@@ -5516,7 +6166,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5516
6166
  if (Object.keys(params).length) return void 0;
5517
6167
  if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
5518
6168
  const [removed] = drafts.splice(index, 1);
5519
- const messages = rowsIn(data, MESSAGES), messageIndex = messages.findIndex((m) => m.id === removed.message.id);
6169
+ const messages = rowsIn(data, MESSAGES2), messageIndex = messages.findIndex((m) => m.id === removed.message.id);
5520
6170
  if (messageIndex >= 0) messages.splice(messageIndex, 1);
5521
6171
  return { status: 204, body: null, collection: GMAIL_DRAFTS, record: { id, deleted: true, threadId: removed.threadId ?? null }, operation: "write" };
5522
6172
  }
@@ -5540,7 +6190,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5540
6190
  if (Object.keys(fields).some((k) => !["raw", "threadId"].includes(k))) return void 0;
5541
6191
  return gmailDraftWrite(data, fields.raw, fields.threadId, sequence);
5542
6192
  }
5543
- if (path === `${MESSAGES}/send`) {
6193
+ if (path === `${MESSAGES2}/send`) {
5544
6194
  if (method !== "POST") return void 0;
5545
6195
  if (Object.keys(params).some((k) => !["raw", "to", "subject", "text", "threadId"].includes(k))) return void 0;
5546
6196
  const text2 = str(params.text), raw2 = str(params.raw);
@@ -5556,17 +6206,17 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5556
6206
  const legacy = plain && !("error" in plain) ? plain : void 0;
5557
6207
  const mime = raw2 && !legacy ? parseGmailDraftRaw(raw2) : void 0;
5558
6208
  if (mime && "error" in mime) {
5559
- return mime.unsupported ? { status: 501, body: restUnsupportedBody("gmail"), collection: MESSAGES, unsupportedReason: mime.error } : fail(400, mime.error);
6209
+ return mime.unsupported ? { status: 501, body: restUnsupportedBody("gmail"), collection: MESSAGES2, unsupportedReason: mime.error } : fail(400, mime.error);
5560
6210
  }
5561
- if (mime && !headerAddresses(mime.headers.find((header3) => header3.name.toLowerCase() === "to")?.value).length) {
6211
+ if (mime && !headerAddresses(mime.headers.find((header4) => header4.name.toLowerCase() === "to")?.value).length) {
5562
6212
  return fail(400, "Invalid To header: a sent message needs at least one recipient.");
5563
6213
  }
5564
6214
  const body = legacy?.text ?? mime?.snippet ?? text2 ?? "";
5565
6215
  const message = { id: `gmail_at_${sequence}`, threadId: str(params.threadId) ?? `gmail_at_${sequence}`, labelIds: ["SENT"], snippet: body.slice(0, 100), payload: mime?.payload ?? { mimeType: "text/plain", headers: legacy?.headers ?? [{ name: "To", value: str(params.to) ?? "" }, { name: "Subject", value: str(params.subject) ?? "" }], body: { data: legacy?.encodedBody ?? body } }, sizeEstimate: mime?.bytes ?? body.length, internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) };
5566
- rowsIn(data, MESSAGES).push(message);
5567
- return withPush(write2(200, MESSAGES, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
6216
+ rowsIn(data, MESSAGES2).push(message);
6217
+ return withPush(write2(200, MESSAGES2, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
5568
6218
  }
5569
- if (path === MESSAGES && method === "POST") {
6219
+ if (path === MESSAGES2 && method === "POST") {
5570
6220
  if (Object.keys(params).some((k) => !["raw", "labelIds", "threadId", "internalDateSource"].includes(k))) return void 0;
5571
6221
  if (typeof params.raw !== "string" || !params.raw) return fail(400, "raw must be a base64url MIME string.");
5572
6222
  if (params.threadId !== void 0 && (typeof params.threadId !== "string" || !gmailThreadMessages(data, params.threadId).length)) return fail(404, "Requested entity was not found.");
@@ -5585,25 +6235,47 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5585
6235
  }
5586
6236
  const id = `gmail_insert_at_${sequence}`;
5587
6237
  const message = { id, threadId: params.threadId ?? id, labelIds, snippet: mime.snippet, payload: mime.payload, sizeEstimate: mime.bytes, internalDate: String(internalDate), historyId: String(17e8 + sequence) };
5588
- rowsIn(data, MESSAGES).push(message);
5589
- return withPush(write2(200, MESSAGES, { id, threadId: message.threadId, labelIds }, message), gmailPublish(data, labelIds, sequence));
6238
+ rowsIn(data, MESSAGES2).push(message);
6239
+ return withPush(write2(200, MESSAGES2, { id, threadId: message.threadId, labelIds }, message), gmailPublish(data, labelIds, sequence));
5590
6240
  }
5591
- if (path === MESSAGES) {
6241
+ if (path === MESSAGES2) {
5592
6242
  if (method !== "GET") return void 0;
5593
- if (Object.keys(params).some((k) => k !== "q")) return void 0;
5594
- let filtered = rowsIn(data, MESSAGES);
5595
- if (params.q !== void 0) {
5596
- if (typeof params.q !== "string") return fail(400, "q must be a string.");
5597
- filtered = filtered.filter((m) => typeof m.snippet === "string" && m.snippet.includes(params.q));
5598
- }
5599
- return ok(MESSAGES, { messages: filtered.map((m) => ({ id: m.id, threadId: m.threadId })), resultSizeEstimate: filtered.length });
6243
+ if (Object.keys(params).some((k) => !["q", "maxResults", "pageToken", "labelIds", "includeSpamTrash"].includes(k))) return void 0;
6244
+ if (params.q !== void 0 && typeof params.q !== "string") return fail(400, "q must be a string.");
6245
+ if (params.includeSpamTrash !== void 0 && !["true", "false", true, false].includes(params.includeSpamTrash)) return fail(400, "includeSpamTrash must be true or false.");
6246
+ const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
6247
+ if (!Number.isInteger(max) || max < 1 || max > 500) return fail(400, "maxResults must be an integer from 1 to 500.");
6248
+ const matcher = params.q === void 0 || params.q === "" ? () => true : gmailQueryMatcher(params.q);
6249
+ if (!matcher) return void 0;
6250
+ const labels = gmailLabelFilter(params), spamTrash = params.includeSpamTrash === true || params.includeSpamTrash === "true";
6251
+ const filtered = rowsIn(data, MESSAGES2).filter((message) => {
6252
+ const ids = Array.isArray(message.labelIds) ? message.labelIds : [];
6253
+ if (!spamTrash && (ids.includes("SPAM") || ids.includes("TRASH"))) return false;
6254
+ return labels.every((label2) => ids.includes(label2)) && matcher(message);
6255
+ });
6256
+ const offset = gmailPageOffset(params.pageToken, filtered.length);
6257
+ if (offset === void 0) return void 0;
6258
+ const page = filtered.slice(offset, offset + max);
6259
+ const nextPageToken = offset + max < filtered.length ? String(offset + max) : void 0;
6260
+ return ok(MESSAGES2, { messages: page.map((m) => ({ id: m.id, threadId: m.threadId })), resultSizeEstimate: filtered.length, ...nextPageToken ? { nextPageToken } : {} });
6261
+ }
6262
+ const attachmentMatch = /^\/gmail\/v1\/users\/me\/messages\/([^/]+)\/attachments\/([^/]+)$/.exec(path);
6263
+ if (attachmentMatch) {
6264
+ if (method !== "GET" || Object.keys(params).length) return void 0;
6265
+ const message = rowsIn(data, MESSAGES2).find((m) => m.id === decodeURIComponent(attachmentMatch[1]));
6266
+ const attachmentId = decodeURIComponent(attachmentMatch[2]);
6267
+ if (!message) return fail(404, "Requested entity was not found.");
6268
+ const collect = (part) => part.body?.attachmentId === attachmentId ? part : (part.parts ?? []).map((child) => collect(child)).find(Boolean);
6269
+ const found = collect(message.payload ?? {});
6270
+ if (!found?.body) return fail(404, `Attachment not found: ${attachmentId}`);
6271
+ return ok(MESSAGES2, { attachmentId, size: found.body.size ?? 0, data: found.body.data ?? "" });
5600
6272
  }
5601
6273
  const messageMatch = /^\/gmail\/v1\/users\/me\/messages\/([^/]+)$/.exec(path);
5602
6274
  if (messageMatch) {
5603
6275
  if (method !== "GET") return void 0;
5604
- const message = rowsIn(data, MESSAGES).find((m) => m.id === messageMatch[1]);
6276
+ const message = rowsIn(data, MESSAGES2).find((m) => m.id === messageMatch[1]);
5605
6277
  if (!message) return fail(404, `Message not found: ${messageMatch[1]}`);
5606
- return ok(MESSAGES, structuredClone(message));
6278
+ return ok(MESSAGES2, structuredClone(message));
5607
6279
  }
5608
6280
  const modifyMatch = /^\/gmail\/v1\/users\/me\/(messages|threads)\/([^/]+)\/modify$/.exec(path);
5609
6281
  if (modifyMatch) {
@@ -5614,9 +6286,9 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5614
6286
  const known2 = gmailLabelKnown(data), unknown = [...add, ...remove2].find((id2) => !known2(id2));
5615
6287
  if (unknown) return fail(400, `Invalid label: ${unknown}`);
5616
6288
  const id = decodeURIComponent(modifyMatch[2]);
5617
- const targets = modifyMatch[1] === "messages" ? rowsIn(data, MESSAGES).filter((m) => m.id === id) : rowsIn(data, MESSAGES).filter((m) => m.threadId === id);
6289
+ const targets = modifyMatch[1] === "messages" ? rowsIn(data, MESSAGES2).filter((m) => m.id === id) : rowsIn(data, MESSAGES2).filter((m) => m.threadId === id);
5618
6290
  if (!targets.length) return fail(404, `Requested entity was not found.`);
5619
- const next = String(BigInt(gmailHistoryId(rowsIn(data, MESSAGES))) + 1n);
6291
+ const next = String(BigInt(gmailHistoryId(rowsIn(data, MESSAGES2))) + 1n);
5620
6292
  for (const message of targets) {
5621
6293
  const labels = new Set(message.labelIds ?? []);
5622
6294
  for (const l of add) labels.add(l);
@@ -5625,7 +6297,46 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5625
6297
  message.historyId = next;
5626
6298
  }
5627
6299
  const body = modifyMatch[1] === "messages" ? structuredClone(targets[0]) : { id, historyId: next, messages: targets.map((m) => structuredClone(m)) };
5628
- return { status: 200, body, collection: MESSAGES, operation: "write", record: { id, addLabelIds: add, removeLabelIds: remove2 } };
6300
+ return { status: 200, body, collection: MESSAGES2, operation: "write", record: { id, addLabelIds: add, removeLabelIds: remove2 } };
6301
+ }
6302
+ const labelMatch = /^\/gmail\/v1\/users\/me\/labels\/([^/]+)$/.exec(path);
6303
+ if (labelMatch) {
6304
+ const id = decodeURIComponent(labelMatch[1]), labels = rowsIn(data, LABELS);
6305
+ const index = labels.findIndex((l) => l.id === id);
6306
+ const system = GMAIL_SYSTEM_LABEL_NAMES.has(String(id).toUpperCase()) || id.startsWith("CATEGORY_");
6307
+ if (method === "GET") {
6308
+ if (Object.keys(params).length) return void 0;
6309
+ if (index < 0) return googleError(LABELS, 404, "Requested entity was not found.");
6310
+ return ok(LABELS, structuredClone(labels[index]));
6311
+ }
6312
+ if (method === "PATCH" || method === "PUT") {
6313
+ if (Object.keys(params).some((k) => !["name", "labelListVisibility", "messageListVisibility", "color"].includes(k))) return void 0;
6314
+ if (index < 0) {
6315
+ if (system) return googleError(LABELS, 400, "Invalid label: system labels cannot be modified.");
6316
+ return googleError(LABELS, 404, "Requested entity was not found.");
6317
+ }
6318
+ if (system) return googleError(LABELS, 400, "Invalid label: system labels cannot be modified.");
6319
+ if (params.name !== void 0) {
6320
+ if (typeof params.name !== "string" || !params.name.trim()) return googleError(LABELS, 400, "Invalid label name");
6321
+ if (labels.some((l, i) => i !== index && String(l.name).toLowerCase() === String(params.name).toLowerCase())) return googleError(LABELS, 409, "Label name exists or conflicts");
6322
+ }
6323
+ if (params.color !== void 0 && (!isObject4(params.color) || Object.keys(params.color).some((k) => !["backgroundColor", "textColor"].includes(k)))) return googleError(LABELS, 400, "Invalid color.");
6324
+ const updated = method === "PUT" ? { id, name: params.name ?? labels[index].name, type: "user", labelListVisibility: params.labelListVisibility ?? labels[index].labelListVisibility ?? "labelShow", messageListVisibility: params.messageListVisibility ?? labels[index].messageListVisibility ?? "show", ...params.color !== void 0 ? { color: params.color } : {} } : { ...labels[index], ...Object.fromEntries(Object.entries(params).filter(([, v]) => v !== void 0)) };
6325
+ labels.splice(index, 1, updated);
6326
+ return { status: 200, body: structuredClone(updated), collection: LABELS, operation: "write", record: updated };
6327
+ }
6328
+ if (method === "DELETE") {
6329
+ if (Object.keys(params).length) return void 0;
6330
+ if (system) return googleError(LABELS, 400, "Invalid label: system labels cannot be deleted.");
6331
+ if (index < 0) return googleError(LABELS, 404, "Requested entity was not found.");
6332
+ const [removed] = labels.splice(index, 1);
6333
+ for (const message of rowsIn(data, MESSAGES2)) {
6334
+ const ids = message.labelIds;
6335
+ if (Array.isArray(ids) && ids.includes(id)) message.labelIds = ids.filter((l) => l !== id);
6336
+ }
6337
+ return { status: 204, body: null, collection: LABELS, operation: "write", record: { id, deleted: true, name: removed.name } };
6338
+ }
6339
+ return void 0;
5629
6340
  }
5630
6341
  if (path === LABELS) {
5631
6342
  if (method === "POST") {
@@ -5645,8 +6356,8 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5645
6356
  }
5646
6357
  var GMAIL_SYSTEM_LABEL_NAMES = /* @__PURE__ */ new Set(["INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT", "CHAT"]);
5647
6358
  function googleCalendarOperation(method, path, params, _headers, data, sequence) {
5648
- const CALENDAR_LIST = "/calendar/v3/users/me/calendarList", EVENTS = "/calendar/v3/calendars/primary/events";
5649
- const fail = (status, message) => googleError(EVENTS, status, message);
6359
+ const CALENDAR_LIST = "/calendar/v3/users/me/calendarList", EVENTS3 = "/calendar/v3/calendars/primary/events";
6360
+ const fail = (status, message) => googleError(EVENTS3, status, message);
5650
6361
  if (path === CALENDAR_LIST) {
5651
6362
  if (method !== "GET") return void 0;
5652
6363
  if (Object.keys(params).length) return void 0;
@@ -5655,9 +6366,9 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5655
6366
  const match = /^\/calendar\/v3\/calendars\/([^/]+)\/events(?:\/([^/]+))?$/.exec(path);
5656
6367
  if (!match) return void 0;
5657
6368
  const [, calendar, eventId] = match;
5658
- if (calendar !== "primary") return googleError(EVENTS, 404, `Not Found: no twin state for calendar ${calendar}`);
6369
+ if (calendar !== "primary") return googleError(EVENTS3, 404, `Not Found: no twin state for calendar ${calendar}`);
5659
6370
  const scalar2 = (value) => ["summary", "description", "location"].filter((k) => params[k] !== void 0 && str(params[k]) === void 0);
5660
- const meetingField = (value) => value !== void 0 && !Array.isArray(value) && !isObject2(value);
6371
+ const meetingField = (value) => value !== void 0 && !Array.isArray(value) && !isObject4(value);
5661
6372
  if (!eventId) {
5662
6373
  if (method === "GET") {
5663
6374
  const allowed = ["timeMin", "timeMax", "maxResults", "pageToken", "singleEvents", "orderBy", "conferenceDataVersion"];
@@ -5675,10 +6386,10 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5675
6386
  if (Number.isNaN(lower) || Number.isNaN(upper) || lower >= upper) return fail(400, "Invalid time range.");
5676
6387
  const limit = params.maxResults === void 0 ? 250 : boundedInt(params.maxResults, 1, 2500);
5677
6388
  if (limit === null) return fail(400, "Invalid maxResults.");
5678
- let events = rowsIn(data, EVENTS).filter((row) => row.status !== "cancelled");
6389
+ let events = rowsIn(data, EVENTS3).filter((row) => row.status !== "cancelled");
5679
6390
  if (events.some((row) => row.recurrence || row.recurringEventId || row.conferenceData)) return void 0;
5680
6391
  const timed = params.timeMin !== void 0 || params.timeMax !== void 0 || params.orderBy !== void 0;
5681
- if (timed && events.some((row) => !isObject2(row.start) || !isObject2(row.end) || !Number.isFinite(timestamp(row.start.dateTime)) || !Number.isFinite(timestamp(row.end.dateTime)))) return void 0;
6392
+ if (timed && events.some((row) => !isObject4(row.start) || !isObject4(row.end) || !Number.isFinite(timestamp(row.start.dateTime)) || !Number.isFinite(timestamp(row.end.dateTime)))) return void 0;
5682
6393
  if (timed) events = events.filter((row) => timestamp(row.end.dateTime) > lower && timestamp(row.start.dateTime) < upper);
5683
6394
  if (params.orderBy === "startTime") events = [...events].sort((a, b) => timestamp(a.start.dateTime) - timestamp(b.start.dateTime));
5684
6395
  const query = Object.fromEntries(Object.entries(params).filter(([key2]) => key2 !== "pageToken").sort(([a], [b]) => a.localeCompare(b)));
@@ -5691,7 +6402,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5691
6402
  offset = Number(token[2]);
5692
6403
  }
5693
6404
  const next = offset + (limit ?? 250);
5694
- return ok(EVENTS, { items: structuredClone(events.slice(offset, next)), ...next < events.length ? { nextPageToken: `at_${fingerprint}_${next}` } : {} });
6405
+ return ok(EVENTS3, { items: structuredClone(events.slice(offset, next)), ...next < events.length ? { nextPageToken: `at_${fingerprint}_${next}` } : {} });
5695
6406
  }
5696
6407
  if (method !== "POST") return void 0;
5697
6408
  if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
@@ -5699,13 +6410,13 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5699
6410
  if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
5700
6411
  const scalarBad = scalar2(params);
5701
6412
  if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
5702
- const event2 = { id: detUuid(`gcal:${sequence}`), summary: params.summary, description: str(params.description) ?? null, location: str(params.location) ?? null, start: isObject2(params.start) ? structuredClone(params.start) : { dateTime: iso2() }, end: isObject2(params.end) ? structuredClone(params.end) : { dateTime: iso2() }, attendees: Array.isArray(params.attendees) ? structuredClone(params.attendees) : [], status: str(params.status) ?? "confirmed", htmlLink: null, creator: { email: "agenttwin@example.test", self: true }, created: iso2(), updated: iso2() };
5703
- rowsIn(data, EVENTS).push(event2);
5704
- return write2(200, EVENTS, structuredClone(event2), event2);
6413
+ const event2 = { id: detUuid(`gcal:${sequence}`), summary: params.summary, description: str(params.description) ?? null, location: str(params.location) ?? null, start: isObject4(params.start) ? structuredClone(params.start) : { dateTime: iso2() }, end: isObject4(params.end) ? structuredClone(params.end) : { dateTime: iso2() }, attendees: Array.isArray(params.attendees) ? structuredClone(params.attendees) : [], status: str(params.status) ?? "confirmed", htmlLink: null, creator: { email: "agenttwin@example.test", self: true }, created: iso2(), updated: iso2() };
6414
+ rowsIn(data, EVENTS3).push(event2);
6415
+ return write2(200, EVENTS3, structuredClone(event2), event2);
5705
6416
  }
5706
- const event = rowsIn(data, EVENTS).find((e) => e.id === eventId);
6417
+ const event = rowsIn(data, EVENTS3).find((e) => e.id === eventId);
5707
6418
  if (!event) return fail(404, `Not Found: event ${eventId}`);
5708
- if (method === "GET") return ok(EVENTS, structuredClone(event));
6419
+ if (method === "GET") return ok(EVENTS3, structuredClone(event));
5709
6420
  if (method === "PATCH") {
5710
6421
  if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
5711
6422
  if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
@@ -5713,23 +6424,23 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5713
6424
  if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
5714
6425
  for (const [k, v] of Object.entries(params)) if (["summary", "description", "location", "start", "end", "attendees", "status"].includes(k)) event[k] = structuredClone(v);
5715
6426
  event.updated = iso2();
5716
- return write2(200, EVENTS, structuredClone(event), event);
6427
+ return write2(200, EVENTS3, structuredClone(event), event);
5717
6428
  }
5718
6429
  if (method === "DELETE") {
5719
- rowsIn(data, EVENTS).splice(rowsIn(data, EVENTS).findIndex((e) => e.id === eventId), 1);
5720
- return write2(200, EVENTS, {}, structuredClone(event));
6430
+ rowsIn(data, EVENTS3).splice(rowsIn(data, EVENTS3).findIndex((e) => e.id === eventId), 1);
6431
+ return write2(200, EVENTS3, {}, structuredClone(event));
5721
6432
  }
5722
6433
  return void 0;
5723
6434
  }
5724
6435
  function gitlabOperation(method, path, params, _headers, data, sequence) {
5725
6436
  const match = /^\/api\/v4\/(projects|issues|merge_requests)(?:\/(\d+))?(?:\/(notes)(?:\/(\d+))?)?$/.exec(path);
5726
6437
  if (!match) return void 0;
5727
- const [, resource, id, sub] = match;
5728
- const collection = sub === "notes" ? "/api/v4/merge_requests/notes" : `/api/v4/${resource}`;
6438
+ const [, resource2, id, sub] = match;
6439
+ const collection = sub === "notes" ? "/api/v4/merge_requests/notes" : `/api/v4/${resource2}`;
5729
6440
  const records = rowsIn(data, collection);
5730
6441
  const author = { id: 42, username: "agenttwin-test", name: "AgentTwin Test" };
5731
6442
  if (sub === "notes") {
5732
- if (!id || !resource) return void 0;
6443
+ if (!id || !resource2) return void 0;
5733
6444
  const mr = rowsIn(data, "/api/v4/merge_requests").find((r) => String(r.iid) === id || String(r.id) === id);
5734
6445
  if (!mr) return notFound(collection, { message: "404 Merge Request Not Found" });
5735
6446
  if (method === "GET") return ok(collection, records.filter((n) => n.noteable_iid === mr.iid).map((row) => structuredClone(row)));
@@ -5745,7 +6456,7 @@ function gitlabOperation(method, path, params, _headers, data, sequence) {
5745
6456
  return ok(collection, records.map((row) => structuredClone(row)));
5746
6457
  }
5747
6458
  if (method === "POST" && !id) {
5748
- if (resource === "projects") {
6459
+ if (resource2 === "projects") {
5749
6460
  if (Object.keys(params).some((k) => !["name", "description", "visibility"].includes(k))) return void 0;
5750
6461
  if (typeof params.name !== "string" || !params.name) return badRequest(collection, { message: "name is missing" });
5751
6462
  if (params.description !== void 0 && str(params.description) === void 0) return void 0;
@@ -5753,7 +6464,7 @@ function gitlabOperation(method, path, params, _headers, data, sequence) {
5753
6464
  records.push(project);
5754
6465
  return created(collection, structuredClone(project), project);
5755
6466
  }
5756
- if (resource === "issues") {
6467
+ if (resource2 === "issues") {
5757
6468
  if (Object.keys(params).some((k) => !["title", "description", "project_id", "labels", "assignee_ids"].includes(k))) return void 0;
5758
6469
  const projectId2 = Number(params.project_id);
5759
6470
  if (typeof params.title !== "string" || !params.title || !Number.isInteger(projectId2)) return badRequest(collection, { message: "title and project_id are required" });
@@ -5773,8 +6484,8 @@ function gitlabOperation(method, path, params, _headers, data, sequence) {
5773
6484
  records.push(mergeRequest);
5774
6485
  return created(collection, structuredClone(mergeRequest), mergeRequest);
5775
6486
  }
5776
- const primary = id ? rowsIn(data, `/api/v4/${resource}`).find((r) => String(r.id) === id || String(r.iid) === id) : void 0;
5777
- if (!primary) return id ? notFound(collection, { message: `404 ${resource === "merge_requests" ? "Merge Request" : resource.slice(0, -1)} Not Found` }) : void 0;
6487
+ const primary = id ? rowsIn(data, `/api/v4/${resource2}`).find((r) => String(r.id) === id || String(r.iid) === id) : void 0;
6488
+ if (!primary) return id ? notFound(collection, { message: `404 ${resource2 === "merge_requests" ? "Merge Request" : resource2.slice(0, -1)} Not Found` }) : void 0;
5778
6489
  if (method === "GET") return ok(collection, structuredClone(primary));
5779
6490
  return void 0;
5780
6491
  }
@@ -5798,11 +6509,11 @@ function jiraOperation(method, path, params, _headers, data, sequence) {
5798
6509
  }
5799
6510
  if (path === ISSUE) {
5800
6511
  if (method !== "POST") return void 0;
5801
- if (Object.keys(params).some((k) => k !== "fields") || !isObject2(params.fields)) return jiraFail(ISSUE, [], { fields: "fields is required" });
6512
+ if (Object.keys(params).some((k) => k !== "fields") || !isObject4(params.fields)) return jiraFail(ISSUE, [], { fields: "fields is required" });
5802
6513
  const fields = params.fields;
5803
6514
  if (Object.keys(fields).some((k) => !["project", "issuetype", "summary", "description", "priority", "labels", "assignee"].includes(k))) return void 0;
5804
- const projectKey = isObject2(fields.project) ? str(fields.project.key) : void 0;
5805
- const issuetype = isObject2(fields.issuetype) ? str(fields.issuetype.name) : void 0;
6515
+ const projectKey = isObject4(fields.project) ? str(fields.project.key) : void 0;
6516
+ const issuetype = isObject4(fields.issuetype) ? str(fields.issuetype.name) : void 0;
5806
6517
  if (!projectKey || !issuetype || typeof fields.summary !== "string" || !fields.summary) return jiraFail(ISSUE, [], { summary: projectKey && issuetype ? "Summary is required." : `${!projectKey ? "project key" : "issuetype name"} and summary are required.` });
5807
6518
  if (!rowsIn(data, PROJECT).some((p) => p.key === projectKey)) return jiraFail(ISSUE, [`Project '${projectKey}' does not exist.`], {});
5808
6519
  const issueRows = rowsIn(data, ISSUE);
@@ -5818,15 +6529,15 @@ function jiraOperation(method, path, params, _headers, data, sequence) {
5818
6529
  if (method === "GET" && !issueMatch[2]) return ok(ISSUE, structuredClone(issue));
5819
6530
  if (method === "POST" && issueMatch[2] === "comment") {
5820
6531
  if (Object.keys(params).some((k) => k !== "body")) return void 0;
5821
- if (typeof params.body !== "string" && !isObject2(params.body)) return jiraFail(ISSUE, [], { body: "body is required" });
5822
- if (isObject2(params.body) && params.body.type !== "doc") return jiraFail(ISSUE, [], { body: "Comment bodies must be Atlassian Document Format objects with type 'doc', or plain strings." });
6532
+ if (typeof params.body !== "string" && !isObject4(params.body)) return jiraFail(ISSUE, [], { body: "body is required" });
6533
+ if (isObject4(params.body) && params.body.type !== "doc") return jiraFail(ISSUE, [], { body: "Comment bodies must be Atlassian Document Format objects with type 'doc', or plain strings." });
5823
6534
  const commentRows = rowsIn(data, "/rest/api/3/issue/comments");
5824
6535
  const comment = { id: uniqueId(commentRows, 101 + sequence), issueKey: issue.key, author: { accountId: "agenttwin-test-account", displayName: "AgentTwin Test" }, created: iso2(), updated: iso2(), body: structuredClone(params.body) };
5825
6536
  commentRows.push(comment);
5826
6537
  return created("/rest/api/3/issue/comments", structuredClone(comment), comment);
5827
6538
  }
5828
6539
  if (method === "POST" && issueMatch[2] === "transitions") {
5829
- if (Object.keys(params).some((k) => !["transition", "fields"].includes(k)) || !isObject2(params.transition) || Object.keys(params.transition).some((k) => k !== "id")) return void 0;
6540
+ if (Object.keys(params).some((k) => !["transition", "fields"].includes(k)) || !isObject4(params.transition) || Object.keys(params.transition).some((k) => k !== "id")) return void 0;
5830
6541
  const transitionId = str(params.transition.id);
5831
6542
  if (!transitionId) return void 0;
5832
6543
  if (!JIRA_TRANSITIONS[transitionId]) return jiraFail(ISSUE, [], { transition: "Transition id must be one of 11, 21, 31" });
@@ -5851,12 +6562,12 @@ function jiraOperation(method, path, params, _headers, data, sequence) {
5851
6562
  }
5852
6563
  var discordError = (collection, code, message) => ({ status: code === 10003 || code === 10004 ? 404 : 400, body: { message, code }, collection });
5853
6564
  function discordOperation(method, path, params, _headers, data, sequence) {
5854
- const CHANNELS = "/api/channels", MESSAGES = "/api/channels/messages", GUILDS = "/api/guilds", MEMBERS = "/api/guilds/members";
6565
+ const CHANNELS = "/api/channels", MESSAGES2 = "/api/channels/messages", GUILDS = "/api/guilds", MEMBERS = "/api/guilds/members";
5855
6566
  const channelMatch = /^\/api\/channels\/([^/]+)(?:\/(messages)(?:\/([^/]+))?)?$/.exec(path);
5856
6567
  if (channelMatch) {
5857
6568
  const [, channelId, messages, messageId] = channelMatch;
5858
6569
  const channel = rowsIn(data, CHANNELS).find((c) => c.id === channelId);
5859
- if (!channel) return discordError(MESSAGES, 10003, "Unknown Channel");
6570
+ if (!channel) return discordError(MESSAGES2, 10003, "Unknown Channel");
5860
6571
  if (!messages) {
5861
6572
  if (method !== "GET") return void 0;
5862
6573
  return ok(CHANNELS, structuredClone(channel));
@@ -5864,15 +6575,15 @@ function discordOperation(method, path, params, _headers, data, sequence) {
5864
6575
  if (messageId || method !== "GET" && method !== "POST") return void 0;
5865
6576
  if (method === "GET") {
5866
6577
  if (Object.keys(params).length) return void 0;
5867
- return ok(MESSAGES, rowsIn(data, MESSAGES).filter((m) => m.channel_id === channelId).map((row) => structuredClone(row)).reverse());
6578
+ return ok(MESSAGES2, rowsIn(data, MESSAGES2).filter((m) => m.channel_id === channelId).map((row) => structuredClone(row)).reverse());
5868
6579
  }
5869
6580
  if (Object.keys(params).some((k) => !["content", "tts"].includes(k))) return void 0;
5870
- if (typeof params.content !== "string" || !params.content) return discordError(MESSAGES, 50035, "Invalid Form Body: content cannot be empty.");
6581
+ if (typeof params.content !== "string" || !params.content) return discordError(MESSAGES2, 50035, "Invalid Form Body: content cannot be empty.");
5871
6582
  if (params.tts !== void 0 && typeof params.tts !== "boolean") return void 0;
5872
- const records = rowsIn(data, MESSAGES);
6583
+ const records = rowsIn(data, MESSAGES2);
5873
6584
  const message = { id: String(uniqueId(records, 11e14 + sequence)), channel_id: channelId, content: params.content, author: { id: "discord_at_agenttwin", username: "agenttwin-test", avatar: null }, timestamp: iso2(), tts: params.tts === true, embeds: [], pinned: false, type: 0 };
5874
6585
  records.push(message);
5875
- return created(MESSAGES, structuredClone(message), message);
6586
+ return created(MESSAGES2, structuredClone(message), message);
5876
6587
  }
5877
6588
  const guildMatch = /^\/api\/guilds\/([^/]+)(?:\/(members))?$/.exec(path);
5878
6589
  if (guildMatch) {
@@ -5894,8 +6605,8 @@ function discordOperation(method, path, params, _headers, data, sequence) {
5894
6605
  function twilioOperation(method, path, params, _headers, data, sequence) {
5895
6606
  const match = /^\/2010-04-01\/Accounts\/([^/]+)\/(Messages|Calls)(?:\.json)?$/.exec(path);
5896
6607
  if (!match) return void 0;
5897
- const [, accountSid, resource] = match;
5898
- const collection = `/2010-04-01/${resource}`;
6608
+ const [, accountSid, resource2] = match;
6609
+ const collection = `/2010-04-01/${resource2}`;
5899
6610
  const records = rowsIn(data, collection);
5900
6611
  const fail = (status, code, message) => ({ status, body: { status, code, message, more_info: "" }, collection });
5901
6612
  const stamp2 = () => {
@@ -5903,13 +6614,13 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
5903
6614
  return `${date} ${time.slice(0, 8)}`;
5904
6615
  };
5905
6616
  if (method === "POST") {
5906
- const allowed = resource === "Messages" ? ["To", "From", "Body"] : ["To", "From", "Url"];
6617
+ const allowed = resource2 === "Messages" ? ["To", "From", "Body"] : ["To", "From", "Url"];
5907
6618
  if (!accountSid || Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
5908
6619
  const missing = allowed.filter((k) => typeof params[k] !== "string" || !params[k]);
5909
6620
  if (missing.length) return fail(400, missing.length === allowed.length ? "21211" : "21606", `No parameter provided for ${allowed.filter((k) => missing.includes(k)).join(", ")}`);
5910
- const prefix = resource === "Messages" ? "SM" : "CA";
6621
+ const prefix = resource2 === "Messages" ? "SM" : "CA";
5911
6622
  const sid = `${prefix}${sha(`${prefix.toLowerCase()}:${sequence}:${accountSid}`).slice(0, 32)}`;
5912
- const record3 = resource === "Messages" ? { account_sid: accountSid, api_version: "2010-04-01", sid, messaging_service_sid: null, status: "queued", to: params.To, from: params.From, body: params.Body, num_segments: "1", num_media: "0", direction: "outbound-api", error_code: null, error_message: null, date_created: stamp2(), date_updated: stamp2(), date_sent: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Messages/${sid}.json` } : { account_sid: accountSid, api_version: "2010-04-01", sid, status: "queued", to: params.To, from: params.From, url: params.Url, direction: "outbound-api", error_code: null, error_message: null, date_created: stamp2(), date_updated: stamp2(), start_time: null, duration: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Calls/${sid}.json` };
6623
+ const record3 = resource2 === "Messages" ? { account_sid: accountSid, api_version: "2010-04-01", sid, messaging_service_sid: null, status: "queued", to: params.To, from: params.From, body: params.Body, num_segments: "1", num_media: "0", direction: "outbound-api", error_code: null, error_message: null, date_created: stamp2(), date_updated: stamp2(), date_sent: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Messages/${sid}.json` } : { account_sid: accountSid, api_version: "2010-04-01", sid, status: "queued", to: params.To, from: params.From, url: params.Url, direction: "outbound-api", error_code: null, error_message: null, date_created: stamp2(), date_updated: stamp2(), start_time: null, duration: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Calls/${sid}.json` };
5913
6624
  records.push(record3);
5914
6625
  return created(collection, structuredClone(record3), record3);
5915
6626
  }
@@ -5924,7 +6635,7 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
5924
6635
  if (typeof params.From !== "string") return fail(400, "20001", "From must be a string");
5925
6636
  filtered = filtered.filter((r) => r.from === params.From);
5926
6637
  }
5927
- return ok(collection, { page: 0, page_size: filtered.length, start: 0, end: Math.max(filtered.length - 1, 0), next_page_uri: null, [resource.toLowerCase()]: filtered.map((row) => structuredClone(row)) });
6638
+ return ok(collection, { page: 0, page_size: filtered.length, start: 0, end: Math.max(filtered.length - 1, 0), next_page_uri: null, [resource2.toLowerCase()]: filtered.map((row) => structuredClone(row)) });
5928
6639
  }
5929
6640
  return void 0;
5930
6641
  }
@@ -5932,19 +6643,19 @@ var ZENDESK_STATUSES = ["new", "open", "pending", "solved", "closed"];
5932
6643
  function zendeskOperation(method, path, params, _headers, data, sequence) {
5933
6644
  const match = /^\/api\/v2\/(tickets|users|organizations)(?:\/(\d+))?\.json$/.exec(path);
5934
6645
  if (!match) return void 0;
5935
- const [, resource, id] = match;
5936
- const collection = `/api/v2/${resource}`;
6646
+ const [, resource2, id] = match;
6647
+ const collection = `/api/v2/${resource2}`;
5937
6648
  const records = rowsIn(data, collection);
5938
- const envelope = (items) => ({ [resource]: items, next_page: null, previous_page: null, count: items.length });
6649
+ const envelope = (items) => ({ [resource2]: items, next_page: null, previous_page: null, count: items.length });
5939
6650
  if (method === "POST" && !id) {
5940
- if (resource !== "tickets") return void 0;
5941
- if (Object.keys(params).some((k) => k !== "ticket") || !isObject2(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
6651
+ if (resource2 !== "tickets") return void 0;
6652
+ if (Object.keys(params).some((k) => k !== "ticket") || !isObject4(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
5942
6653
  const ticketParams = params.ticket;
5943
6654
  if (Object.keys(ticketParams).some((k) => !["subject", "comment", "requester", "status", "priority", "tags", "description", "type"].includes(k))) return void 0;
5944
6655
  if (typeof ticketParams.subject !== "string" || !ticketParams.subject) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: Subject can't be blank" });
5945
- if (!isObject2(ticketParams.comment) || Object.keys(ticketParams.comment).some((k) => k !== "body") || typeof ticketParams.comment.body !== "string" || !ticketParams.comment.body) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: comment body is required" });
6656
+ if (!isObject4(ticketParams.comment) || Object.keys(ticketParams.comment).some((k) => k !== "body") || typeof ticketParams.comment.body !== "string" || !ticketParams.comment.body) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: comment body is required" });
5946
6657
  if (ticketParams.status !== void 0 && !ZENDESK_STATUSES.includes(String(ticketParams.status))) return badRequest(collection, { error: "InvalidStatus", description: "Status must be new, open, pending, solved or closed" });
5947
- const ticket = { id: uniqueId(records, 1 + sequence), subject: ticketParams.subject, description: str(ticketParams.description) ?? ticketParams.comment.body, status: str(ticketParams.status) ?? "new", priority: str(ticketParams.priority) ?? "normal", tags: Array.isArray(ticketParams.tags) ? structuredClone(ticketParams.tags) : [], requester: isObject2(ticketParams.requester) ? structuredClone(ticketParams.requester) : null, created_at: iso2(), updated_at: iso2() };
6658
+ const ticket = { id: uniqueId(records, 1 + sequence), subject: ticketParams.subject, description: str(ticketParams.description) ?? ticketParams.comment.body, status: str(ticketParams.status) ?? "new", priority: str(ticketParams.priority) ?? "normal", tags: Array.isArray(ticketParams.tags) ? structuredClone(ticketParams.tags) : [], requester: isObject4(ticketParams.requester) ? structuredClone(ticketParams.requester) : null, created_at: iso2(), updated_at: iso2() };
5948
6659
  records.push(ticket);
5949
6660
  return created(collection, { ticket: structuredClone(ticket), audit: null }, ticket);
5950
6661
  }
@@ -5952,15 +6663,15 @@ function zendeskOperation(method, path, params, _headers, data, sequence) {
5952
6663
  if (Object.keys(params).length) return void 0;
5953
6664
  return ok(collection, envelope(records));
5954
6665
  }
5955
- if (method === "GET" && id && resource === "tickets") {
6666
+ if (method === "GET" && id && resource2 === "tickets") {
5956
6667
  const ticket = records.find((r) => String(r.id) === id);
5957
6668
  if (!ticket) return notFound(collection, { error: "RecordNotFound", description: `Not found: ${id}` });
5958
6669
  return ok(collection, { ticket: structuredClone(ticket) });
5959
6670
  }
5960
- if (method === "PUT" && id && resource === "tickets") {
6671
+ if (method === "PUT" && id && resource2 === "tickets") {
5961
6672
  const ticket = typeof id === "string" ? records.find((r) => String(r.id) === id) : void 0;
5962
6673
  if (!ticket) return notFound(collection, { error: "RecordNotFound", description: `Not found: ${id}` });
5963
- if (Object.keys(params).some((k) => k !== "ticket") || !isObject2(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
6674
+ if (Object.keys(params).some((k) => k !== "ticket") || !isObject4(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
5964
6675
  const ticketParams = params.ticket;
5965
6676
  if (Object.keys(ticketParams).some((k) => !["subject", "status", "priority", "tags"].includes(k))) return void 0;
5966
6677
  if (ticketParams.status !== void 0 && !ZENDESK_STATUSES.includes(String(ticketParams.status))) return badRequest(collection, { error: "InvalidStatus", description: "Status must be new, open, pending, solved or closed" });
@@ -5989,7 +6700,11 @@ var UNSUPPORTED_BODIES = {
5989
6700
  openai: { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the AgentTwin scripted OpenAI subset, or no scripted response is left" }, forwardedToProduction: false },
5990
6701
  anthropic: { type: "error", error: { type: "invalid_request_error", message: "Outside the AgentTwin scripted Anthropic subset, or no scripted response is left" }, forwardedToProduction: false },
5991
6702
  zendesk: { error: "UnsupportedOperation", description: "Outside the verified AgentTwin Zendesk twin subset", forwardedToProduction: false },
5992
- "upstash-redis": { error: "ERR outside the verified AgentTwin Upstash Redis twin subset", forwardedToProduction: false }
6703
+ "upstash-redis": { error: "ERR outside the verified AgentTwin Upstash Redis twin subset", forwardedToProduction: false },
6704
+ posthog: { status: 0, error: "Outside the verified AgentTwin PostHog twin subset", forwardedToProduction: false },
6705
+ tinybird: { error: "Outside the verified AgentTwin Tinybird twin subset", documentation: "https://www.tinybird.co/docs/api-reference", forwardedToProduction: false },
6706
+ lemonsqueezy: { errors: [{ status: "501", title: "Unsupported Operation", detail: "Outside the verified AgentTwin Lemon Squeezy twin subset" }], forwardedToProduction: false },
6707
+ qstash: { error: "Outside the verified AgentTwin QStash twin subset", forwardedToProduction: false }
5993
6708
  };
5994
6709
  var REST_ADAPTERS = {
5995
6710
  openai: openaiOperation,
@@ -6009,7 +6724,11 @@ var REST_ADAPTERS = {
6009
6724
  zendesk: zendeskOperation,
6010
6725
  "google-oauth": googleOAuthOperation,
6011
6726
  composio: composioOperation,
6012
- "upstash-redis": upstashRedisOperation
6727
+ "upstash-redis": upstashRedisOperation,
6728
+ posthog: posthogOperation,
6729
+ tinybird: tinybirdOperation,
6730
+ lemonsqueezy: lemonsqueezyOperation,
6731
+ qstash: qstashOperation
6013
6732
  };
6014
6733
  function restUnsupportedBody(adapter) {
6015
6734
  return UNSUPPORTED_BODIES[adapter];
@@ -6110,11 +6829,11 @@ var PostgrestLayer = class _PostgrestLayer {
6110
6829
  return clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
6111
6830
  }
6112
6831
  async handle(request) {
6113
- const header3 = (name) => {
6832
+ const header4 = (name) => {
6114
6833
  const v = request.headers[name];
6115
6834
  return Array.isArray(v) ? v.join(",") : v ?? "";
6116
6835
  };
6117
- const prefer = header3("prefer"), single = /vnd\.pgrst\.object/.test(header3("accept"));
6836
+ const prefer = header4("prefer"), single = /vnd\.pgrst\.object/.test(header4("accept"));
6118
6837
  const reply = (status, body, extra = {}) => ({ status, headers: { "content-type": "application/json; charset=utf-8", ...extra }, body: body === void 0 ? "" : JSON.stringify(body) });
6119
6838
  const segments = request.url.pathname.replace(/^\/rest\/v1\/?/, "").split("/").filter(Boolean).map(decodeURIComponent);
6120
6839
  if (!segments.length) return reply(404, { code: "PGRST125", message: "Invalid path specified in request URL" });
@@ -6133,8 +6852,8 @@ var PostgrestLayer = class _PostgrestLayer {
6133
6852
  return `${ident2(k)} => $${i + 1}`;
6134
6853
  });
6135
6854
  const r = await this.pool.query(`SELECT to_json(f) AS v FROM ${ident2(segments[1])}(${list2.join(", ")}) f`, values);
6136
- const rows3 = r.rows.map((x) => x.v);
6137
- return reply(200, rows3.length === 1 && (typeof rows3[0] !== "object" || rows3[0] === null || !Array.isArray(rows3[0])) && r.fields.length === 1 && r.rowCount === 1 && single ? rows3[0] : rows3.length === 1 && typeof rows3[0] !== "object" ? rows3[0] : rows3);
6855
+ const rows7 = r.rows.map((x) => x.v);
6856
+ return reply(200, rows7.length === 1 && (typeof rows7[0] !== "object" || rows7[0] === null || !Array.isArray(rows7[0])) && r.fields.length === 1 && r.rowCount === 1 && single ? rows7[0] : rows7.length === 1 && typeof rows7[0] !== "object" ? rows7[0] : rows7);
6138
6857
  }
6139
6858
  const table2 = segments[0], t = ident2(table2);
6140
6859
  const returning = async (sql2) => {
@@ -6153,9 +6872,9 @@ var PostgrestLayer = class _PostgrestLayer {
6153
6872
  perRow = true;
6154
6873
  sql = `SELECT row_to_json(x) AS row FROM (SELECT ${cols} FROM ${t} t${_PostgrestLayer.where(params, values)}${order.length ? ` ORDER BY ${order.join(", ")}` : ""}${limit >= 0 && params.has("limit") ? ` LIMIT ${Math.trunc(limit)}` : ""}${offset > 0 ? ` OFFSET ${Math.trunc(offset)}` : ""}) x`;
6155
6874
  } else if (method === "POST") {
6156
- const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
6157
- const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
6158
- values.push(JSON.stringify(rows3));
6875
+ const rows7 = Array.isArray(payload) ? payload : [payload ?? {}];
6876
+ const keys = [...new Set(rows7.flatMap((r) => Object.keys(r)))];
6877
+ values.push(JSON.stringify(rows7));
6159
6878
  const target = params.get("on_conflict")?.split(",").map(ident2).join(", ");
6160
6879
  const pk = target ?? (await this.pool.query(`SELECT string_agg(quote_ident(a.attname), ', ') AS k FROM pg_index i JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indrelid=$1::regclass AND i.indisprimary`, [table2])).rows[0]?.k;
6161
6880
  const merge = /resolution=merge-duplicates/.test(prefer), ignore = /resolution=ignore-duplicates/.test(prefer);
@@ -6173,12 +6892,12 @@ var PostgrestLayer = class _PostgrestLayer {
6173
6892
  sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
6174
6893
  } else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
6175
6894
  const result = await this.pool.query(sql, values);
6176
- const rows2 = perRow ? result.rows.map((r) => r.row) : result.rows[0]?.rows ?? [];
6177
- const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
6895
+ const rows6 = perRow ? result.rows.map((r) => r.row) : result.rows[0]?.rows ?? [];
6896
+ const range = { "content-range": `0-${Math.max(rows6.length - 1, 0)}/${/count=exact/.test(prefer) ? rows6.length : "*"}` };
6178
6897
  if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6179
6898
  if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6180
- if (single) return rows2.length === 1 ? reply(status, rows2[0], range) : reply(406, { code: "PGRST116", message: "JSON object requested, multiple (or no) rows returned", details: `The result contains ${rows2.length} rows`, hint: null });
6181
- return reply(status, rows2, range);
6899
+ if (single) return rows6.length === 1 ? reply(status, rows6[0], range) : reply(406, { code: "PGRST116", message: "JSON object requested, multiple (or no) rows returned", details: `The result contains ${rows6.length} rows`, hint: null });
6900
+ return reply(status, rows6, range);
6182
6901
  } catch (error) {
6183
6902
  const e = error;
6184
6903
  const status = e.code === "23505" ? 409 : e.code === "42P01" ? 404 : e.code === "42501" ? 403 : 400;
@@ -6188,16 +6907,16 @@ var PostgrestLayer = class _PostgrestLayer {
6188
6907
  };
6189
6908
 
6190
6909
  // src/runtime/gotrue.ts
6191
- import { createHash as createHash6, createHmac, randomBytes as randomBytes2, randomUUID as randomUUID3 } from "crypto";
6910
+ import { createHash as createHash6, createHmac as createHmac3, randomBytes as randomBytes2, randomUUID as randomUUID3 } from "crypto";
6192
6911
  var b64url = (v) => Buffer.from(v).toString("base64url");
6193
6912
  var userIdFor = (email) => {
6194
6913
  const h = createHash6("sha256").update(`agenttwin-user:${email.toLowerCase()}`).digest("hex");
6195
6914
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
6196
6915
  };
6197
6916
  var GoTrueLayer = class {
6198
- constructor(secret = randomBytes2(32).toString("hex"), now = () => /* @__PURE__ */ new Date()) {
6917
+ constructor(secret = randomBytes2(32).toString("hex"), now5 = () => /* @__PURE__ */ new Date()) {
6199
6918
  this.secret = secret;
6200
- this.now = now;
6919
+ this.now = now5;
6201
6920
  }
6202
6921
  secret;
6203
6922
  now;
@@ -6211,12 +6930,12 @@ var GoTrueLayer = class {
6211
6930
  }
6212
6931
  sign(claims) {
6213
6932
  const head = b64url(JSON.stringify({ alg: "HS256", typ: "JWT" })), body = b64url(JSON.stringify(claims));
6214
- return `${head}.${body}.${b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest())}`;
6933
+ return `${head}.${body}.${b64url(createHmac3("sha256", this.secret).update(`${head}.${body}`).digest())}`;
6215
6934
  }
6216
6935
  verify(token) {
6217
6936
  const [head, body, sig] = token.split(".");
6218
6937
  if (!head || !body || !sig) return void 0;
6219
- if (b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest()) !== sig) return void 0;
6938
+ if (b64url(createHmac3("sha256", this.secret).update(`${head}.${body}`).digest()) !== sig) return void 0;
6220
6939
  try {
6221
6940
  const c = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
6222
6941
  return typeof c.exp === "number" && c.exp * 1e3 < this.now().getTime() ? void 0 : c;
@@ -6375,8 +7094,8 @@ var GoTrueLayer = class {
6375
7094
 
6376
7095
  // src/runtime/supabase-storage.ts
6377
7096
  var StorageLayer = class {
6378
- constructor(now = () => /* @__PURE__ */ new Date()) {
6379
- this.now = now;
7097
+ constructor(now5 = () => /* @__PURE__ */ new Date()) {
7098
+ this.now = now5;
6380
7099
  }
6381
7100
  now;
6382
7101
  buckets = /* @__PURE__ */ new Map();
@@ -6404,7 +7123,7 @@ var StorageLayer = class {
6404
7123
  return {};
6405
7124
  }
6406
7125
  };
6407
- const header3 = (name) => {
7126
+ const header4 = (name) => {
6408
7127
  const v = request.headers[name];
6409
7128
  return Array.isArray(v) ? v[0] : v;
6410
7129
  };
@@ -6445,9 +7164,9 @@ var StorageLayer = class {
6445
7164
  const [, bucket, name] = obj;
6446
7165
  const k = this.key(bucket, name);
6447
7166
  if (method === "POST" || method === "PUT") {
6448
- if (method === "POST" && this.objects.has(k) && header3("x-upsert") !== "true") return fail(400, "Duplicate", "The resource already exists");
7167
+ if (method === "POST" && this.objects.has(k) && header4("x-upsert") !== "true") return fail(400, "Duplicate", "The resource already exists");
6449
7168
  this.bucket(bucket);
6450
- this.objects.set(k, { bucket, name, type: header3("content-type")?.split(";")[0] ?? "application/octet-stream", body: request.body ?? Buffer.alloc(0), created: this.now().toISOString() });
7169
+ this.objects.set(k, { bucket, name, type: header4("content-type")?.split(";")[0] ?? "application/octet-stream", body: request.body ?? Buffer.alloc(0), created: this.now().toISOString() });
6451
7170
  return reply(200, { Key: k, Id: k }, `uploaded ${k} (${request.body?.length ?? 0} bytes)`);
6452
7171
  }
6453
7172
  if (method === "GET" || method === "HEAD") {
@@ -6614,12 +7333,12 @@ var HttpWorld = class {
6614
7333
  sampleResources() {
6615
7334
  const resources = this.spec.resources;
6616
7335
  if (!resources?.length || this.resourceSampleCount >= 5e3) return;
6617
- for (const resource of resources) {
7336
+ for (const resource2 of resources) {
6618
7337
  if (this.resourceSampleCount >= 5e3) return;
6619
- const rows2 = this.state[resource.service]?.[resource.path] ?? [];
6620
- const count = resource.where ? rows2.filter((row) => Object.entries(resource.where).every(([key2, value]) => isDeepStrictEqual(row[key2], value))).length : rows2.length;
7338
+ const rows6 = this.state[resource2.service]?.[resource2.path] ?? [];
7339
+ const count = resource2.where ? rows6.filter((row) => Object.entries(resource2.where).every(([key2, value]) => isDeepStrictEqual(row[key2], value))).length : rows6.length;
6621
7340
  this.resourceSampleCount++;
6622
- this.record(resource.service, "resource", resource.path, `resource ${resource.id} = ${count}`, { resource: resource.id, count });
7341
+ this.record(resource2.service, "resource", resource2.path, `resource ${resource2.id} = ${count}`, { resource: resource2.id, count });
6623
7342
  }
6624
7343
  }
6625
7344
  /**
@@ -6974,6 +7693,13 @@ var HttpWorld = class {
6974
7693
  const all = form.getAll(key3);
6975
7694
  parsed[key3] = all.length > 1 ? all : all[0];
6976
7695
  }
7696
+ } else if (enterprise && String(req.headers["content-type"] ?? "").startsWith("application/x-www-form-urlencoded")) {
7697
+ const form = new URLSearchParams(text2);
7698
+ parsed = {};
7699
+ for (const key3 of new Set(form.keys())) {
7700
+ const all = form.getAll(key3);
7701
+ parsed[key3] = all.length > 1 ? all : all[0];
7702
+ }
6977
7703
  } else if (mode === "raw") {
6978
7704
  rawBody = text2;
6979
7705
  parsed = {};
@@ -6986,6 +7712,9 @@ var HttpWorld = class {
6986
7712
  } else if (service.adapter === "upstash-redis") {
6987
7713
  rawBody = text2;
6988
7714
  parsed = {};
7715
+ } else if (service.adapter === "tinybird" || service.adapter === "qstash") {
7716
+ rawBody = text2;
7717
+ parsed = Object.fromEntries(url.searchParams);
6989
7718
  } else if (service.adapter === "gmail" && !text2.trim()) parsed = {};
6990
7719
  else if (service.adapter === "google-oauth") {
6991
7720
  if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
@@ -7346,14 +8075,14 @@ var HttpWorld = class {
7346
8075
  }
7347
8076
  if (type.startsWith("_")) continue;
7348
8077
  const collection = packCollection(type, path);
7349
- const rows2 = data[collection] ??= [];
7350
- const at = rows2.findIndex((r) => r.id === id);
8078
+ const rows6 = data[collection] ??= [];
8079
+ const at = rows6.findIndex((r) => r.id === id);
7351
8080
  const removed = /^(del|delete|remove)$/i.test(a.op ?? "") || /\.(delete|del)$/.test(a.operation ?? "");
7352
8081
  const row = { id, ...a.fields ?? {} };
7353
8082
  if (removed) {
7354
- if (at >= 0) rows2.splice(at, 1);
7355
- } else if (at >= 0) rows2[at] = { ...rows2[at], ...row };
7356
- else rows2.push(row);
8083
+ if (at >= 0) rows6.splice(at, 1);
8084
+ } else if (at >= 0) rows6[at] = { ...rows6[at], ...row };
8085
+ else rows6.push(row);
7357
8086
  if (!evidence) continue;
7358
8087
  const byApp = a.actor?.kind === "agent" && !byWorld;
7359
8088
  this.record(service.name, byApp ? "write" : "twin", collection, `${method} ${path} \u2192 ${a.operation ?? type} ${id}${byApp ? "" : " (by the twin)"}`, row);
@@ -7745,8 +8474,8 @@ var HttpWorld = class {
7745
8474
  }
7746
8475
  assertions() {
7747
8476
  return this.spec.assertions.map((a) => {
7748
- const rows2 = this.state[a.service][a.path].filter((row) => !a.where || Object.entries(a.where).every(([k, v]) => isDeepStrictEqual(row[k], v)));
7749
- return { ...a, actual: rows2.length, passed: rows2.length === a.count };
8477
+ const rows6 = this.state[a.service][a.path].filter((row) => !a.where || Object.entries(a.where).every(([k, v]) => isDeepStrictEqual(row[k], v)));
8478
+ return { ...a, actual: rows6.length, passed: rows6.length === a.count };
7750
8479
  });
7751
8480
  }
7752
8481
  get faultTriggered() {
@@ -7868,18 +8597,18 @@ function evaluateState(spec, initial, final, events) {
7868
8597
  }
7869
8598
  var canonical = (value) => Array.isArray(value) ? value.map(canonical) : typeof value === "object" && value !== null ? Object.fromEntries(Object.keys(value).sort().map((key2) => [key2, canonical(value[key2])])) : value;
7870
8599
  var short = (value, limit = 120) => value.length <= limit ? value : `${value.slice(0, limit)}\u2026`;
7871
- var recordPresent = (rows2, record3) => typeof record3.id === "string" && record3.id ? rows2.some((row) => row.id === record3.id) : rows2.some((row) => isDeepStrictEqual2(row, record3));
8600
+ var recordPresent = (rows6, record3) => typeof record3.id === "string" && record3.id ? rows6.some((row) => row.id === record3.id) : rows6.some((row) => isDeepStrictEqual2(row, record3));
7872
8601
  function evaluateProperty(policy, final, events) {
7873
8602
  const timing = policy.timing ?? "eventually";
7874
8603
  const base = { id: policy.id, kind: "property", propertyKind: policy.kind, timing, service: policy.service, path: policy.path, passed: false };
7875
- const rows2 = final[policy.service]?.[policy.path];
7876
- if (!rows2) return { ...base, expected: "intact", actual: "missing collection", evidence: { timing, evidenceGap: `final state has no collection "${policy.path}" in "${policy.service}"` } };
7877
- if (timing === "always") return evaluateAlwaysProperty(policy, rows2, events, base);
8604
+ const rows6 = final[policy.service]?.[policy.path];
8605
+ if (!rows6) return { ...base, expected: "intact", actual: "missing collection", evidence: { timing, evidenceGap: `final state has no collection "${policy.path}" in "${policy.service}"` } };
8606
+ if (timing === "always") return evaluateAlwaysProperty(policy, rows6, events, base);
7878
8607
  const eventsFor = (operation2, where2) => events.filter((e) => e.service === policy.service && e.path === policy.path && e.operation === operation2 && (!where2 || e.record !== void 0 && matches(e.record, where2)));
7879
8608
  if (policy.kind === "unique-per-act") {
7880
8609
  const field = String(policy.params?.field);
7881
8610
  const keyed = /* @__PURE__ */ new Map();
7882
- for (const row of rows2) {
8611
+ for (const row of rows6) {
7883
8612
  if (row[field] === void 0) continue;
7884
8613
  const key2 = JSON.stringify(canonical(row[field]));
7885
8614
  keyed.set(key2, [...keyed.get(key2) ?? [], row.id ?? row]);
@@ -7895,7 +8624,7 @@ function evaluateProperty(policy, final, events) {
7895
8624
  }
7896
8625
  if (policy.kind === "no-loss") {
7897
8626
  const writes = eventsFor("write", policy.params?.where);
7898
- const lost = writes.filter((e) => e.record !== void 0 && !recordPresent(rows2, e.record));
8627
+ const lost = writes.filter((e) => e.record !== void 0 && !recordPresent(rows6, e.record));
7899
8628
  const unknown2 = writes.some((e) => !e.record);
7900
8629
  return {
7901
8630
  ...base,
@@ -7918,7 +8647,7 @@ function evaluateProperty(policy, final, events) {
7918
8647
  evidence: { timing, operation, eventSequences: hits.map((e) => e.sequence), evidenceGap: unknown }
7919
8648
  };
7920
8649
  }
7921
- function evaluateAlwaysProperty(policy, rows2, events, base) {
8650
+ function evaluateAlwaysProperty(policy, rows6, events, base) {
7922
8651
  const relevant = events.filter((e) => e.service === policy.service && e.path === policy.path);
7923
8652
  if (policy.kind === "unique-per-act") {
7924
8653
  const field = String(policy.params?.field);
@@ -7955,7 +8684,7 @@ function evaluateAlwaysProperty(policy, rows2, events, base) {
7955
8684
  if (policy.kind === "no-loss") {
7956
8685
  const where2 = policy.params?.where;
7957
8686
  const writes = relevant.filter((e) => e.operation === "write" && (!where2 || e.record !== void 0 && matches(e.record, where2)));
7958
- const lost = writes.filter((e) => e.record !== void 0 && !recordPresent(rows2, e.record));
8687
+ const lost = writes.filter((e) => e.record !== void 0 && !recordPresent(rows6, e.record));
7959
8688
  const evidenceGap2 = writes.some((e) => !e.record);
7960
8689
  return {
7961
8690
  ...base,
@@ -8211,7 +8940,7 @@ var formatMoney = (m) => new Intl.NumberFormat("en-US", { style: "currency", cur
8211
8940
 
8212
8941
  // src/runtime/application-activity.ts
8213
8942
  function isApplicationWrite(event) {
8214
- return event.operation === "write" && !event.path?.startsWith("/_twin/") && !/^[A-Z]+ \/_twin\//.test(event.detail ?? "");
8943
+ return event.operation === "write" && event.activity !== "bookkeeping" && !event.path?.startsWith("/_twin/") && !/^[A-Z]+ \/_twin\//.test(event.detail ?? "");
8215
8944
  }
8216
8945
 
8217
8946
  // src/runtime/generic-calls.ts
@@ -8580,11 +9309,11 @@ var contentSignature = (row, collection) => {
8580
9309
  return canonical3(Object.fromEntries(Object.entries(row).filter(([k, v]) => !volatileKey(k) && !ownId(k) && !own.some((id) => JSON.stringify(v ?? null).includes(id)))));
8581
9310
  };
8582
9311
  function addedRows(initial, final) {
8583
- const rows2 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
8584
- const ids = new Set(rows2(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
9312
+ const rows6 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
9313
+ const ids = new Set(rows6(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
8585
9314
  const seen = /* @__PURE__ */ new Map();
8586
- for (const r of rows2(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
8587
- return rows2(final).filter((r) => {
9315
+ for (const r of rows6(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
9316
+ return rows6(final).filter((r) => {
8588
9317
  if (r.id !== void 0 && r.id !== null) return !ids.has(r.id);
8589
9318
  const key2 = canonical3(r), left = seen.get(key2) ?? 0;
8590
9319
  if (left > 0) {
@@ -8728,8 +9457,8 @@ var stripeIdempotentRetries = {
8728
9457
  var NEGATIVE = /\b(fail|failed|failure|error|unable|could ?n[o']t|cannot|can't|retry|retrying|escalat\w*|pending|not (?:been )?(?:refunded|created|processed|completed))\b/i;
8729
9458
  var gmailText = (r) => {
8730
9459
  const headers = r.payload?.headers ?? [];
8731
- const header3 = (name) => headers.find((h) => h.name?.toLowerCase() === name)?.value ?? "";
8732
- return { to: header3("to"), subject: header3("subject"), body: String(r.payload?.body?.data ?? r.snippet ?? "") };
9460
+ const header4 = (name) => headers.find((h) => h.name?.toLowerCase() === name)?.value ?? "";
9461
+ return { to: header4("to"), subject: header4("subject"), body: String(r.payload?.body?.data ?? r.snippet ?? "") };
8733
9462
  };
8734
9463
  function messageChecks(adapter, path) {
8735
9464
  const noun = adapter === "slack" ? "Slack message" : "email", name = PROVIDER[adapter];