agenttwin 0.3.43 → 0.3.44

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 (100) hide show
  1. package/dist/api.js +26430 -4497
  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-d3c4451763af3bb2.js} +1 -1
  7. package/dist/dashboard/assets/next/static/chunks/app/about/page-e8f70f456b3e001f.js +1 -0
  8. package/dist/dashboard/assets/next/static/chunks/app/account/password/page-13d4d6cf28183f27.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-e6ac9852938ee195.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/app/auth/page-e6ac9852938ee195.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/app/blog/{layout-89f2942330b48007.js → layout-47a0e404f3655e69.js} +1 -1
  12. package/dist/dashboard/assets/next/static/chunks/app/compare/page-e6ac9852938ee195.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/contact/page-e6ac9852938ee195.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-00f2a0cb3dd9dfcc.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-d2f69d996bda5b65.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/app/demo/{page-9e977d1d883f7386.js → page-0ebf741047bacc39.js} +1 -1
  17. package/dist/dashboard/assets/next/static/chunks/app/developers/page-e6ac9852938ee195.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/{page-aea3b669bcb45491.js → page-f9e33ed2f89fd53d.js} +1 -1
  19. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-e6ac9852938ee195.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-526ed9ed987ec1ab.js +1 -0
  21. package/dist/dashboard/assets/next/static/chunks/app/guides/page-e6ac9852938ee195.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/{layout-bc1ef1623bd1dca6.js → layout-8e8607ccec674a88.js} +1 -1
  23. package/dist/dashboard/assets/next/static/chunks/app/login/page-0fdb6c325a08152f.js +1 -0
  24. package/dist/dashboard/assets/next/static/chunks/app/not-found-e6ac9852938ee195.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-aa8315fd545cfcab.js +1 -0
  26. package/dist/dashboard/assets/next/static/chunks/app/page-563661520c08bc87.js +1 -0
  27. package/dist/dashboard/assets/next/static/chunks/app/{enterprise/page-ce47c76b4160b3c9.js → pricing/page-0d9e6abaa82f633b.js} +1 -1
  28. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-e6ac9852938ee195.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-e6ac9852938ee195.js +1 -0
  30. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-e6ac9852938ee195.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/security/page-e6ac9852938ee195.js +1 -0
  32. package/dist/dashboard/assets/next/static/chunks/app/signup/page-0fdb6c325a08152f.js +1 -0
  33. package/dist/dashboard/assets/next/static/chunks/app/status/{page-d075703822281526.js → page-1dce1a7886e3e6f0.js} +1 -1
  34. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-e6ac9852938ee195.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/app/terms/page-e6ac9852938ee195.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-eac4c37292388b51.js +1 -0
  37. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-d82d70f6caa12d7c.js +1 -0
  38. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-ece40a44e9fbe945.js +1 -0
  39. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-52b97f3b9b06f7f7.js +1 -0
  40. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-b5f3b1ecfef066bb.js +1 -0
  41. package/dist/dashboard/assets/next/static/chunks/app/v2/page-e63b0b6f3f0512e0.js +1 -0
  42. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-52b97f3b9b06f7f7.js +1 -0
  43. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-e6ac9852938ee195.js +1 -0
  44. package/dist/dashboard/assets/next/static/chunks/{main-app-85f4e8de9868bedc.js → main-app-8016af41043dfe3d.js} +1 -1
  45. package/dist/dashboard/assets/next/static/chunks/{webpack-382af3529e0fbd25.js → webpack-5e3b77bcb344d4ed.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 +27081 -5120
  54. package/dist/gateway.js +26443 -4510
  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/api-policy/page-35fd8f4fe3b2af15.js +0 -1
  65. package/dist/dashboard/assets/next/static/chunks/app/auth/page-35fd8f4fe3b2af15.js +0 -1
  66. package/dist/dashboard/assets/next/static/chunks/app/compare/page-35fd8f4fe3b2af15.js +0 -1
  67. package/dist/dashboard/assets/next/static/chunks/app/contact/page-35fd8f4fe3b2af15.js +0 -1
  68. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-0262e35e50882ab7.js +0 -1
  69. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-943e07dc51384546.js +0 -1
  70. package/dist/dashboard/assets/next/static/chunks/app/developers/page-35fd8f4fe3b2af15.js +0 -1
  71. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-35fd8f4fe3b2af15.js +0 -1
  72. package/dist/dashboard/assets/next/static/chunks/app/guides/page-35fd8f4fe3b2af15.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/app/login/page-9a6e88fc56812fbb.js +0 -1
  74. package/dist/dashboard/assets/next/static/chunks/app/not-found-35fd8f4fe3b2af15.js +0 -1
  75. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-9c1bd81087260f4f.js +0 -1
  76. package/dist/dashboard/assets/next/static/chunks/app/page-7849ed5b53ffb2d1.js +0 -1
  77. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-2e2f53160e686d9e.js +0 -1
  78. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-35fd8f4fe3b2af15.js +0 -1
  79. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-35fd8f4fe3b2af15.js +0 -1
  80. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-35fd8f4fe3b2af15.js +0 -1
  81. package/dist/dashboard/assets/next/static/chunks/app/security/page-35fd8f4fe3b2af15.js +0 -1
  82. package/dist/dashboard/assets/next/static/chunks/app/signup/page-9a6e88fc56812fbb.js +0 -1
  83. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-35fd8f4fe3b2af15.js +0 -1
  84. package/dist/dashboard/assets/next/static/chunks/app/terms/page-35fd8f4fe3b2af15.js +0 -1
  85. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-22d3ae1def1dd220.js +0 -1
  86. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-1b768bed2b8a2747.js +0 -1
  87. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-38b897124c7f6223.js +0 -1
  88. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-91f11cbfe46c4c25.js +0 -1
  89. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-64dd3f1b59afe38a.js +0 -1
  90. package/dist/dashboard/assets/next/static/chunks/app/v2/page-9191727c63b6ce2e.js +0 -1
  91. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-91f11cbfe46c4c25.js +0 -1
  92. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-35fd8f4fe3b2af15.js +0 -1
  93. package/dist/dashboard/assets/next/static/css/14ef6d1b7f922ef2.css +0 -1
  94. package/dist/dashboard/assets/next/static/css/39133c9a03c8edb8.css +0 -1
  95. package/dist/dashboard/assets/next/static/css/8f1b98de253e73ed.css +0 -1
  96. package/dist/dashboard/assets/next/static/css/c3d3b671693fb96d.css +0 -1
  97. package/dist/dashboard/assets/next/static/css/dd3fb06005e18149.css +0 -1
  98. package/dist/dashboard/assets/next/static/css/f14e187b236cb6fb.css +0 -1
  99. /package/dist/dashboard/assets/next/static/{sxtodXehxQTT0-7MaA4p7 → 485syozzbgr0SePb1vNxp}/_buildManifest.js +0 -0
  100. /package/dist/dashboard/assets/next/static/{sxtodXehxQTT0-7MaA4p7 → 485syozzbgr0SePb1vNxp}/_ssgManifest.js +0 -0
@@ -71,7 +71,7 @@ var init_application_clock = __esm({
71
71
  "src/runtime/application-clock.ts"() {
72
72
  "use strict";
73
73
  MAX_CLOCK_SCALE = 1e4;
74
- 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;
74
+ 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;
75
75
  }
76
76
  });
77
77
 
@@ -221,8 +221,8 @@ var init_seed = __esm({
221
221
  // src/runtime/postgres-clock.ts
222
222
  function validPostgresClock(value) {
223
223
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 1) return false;
224
- const now = value.now;
225
- 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;
224
+ const now5 = value.now;
225
+ 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;
226
226
  }
227
227
  var init_postgres_clock = __esm({
228
228
  "src/runtime/postgres-clock.ts"() {
@@ -450,19 +450,19 @@ function overlay(target, input, schema, merge) {
450
450
  } else target[key2] = isObj(v) || Array.isArray(v) ? structuredClone(v) : coerce(v, child);
451
451
  }
452
452
  }
453
- function newId(resource, rows2, stream) {
454
- const s = resource.idSchema, taken = new Set(rows2.map((r) => String(r[resource.idField])));
453
+ function newId(resource2, rows6, stream) {
454
+ const s = resource2.idSchema, taken = new Set(rows6.map((r) => String(r[resource2.idField])));
455
455
  for (let i = 0; i < 50; i++) {
456
456
  let id;
457
- if (s?.type === "integer" || s?.type === "number") id = rows2.reduce((m, r) => Math.max(m, Number(r[resource.idField]) || 0), 1e3) + 1 + i;
457
+ if (s?.type === "integer" || s?.type === "number") id = rows6.reduce((m, r) => Math.max(m, Number(r[resource2.idField]) || 0), 1e3) + 1 + i;
458
458
  else if (s?.pattern) id = fromPattern(s.pattern, stream);
459
459
  if (id === void 0 && typeof s?.example === "string" && /^[A-Za-z]{1,8}_/.test(s.example)) id = s.example.split("_")[0] + "_" + stream.nextHex(12);
460
460
  if (id === void 0 && s?.format === "uuid") id = fakeValue(s, "id", stream);
461
461
  if (id === void 0 && typeof s?.example === "string" && /^\d+$/.test(s.example)) id = String(1e7 + stream.nextInt(89999999));
462
- id ??= `${singular(resource.name).replace(/[^a-z0-9]/gi, "").slice(0, 4).toLowerCase() || "obj"}_${stream.nextHex(10)}`;
462
+ id ??= `${singular(resource2.name).replace(/[^a-z0-9]/gi, "").slice(0, 4).toLowerCase() || "obj"}_${stream.nextHex(10)}`;
463
463
  if (!taken.has(String(id))) return id;
464
464
  }
465
- return `${resource.name}_${stream.nextHex(16)}`;
465
+ return `${resource2.name}_${stream.nextHex(16)}`;
466
466
  }
467
467
  function routes(twin) {
468
468
  let list2 = cache.get(twin);
@@ -524,27 +524,27 @@ function errorBody(twin, op2, status, code, message, seed) {
524
524
  fill(body, choice.schema, 0);
525
525
  return { status: finalStatus, body };
526
526
  }
527
- function inScope(row, resource, params, op2) {
527
+ function inScope(row, resource2, params, op2) {
528
528
  for (const p of op2.parentParams ?? []) {
529
- const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
529
+ const field = Object.keys(resource2.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
530
530
  const value = row[parentKey(p)] ?? (field ? row[field] : void 0);
531
531
  if (value !== void 0 && String(value) !== params[p]) return false;
532
532
  }
533
533
  return true;
534
534
  }
535
- function withParents(row, resource, op2, params) {
535
+ function withParents(row, resource2, op2, params) {
536
536
  const out = visible(row);
537
537
  for (const p of op2.parentParams ?? []) {
538
- const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
538
+ const field = Object.keys(resource2.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
539
539
  if (field && (out[field] === void 0 || out[field] === null)) out[field] = params[p];
540
540
  }
541
541
  return out;
542
542
  }
543
- function shape(op2, resource, record3, stream, sequence, params = {}) {
543
+ function shape(op2, resource2, record3, stream, sequence, params = {}) {
544
544
  const r = op2.response;
545
- const out = withParents(record3, resource, op2, params);
546
- 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;
547
- 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)));
545
+ const out = withParents(record3, resource2, op2, params);
546
+ 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;
547
+ 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)));
548
548
  if (!holder) return out;
549
549
  const env = materialize(r, "create", stream, sequence);
550
550
  for (const [k, s] of Object.entries(r.properties)) if (normName(k) === "success" && s.type === "boolean") env[k] = true;
@@ -580,8 +580,8 @@ function listEnvelope(op2, page, info, stream, sequence) {
580
580
  function handleRest(twin, req, data, ctx) {
581
581
  const match = matchOperation(twin, req.method, req.path);
582
582
  if (!match || !match.op.supported) return void 0;
583
- const { op: op2, params } = match, resource = resourceOf(twin, op2), collection = resource.collection;
584
- const rows2 = data[collection] ??= [];
583
+ const { op: op2, params } = match, resource2 = resourceOf(twin, op2), collection = resource2.collection;
584
+ const rows6 = data[collection] ??= [];
585
585
  const stream = streamFor(ctx.seed, `${twin.id}:${collection}:${ctx.sequence}`);
586
586
  const fail = (status, code, message) => {
587
587
  const e = errorBody(twin, op2, status, code, message, ctx.seed);
@@ -604,7 +604,7 @@ function handleRest(twin, req, data, ctx) {
604
604
  }
605
605
  }
606
606
  const id = op2.idParam ? params[op2.idParam] : void 0;
607
- const scoped = rows2.filter((r) => inScope(r, resource, params, op2));
607
+ const scoped = rows6.filter((r) => inScope(r, resource2, params, op2));
608
608
  if (op2.kind === "list") {
609
609
  const filters = [];
610
610
  let size = 20, cursor, cursorName = "";
@@ -631,71 +631,71 @@ function handleRest(twin, req, data, ctx) {
631
631
  }));
632
632
  let start = 0;
633
633
  if (cursor !== void 0) {
634
- const i = matches2.findIndex((r) => String(r[resource.idField]) === cursor);
634
+ const i = matches2.findIndex((r) => String(r[resource2.idField]) === cursor);
635
635
  start = i >= 0 ? i + 1 : cursorName === "page" ? Math.max(0, (Number(cursor) - 1) * size) : Number.isFinite(Number(cursor)) ? Number(cursor) : 0;
636
636
  }
637
- const page = matches2.slice(start, start + size).map((r) => withParents(r, resource, op2, params));
637
+ const page = matches2.slice(start, start + size).map((r) => withParents(r, resource2, op2, params));
638
638
  const more = start + size < matches2.length;
639
- const next2 = more ? cursorName === "startingafter" ? String(page[page.length - 1][resource.idField]) : String(start + size) : void 0;
639
+ const next2 = more ? cursorName === "startingafter" ? String(page[page.length - 1][resource2.idField]) : String(start + size) : void 0;
640
640
  const nextUrl = next2 ? `${req.path}?${new URLSearchParams({ ...req.query, [op2.params.find((p) => normName(p.name) === cursorName)?.name ?? "after"]: next2 })}` : void 0;
641
641
  return { status: op2.status, body: listEnvelope(op2, page, { total: matches2.length, ...next2 ? { next: next2 } : {}, ...nextUrl ? { nextUrl } : {} }, stream, ctx.sequence), collection, operation: "read" };
642
642
  }
643
643
  if (op2.kind === "singleton") {
644
644
  if (req.method === "GET") {
645
- const row3 = scoped[0] ?? materialize(resource.schema ?? op2.response, "seed", streamFor(ctx.seed, `singleton:${twin.id}:${collection}`), 0);
646
- if (!scoped.length && isObj(row3)) rows2.push(row3);
645
+ const row3 = scoped[0] ?? materialize(resource2.schema ?? op2.response, "seed", streamFor(ctx.seed, `singleton:${twin.id}:${collection}`), 0);
646
+ if (!scoped.length && isObj(row3)) rows6.push(row3);
647
647
  return { status: op2.status, body: visible(row3), collection, operation: "read" };
648
648
  }
649
649
  if (req.method === "DELETE") {
650
- rows2.length = 0;
650
+ rows6.length = 0;
651
651
  return { status: op2.status === 200 && !op2.response ? 204 : op2.status, body: op2.response ? {} : null, collection, operation: "write", record: {} };
652
652
  }
653
653
  const row2 = scoped[0] ?? {};
654
654
  overlay(row2, body, op2.body, true);
655
- if (!scoped.length) rows2.push(row2);
655
+ if (!scoped.length) rows6.push(row2);
656
656
  return { status: op2.status, body: visible(row2), collection, operation: "write", record: row2 };
657
657
  }
658
- if (op2.kind === "create" || op2.kind === "upsert" && findRow(scoped, resource, id) < 0) {
659
- if (rows2.length >= 1e4) return fail(429, "capacity", "Twin collection is full");
660
- const record3 = materialize(resource.schema ?? op2.response, "create", stream, ctx.sequence) ?? {};
661
- overlay(record3, body, resource.schema, true);
662
- const supplied = Object.keys(body).find((k) => normName(k) === normName(resource.idField));
663
- if (id !== void 0) record3[resource.idField] = id;
664
- else if (!supplied) record3[resource.idField] = newId(resource, rows2, stream);
665
- else if (findRow(scoped, resource, String(record3[resource.idField])) >= 0) return fail(409, "conflict", `${resource.name} ${record3[resource.idField]} already exists`);
658
+ if (op2.kind === "create" || op2.kind === "upsert" && findRow(scoped, resource2, id) < 0) {
659
+ if (rows6.length >= 1e4) return fail(429, "capacity", "Twin collection is full");
660
+ const record3 = materialize(resource2.schema ?? op2.response, "create", stream, ctx.sequence) ?? {};
661
+ overlay(record3, body, resource2.schema, true);
662
+ const supplied = Object.keys(body).find((k) => normName(k) === normName(resource2.idField));
663
+ if (id !== void 0) record3[resource2.idField] = id;
664
+ else if (!supplied) record3[resource2.idField] = newId(resource2, rows6, stream);
665
+ else if (findRow(scoped, resource2, String(record3[resource2.idField])) >= 0) return fail(409, "conflict", `${resource2.name} ${record3[resource2.idField]} already exists`);
666
666
  for (const p of op2.parentParams ?? []) {
667
- const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
667
+ const field = Object.keys(resource2.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
668
668
  if (field && record3[field] === void 0) record3[field] = params[p];
669
669
  else if (!field) record3[parentKey(p)] = params[p];
670
670
  }
671
- rows2.push(record3);
672
- 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) };
671
+ rows6.push(record3);
672
+ 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) };
673
673
  }
674
- const index = rows2.findIndex((r) => String(r[resource.idField]) === id && inScope(r, resource, params, op2));
675
- if (index < 0) return { ...fail(404, "not_found", `No such ${singular(resource.name)}: ${id}`), operation: "read" };
676
- const row = rows2[index];
677
- if (op2.kind === "read") return { status: op2.status, body: shape(op2, resource, row, stream, ctx.sequence, params), collection, operation: "read" };
674
+ const index = rows6.findIndex((r) => String(r[resource2.idField]) === id && inScope(r, resource2, params, op2));
675
+ if (index < 0) return { ...fail(404, "not_found", `No such ${singular(resource2.name)}: ${id}`), operation: "read" };
676
+ const row = rows6[index];
677
+ if (op2.kind === "read") return { status: op2.status, body: shape(op2, resource2, row, stream, ctx.sequence, params), collection, operation: "read" };
678
678
  if (op2.kind === "delete") {
679
- rows2.splice(index, 1);
679
+ rows6.splice(index, 1);
680
680
  const props = op2.response?.properties;
681
- 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;
681
+ 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;
682
682
  return { status: reply ? op2.status : op2.status === 200 ? 204 : op2.status, body: reply, collection, operation: "write", record: visible(row) };
683
683
  }
684
684
  if (op2.kind === "action") {
685
685
  const verb = normName(op2.path.split("/").pop() ?? "");
686
- const status = Object.entries(resource.schema?.properties ?? {}).find(([k]) => /^(status|state)$/i.test(k));
686
+ const status = Object.entries(resource2.schema?.properties ?? {}).find(([k]) => /^(status|state)$/i.test(k));
687
687
  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"));
688
688
  if (status && target !== void 0) row[status[0]] = target;
689
- overlay(row, body, resource.schema, true);
690
- for (const [k, s] of Object.entries(resource.schema?.properties ?? {})) if (UPDATED.has(normName(k))) row[k] = stamp(s, ctx.sequence);
691
- return { status: op2.status, body: shape(op2, resource, row, stream, ctx.sequence, params), collection, operation: "write", record: visible(row) };
689
+ overlay(row, body, resource2.schema, true);
690
+ for (const [k, s] of Object.entries(resource2.schema?.properties ?? {})) if (UPDATED.has(normName(k))) row[k] = stamp(s, ctx.sequence);
691
+ return { status: op2.status, body: shape(op2, resource2, row, stream, ctx.sequence, params), collection, operation: "write", record: visible(row) };
692
692
  }
693
- 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);
694
- overlay(next, body, resource.schema, op2.kind === "update");
695
- next[resource.idField] = row[resource.idField];
696
- for (const [k, s] of Object.entries(resource.schema?.properties ?? {})) if (UPDATED.has(normName(k))) next[k] = stamp(s, ctx.sequence);
697
- rows2[index] = next;
698
- return { status: op2.status === 201 ? 200 : op2.status, body: shape(op2, resource, next, stream, ctx.sequence, params), collection, operation: "write", record: visible(next) };
693
+ 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);
694
+ overlay(next, body, resource2.schema, op2.kind === "update");
695
+ next[resource2.idField] = row[resource2.idField];
696
+ for (const [k, s] of Object.entries(resource2.schema?.properties ?? {})) if (UPDATED.has(normName(k))) next[k] = stamp(s, ctx.sequence);
697
+ rows6[index] = next;
698
+ return { status: op2.status === 201 ? 200 : op2.status, body: shape(op2, resource2, next, stream, ctx.sequence, params), collection, operation: "write", record: visible(next) };
699
699
  }
700
700
  var HIDDEN, visible, isObj, CREATED, UPDATED, stamp, coerce, cache, pathKnown, MESSAGE, CODE, STATUS, PAGE_SIZE, CURSOR, resourceOf, findRow, parentKey;
701
701
  var init_engine = __esm({
@@ -734,7 +734,7 @@ var init_engine = __esm({
734
734
  PAGE_SIZE = /^(limit|perpage|pagesize|maxresults|maxitems|top|size|first|count|maxkeys)$/;
735
735
  CURSOR = /^(after|startingafter|cursor|pagetoken|nextpagetoken|offset|start|skip|page|marker|continuationtoken|nexttoken|startafter|startindex)$/;
736
736
  resourceOf = (twin, op2) => twin.resources.find((r) => r.collection === op2.resource);
737
- findRow = (rows2, resource, id) => rows2.findIndex((r) => String(r[resource.idField]) === id);
737
+ findRow = (rows6, resource2, id) => rows6.findIndex((r) => String(r[resource2.idField]) === id);
738
738
  parentKey = (name) => HIDDEN + name;
739
739
  }
740
740
  });
@@ -743,14 +743,34 @@ var init_engine = __esm({
743
743
  import { createHash as createHash2 } from "crypto";
744
744
  function eqFilter(expression, quote3) {
745
745
  const parts = expression.split(/\s+and\s+/i), tests = [];
746
+ const compare = (actual, op2, value) => {
747
+ const equal = actual === value || typeof value === "number" && String(actual) === String(value);
748
+ if (op2 === "eq") return equal;
749
+ if (op2 === "ne") return !equal;
750
+ if (actual === void 0 || actual === null) return false;
751
+ let a = actual, b = value;
752
+ if (typeof a === "string" && typeof b === "string") {
753
+ const ad = Date.parse(a), bd = Date.parse(b);
754
+ if (Number.isFinite(ad) && Number.isFinite(bd)) {
755
+ a = ad;
756
+ b = bd;
757
+ }
758
+ } else if (typeof b === "number" && typeof a === "string" && /^-?\d+(?:\.\d+)?$/.test(a)) a = Number(a);
759
+ const left = a, right = b;
760
+ if (left === right) return op2 === "ge" || op2 === "le";
761
+ return op2 === "ge" ? left > right : op2 === "le" ? left < right : op2 === "gt" ? left > right : left < right;
762
+ };
746
763
  for (const part of parts) {
747
- const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote3}([^${quote3}]*)${quote3}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
764
+ const any = /^\s*categories\/any\(\s*c\s*:\s*c\s+eq\s+'([^']*)'\s*\)\s*$/i.exec(part);
765
+ if (any) {
766
+ tests.push((r) => Array.isArray(r.categories) && r.categories.includes(any[1]));
767
+ continue;
768
+ }
769
+ const m = new RegExp(`^\\s*([\\w.]+)\\s+(eq|ne|ge|le|gt|lt)\\s+(?:${quote3}([^${quote3}]*)${quote3}|(true|false|-?\\d+(?:\\.\\d+)?|null|\\d{4}-\\d{2}-\\d{2}T[\\d:.+-]+Z?))\\s*$`, "i").exec(part);
748
770
  if (!m) return null;
749
- const value = m[2] !== void 0 ? m[2] : m[3] === "null" ? null : m[3] === "true" ? true : m[3] === "false" ? false : Number(m[3]);
750
- tests.push((r) => {
751
- const actual = m[1].split(".").reduce((v, k) => v?.[k], r);
752
- return actual === value || typeof value === "number" && String(actual) === String(value);
753
- });
771
+ const op2 = m[2].toLowerCase();
772
+ 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]);
773
+ tests.push((r) => compare(m[1].split(".").reduce((v, k) => v?.[k], r), op2, value));
754
774
  }
755
775
  return (r) => tests.every((t) => t(r));
756
776
  }
@@ -786,9 +806,10 @@ function sqlWhere(clause, bindings, counter) {
786
806
  function enterpriseAuth(adapter, headers, url, token) {
787
807
  if (adapter === "okta") return headers.authorization === `SSWS ${token}`;
788
808
  if (adapter === "pagerduty") return headers.authorization === `Token token=${token}` || new URL(url, "http://localhost").pathname === "/v2/enqueue";
809
+ if (adapter === "outlook") return /\/oauth2\/(?:v2\.0\/)?token$/.test(new URL(url, "http://localhost").pathname);
789
810
  return false;
790
811
  }
791
- var ENTERPRISE_ADAPTERS, isEnterpriseAdapter, EPOCH, iso, hash, isObject, scalar, flat, read, write, table, limitOf, nextNumber, header, SF_OBJECTS, sfError, sfView, salesforce, SN_TABLES, snTime, snError, servicenow, wdError, workday, SAP_SETS, sapError, sapView, sap, graphError, graphId, graphPage, teams, address, outlook, entra, oktaError, oktaId, okta, cfError, storage, confluence, sharepoint, sfSqlValue, VALUE, ident, snowflake, NS_TYPES, nsError, nsLink, netsuite, pdError, pdId, pagerduty, ENTERPRISE_OPERATIONS, ENTERPRISE_OPTIONAL_COLLECTIONS, FREEFORM_COLLECTION_ADAPTERS, unsupported, ENTERPRISE_UNSUPPORTED, op, ENTERPRISE_CONTRACTS;
812
+ var ENTERPRISE_ADAPTERS, isEnterpriseAdapter, EPOCH, iso, hash, isObject, scalar, flat, read, write, table, limitOf, nextNumber, header, SF_OBJECTS, sfError, sfView, salesforce, SN_TABLES, snTime, snError, servicenow, wdError, workday, SAP_SETS, sapError, sapView, sap, graphError, graphId, graphPage, teams, address, OUTLOOK_FOLDERS, outlookFolderRows, outlookToken, outlook, entra, oktaError, oktaId, okta, cfError, storage, confluence, sharepoint, sfSqlValue, VALUE, ident, snowflake, NS_TYPES, nsError, nsLink, netsuite, pdError, pdId, pagerduty, ENTERPRISE_OPERATIONS, ENTERPRISE_OPTIONAL_COLLECTIONS, FREEFORM_COLLECTION_ADAPTERS, unsupported, ENTERPRISE_UNSUPPORTED, op, ENTERPRISE_CONTRACTS;
792
813
  var init_enterprise_twins = __esm({
793
814
  "src/runtime/enterprise-twins.ts"() {
794
815
  "use strict";
@@ -809,7 +830,7 @@ var init_enterprise_twins = __esm({
809
830
  const n = Number(value);
810
831
  return Number.isInteger(n) && n >= 1 && n <= max ? n : null;
811
832
  };
812
- nextNumber = (rows2, key2, start) => rows2.reduce((max, r) => Math.max(max, Number(String(r[key2] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
833
+ nextNumber = (rows6, key2, start) => rows6.reduce((max, r) => Math.max(max, Number(String(r[key2] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
813
834
  header = (headers, name) => {
814
835
  const v = headers[name];
815
836
  return Array.isArray(v) ? v[0] : v;
@@ -842,18 +863,18 @@ var init_enterprise_twins = __esm({
842
863
  if (!s) return;
843
864
  const object4 = s[1], spec = SF_OBJECTS[object4], collection = `/sobjects/${object4}`;
844
865
  if (!spec) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
845
- const rows2 = table(data, collection);
866
+ const rows6 = table(data, collection);
846
867
  if (!s[2] && method === "POST") {
847
868
  if (!flat(body)) return;
848
869
  const missing = spec.required.filter((f) => body[f] === void 0 || body[f] === null || body[f] === "");
849
870
  if (missing.length) return { ...sfError(400, "REQUIRED_FIELD_MISSING", `Required fields are missing: [${missing.join(", ")}]`, missing), collection };
850
- const id = (spec.prefix + hash(`salesforce:${object4}:${sequence}:${rows2.length}`).slice(0, 12)).toUpperCase().replace(/^00Q/i, "00Q") + "AAA";
871
+ const id = (spec.prefix + hash(`salesforce:${object4}:${sequence}:${rows6.length}`).slice(0, 12)).toUpperCase().replace(/^00Q/i, "00Q") + "AAA";
851
872
  const record4 = { Id: id, ...body, CreatedDate: iso(sequence), LastModifiedDate: iso(sequence), IsDeleted: false };
852
- rows2.push(record4);
873
+ rows6.push(record4);
853
874
  return write(collection, record4, { id, success: true, errors: [] }, 201);
854
875
  }
855
876
  if (!s[2]) return;
856
- const record3 = rows2.find((r) => r.Id === s[2] || String(r.Id).slice(0, 15) === s[2].slice(0, 15));
877
+ const record3 = rows6.find((r) => r.Id === s[2] || String(r.Id).slice(0, 15) === s[2].slice(0, 15));
857
878
  if (!record3) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
858
879
  if (method === "GET") return read(collection, sfView(object4, version, record3));
859
880
  if (method === "PATCH") {
@@ -862,7 +883,7 @@ var init_enterprise_twins = __esm({
862
883
  return write(collection, record3, null, 204);
863
884
  }
864
885
  if (method === "DELETE") {
865
- rows2.splice(rows2.indexOf(record3), 1);
886
+ rows6.splice(rows6.indexOf(record3), 1);
866
887
  return write(collection, { ...record3, IsDeleted: true }, null, 204);
867
888
  }
868
889
  };
@@ -874,7 +895,7 @@ var init_enterprise_twins = __esm({
874
895
  if (!m) return;
875
896
  const [, name, sysId] = m, collection = `/${name}`;
876
897
  if (!(name in SN_TABLES)) return { ...snError(400, "Invalid table", `Invalid table ${name}`), collection };
877
- const rows2 = table(data, collection);
898
+ const rows6 = table(data, collection);
878
899
  if (!sysId && method === "GET") {
879
900
  const limit = limitOf(query.sysparm_limit, 1e4, 1e4), offset = Number(query.sysparm_offset ?? 0);
880
901
  if (limit === null || !Number.isInteger(offset) || offset < 0) return;
@@ -884,7 +905,7 @@ var init_enterprise_twins = __esm({
884
905
  if (!c || /^(OR|NQ|ORDERBY)/.test(clause)) return;
885
906
  tests.push((r) => String(r[c[1]] ?? "") === c[3] === (c[2] === "="));
886
907
  }
887
- const matched = rows2.filter((r) => tests.every((t) => t(r)));
908
+ const matched = rows6.filter((r) => tests.every((t) => t(r)));
888
909
  const fields = query.sysparm_fields?.split(",").map((f) => f.trim());
889
910
  const page = matched.slice(offset, offset + limit).map((r) => fields ? Object.fromEntries(fields.map((f) => [f, r[f] ?? ""])) : r);
890
911
  return read(collection, { result: page }, 200, { "x-total-count": String(matched.length) });
@@ -893,19 +914,19 @@ var init_enterprise_twins = __esm({
893
914
  if (!flat(body) || "sys_id" in body) return;
894
915
  const prefix = SN_TABLES[name];
895
916
  const record4 = {
896
- sys_id: hash(`servicenow:${name}:${sequence}:${rows2.length}`).slice(0, 32),
897
- ...prefix ? { number: `${prefix}${String(nextNumber(rows2, "number", 10001)).padStart(7, "0")}` } : {},
917
+ sys_id: hash(`servicenow:${name}:${sequence}:${rows6.length}`).slice(0, 32),
918
+ ...prefix ? { number: `${prefix}${String(nextNumber(rows6, "number", 10001)).padStart(7, "0")}` } : {},
898
919
  ...name === "incident" ? { state: "1", impact: "3", urgency: "3", priority: "5" } : {},
899
920
  ...Object.fromEntries(Object.entries(body).map(([k, v]) => [k, v === null ? "" : String(v)])),
900
921
  sys_created_on: snTime(sequence),
901
922
  sys_updated_on: snTime(sequence),
902
923
  sys_mod_count: "0"
903
924
  };
904
- rows2.push(record4);
925
+ rows6.push(record4);
905
926
  return write(collection, record4, { result: record4 }, 201);
906
927
  }
907
928
  if (!sysId) return;
908
- const record3 = rows2.find((r) => r.sys_id === sysId);
929
+ const record3 = rows6.find((r) => r.sys_id === sysId);
909
930
  if (!record3) return { ...snError(404, "No Record found", "Record doesn't exist or ACL restricts the record retrieval"), collection };
910
931
  if (method === "GET") return read(collection, { result: record3 });
911
932
  if (method === "PATCH" || method === "PUT") {
@@ -914,7 +935,7 @@ var init_enterprise_twins = __esm({
914
935
  return write(collection, record3, { result: record3 });
915
936
  }
916
937
  if (method === "DELETE") {
917
- rows2.splice(rows2.indexOf(record3), 1);
938
+ rows6.splice(rows6.indexOf(record3), 1);
918
939
  return write(collection, record3, null, 204);
919
940
  }
920
941
  };
@@ -963,24 +984,24 @@ var init_enterprise_twins = __esm({
963
984
  sap = (method, path, body, query, headers, data, sequence) => {
964
985
  const m = /^\/sap\/opu\/odata\/sap\/(API_BUSINESS_PARTNER|API_SALES_ORDER_SRV)\/(A_BusinessPartner|A_SalesOrder)(?:\('([^']{1,20})'\))?$/.exec(path);
965
986
  if (!m || SAP_SETS[m[2]].service !== m[1]) return;
966
- const [, , set, key2] = m, collection = `/${set}`, rows2 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
987
+ const [, , set, key2] = m, collection = `/${set}`, rows6 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
967
988
  if (method === "GET") {
968
989
  const issued = header(headers, "x-csrf-token")?.toLowerCase() === "fetch" ? { "x-csrf-token": csrf } : void 0;
969
990
  if (key2) {
970
- const record4 = rows2.find((r) => r[SAP_SETS[set].key] === key2);
991
+ const record4 = rows6.find((r) => r[SAP_SETS[set].key] === key2);
971
992
  return record4 ? read(collection, { d: sapView(set, record4) }, 200, issued) : { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection };
972
993
  }
973
994
  const where = query.$filter ? eqFilter(query.$filter, "'") : () => true;
974
995
  const top = limitOf(query.$top, 1e3, 5e3), skip = Number(query.$skip ?? 0);
975
996
  if (!where || top === null || !Number.isInteger(skip) || skip < 0) return;
976
- return read(collection, { d: { results: rows2.filter(where).slice(skip, skip + top).map((r) => sapView(set, r)) } }, 200, issued);
997
+ return read(collection, { d: { results: rows6.filter(where).slice(skip, skip + top).map((r) => sapView(set, r)) } }, 200, issued);
977
998
  }
978
999
  if (header(headers, "x-csrf-token") !== csrf) return { ...sapError(403, "403", "CSRF token validation failed", { "x-csrf-token": "Required" }), collection };
979
1000
  if (method === "POST" && !key2) {
980
1001
  if (set === "A_BusinessPartner") {
981
1002
  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 };
982
- const record5 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${twinNowMs((EPOCH + sequence) * 1e3)})/`, BusinessPartnerIsBlocked: false };
983
- rows2.push(record5);
1003
+ const record5 = { BusinessPartner: String(nextNumber(rows6, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${twinNowMs((EPOCH + sequence) * 1e3)})/`, BusinessPartnerIsBlocked: false };
1004
+ rows6.push(record5);
984
1005
  return write(collection, record5, { d: sapView(set, record5) }, 201);
985
1006
  }
986
1007
  const items = isObject(body.to_Item) && Array.isArray(body.to_Item.results) ? body.to_Item.results : null;
@@ -989,7 +1010,7 @@ var init_enterprise_twins = __esm({
989
1010
  const total = items.reduce((sum, i) => sum + Number(i.NetAmount ?? 0), 0);
990
1011
  const { to_Item: _items, ...header_ } = body;
991
1012
  const record4 = {
992
- SalesOrder: String(nextNumber(rows2, "SalesOrder", 1)).padStart(10, "0"),
1013
+ SalesOrder: String(nextNumber(rows6, "SalesOrder", 1)).padStart(10, "0"),
993
1014
  ...header_,
994
1015
  TransactionCurrency: body.TransactionCurrency ?? "USD",
995
1016
  TotalNetAmount: total.toFixed(2),
@@ -997,10 +1018,10 @@ var init_enterprise_twins = __esm({
997
1018
  CreationDate: `/Date(${twinNowMs((EPOCH + sequence) * 1e3)})/`,
998
1019
  to_Item: { results: items.map((i, n) => ({ SalesOrderItem: String((n + 1) * 10), ...i })) }
999
1020
  };
1000
- rows2.push(record4);
1021
+ rows6.push(record4);
1001
1022
  return write(collection, record4, { d: sapView(set, record4) }, 201);
1002
1023
  }
1003
- const record3 = key2 ? rows2.find((r) => r[SAP_SETS[set].key] === key2) : void 0;
1024
+ const record3 = key2 ? rows6.find((r) => r[SAP_SETS[set].key] === key2) : void 0;
1004
1025
  if (!record3) return key2 ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
1005
1026
  if (method === "PATCH" || method === "MERGE") {
1006
1027
  if (!flat(body) || SAP_SETS[set].key in body) return;
@@ -1013,11 +1034,24 @@ var init_enterprise_twins = __esm({
1013
1034
  const h = hash(seed);
1014
1035
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
1015
1036
  };
1016
- graphPage = (rows2, query) => {
1037
+ graphPage = (rows6, query) => {
1017
1038
  const where = query.$filter ? eqFilter(query.$filter, "'") : () => true, top = limitOf(query.$top, 100, 999);
1018
1039
  if (!where || top === null) return null;
1040
+ let filtered = rows6.filter(where);
1041
+ if (query.$orderby !== void 0) {
1042
+ const [field, direction] = query.$orderby.trim().split(/\s+/);
1043
+ const value = (r) => field.split(".").reduce((v, k) => v?.[k], r);
1044
+ const sign = /^desc$/i.test(direction ?? "") ? -1 : 1;
1045
+ filtered = [...filtered].sort((a, b) => {
1046
+ const left = value(a), right = value(b);
1047
+ if (left === right) return 0;
1048
+ if (left === void 0 || left === null) return 1;
1049
+ if (right === void 0 || right === null) return -1;
1050
+ return sign * (left < right ? -1 : 1);
1051
+ });
1052
+ }
1019
1053
  const select = query.$select?.split(",").map((s) => s.trim());
1020
- return rows2.filter(where).slice(0, top).map((r) => select ? Object.fromEntries([["id", r.id], ...select.map((s) => [s, r[s] ?? null])]) : r);
1054
+ return filtered.slice(0, top).map((r) => select ? Object.fromEntries([["id", r.id], ...select.map((s) => [s, r[s] ?? null])]) : r);
1021
1055
  };
1022
1056
  teams = (method, path, body, query, _headers, data, sequence) => {
1023
1057
  const m = /^\/v1\.0\/(?:teams\/([\w-]+)\/channels(?:\/([\w:@.%-]+)\/messages(?:\/(\d+)\/replies)?)?|chats\/([\w:@.%-]+)\/messages)$/.exec(path);
@@ -1054,11 +1088,56 @@ var init_enterprise_twins = __esm({
1054
1088
  return write("/messages", record3, record3, 201);
1055
1089
  };
1056
1090
  address = (r) => isObject(r) && isObject(r.emailAddress) && typeof r.emailAddress.address === "string" && /^[^@\s]+@[^@\s]+$/.test(r.emailAddress.address);
1091
+ OUTLOOK_FOLDERS = [
1092
+ { id: "inbox", displayName: "Inbox", parentFolderId: null, childFolderCount: 0, isHidden: false },
1093
+ { id: "drafts", displayName: "Drafts", parentFolderId: null, childFolderCount: 0, isHidden: false },
1094
+ { id: "sentitems", displayName: "Sent Items", parentFolderId: null, childFolderCount: 0, isHidden: false },
1095
+ { id: "deleteditems", displayName: "Deleted Items", parentFolderId: null, childFolderCount: 0, isHidden: false },
1096
+ { id: "archive", displayName: "Archive", parentFolderId: null, childFolderCount: 0, isHidden: false },
1097
+ { id: "outbox", displayName: "Outbox", parentFolderId: null, childFolderCount: 0, isHidden: false },
1098
+ { id: "junkemail", displayName: "Junk Email", parentFolderId: null, childFolderCount: 0, isHidden: false }
1099
+ ];
1100
+ outlookFolderRows = (messages, data) => {
1101
+ const seeded = table(data, "/mailFolders");
1102
+ const folders = seeded.length ? seeded : OUTLOOK_FOLDERS.map((f) => ({ ...f }));
1103
+ const inFolder = (id) => messages.filter((m) => id === "inbox" ? !m.parentFolderId || m.parentFolderId === "inbox" : m.parentFolderId === id);
1104
+ return folders.map((folder) => {
1105
+ const rows6 = inFolder(String(folder.id));
1106
+ return { ...folder, totalItemCount: rows6.length, unreadItemCount: rows6.filter((m) => m.isRead === false).length };
1107
+ });
1108
+ };
1109
+ outlookToken = (method, body, data, sequence) => {
1110
+ if (method !== "POST") return;
1111
+ const failToken = (status, error, description) => ({ status, body: { error, error_description: description, trace_id: graphId(`trace:${sequence}`), correlation_id: graphId(`corr:${sequence}`) }, collection: "/tokens" });
1112
+ const grant = String(body.grant_type ?? "");
1113
+ if (grant !== "client_credentials" && grant !== "refresh_token") return failToken(400, "unsupported_grant_type", `AADSTS70003: The grant type '${grant}' is not supported.`);
1114
+ const bounded = (v) => typeof v === "string" && v.length > 0 && v.length <= 256;
1115
+ if (!bounded(body.client_id)) return failToken(400, "invalid_request", "AADSTS900144: The request body must contain the following parameter: client_id.");
1116
+ if (grant === "refresh_token") {
1117
+ if (!bounded(body.refresh_token)) return failToken(400, "invalid_request", "AADSTS900144: The request body must contain the following parameter: refresh_token.");
1118
+ const grants = table(data, "/grants");
1119
+ 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.");
1120
+ } else if (!bounded(body.client_secret)) return failToken(401, "invalid_client", "AADSTS7000215: Invalid client secret provided.");
1121
+ const expires_in = 3599;
1122
+ const response = {
1123
+ token_type: "Bearer",
1124
+ scope: String(body.scope ?? "https://graph.microsoft.com/.default"),
1125
+ expires_in,
1126
+ ext_expires_in: expires_in,
1127
+ access_token: `synthetic-ms-access-${hash(`outlook:${sequence}:${JSON.stringify(body)}`).slice(0, 24)}`,
1128
+ ...grant === "refresh_token" ? { refresh_token: String(body.refresh_token) } : {}
1129
+ };
1130
+ const record3 = { id: `token_${sequence}`, client_id: body.client_id, grant_type: grant, issued_at: iso(sequence), ...response };
1131
+ table(data, "/tokens").push(record3);
1132
+ return write("/tokens", record3, response);
1133
+ };
1057
1134
  outlook = (method, path, body, query, _headers, data, sequence) => {
1058
- const m = /^\/v1\.0\/(?:me|users\/[^/]+)\/(sendMail|messages|mailFolders\/(inbox|sentitems)\/messages|messages\/([\w=-]+)(?:\/(reply))?)$/.exec(path);
1059
- if (!m) return;
1060
- const messages = table(data, "/messages"), [, route, folder, id, reply] = m;
1061
- const store = (message, parentFolderId) => {
1135
+ if (/^\/(?:common|organizations|consumers|[^/]+)\/oauth2\/(?:v2\.0\/)?token$/.test(path)) return outlookToken(method, body, data, sequence);
1136
+ const envelope = /^\/v1\.0\/(?:(?:me|users\/[^/]+)\/)?(.+)$/.exec(path);
1137
+ if (!envelope) return;
1138
+ const rest = envelope[1];
1139
+ const messages = table(data, "/messages");
1140
+ const store = (message, parentFolderId, draft = false) => {
1062
1141
  const record4 = {
1063
1142
  id: Buffer.from(hash(`outlook:${sequence}:${messages.length}`).slice(0, 30)).toString("base64url"),
1064
1143
  createdDateTime: iso(sequence),
@@ -1070,7 +1149,7 @@ var init_enterprise_twins = __esm({
1070
1149
  ccRecipients: message.ccRecipients ?? [],
1071
1150
  from: { emailAddress: { address: "agent@contoso.test", name: "Agent" } },
1072
1151
  isRead: true,
1073
- isDraft: false,
1152
+ isDraft: draft,
1074
1153
  importance: message.importance ?? "normal",
1075
1154
  parentFolderId,
1076
1155
  conversationId: message.conversationId ?? graphId(`conv:${sequence}`)
@@ -1078,7 +1157,77 @@ var init_enterprise_twins = __esm({
1078
1157
  messages.push(record4);
1079
1158
  return record4;
1080
1159
  };
1081
- if (route === "sendMail" && method === "POST") {
1160
+ const notFound2 = (collection) => ({ ...graphError(404, "ErrorItemNotFound", "The specified object was not found in the store.", sequence), collection });
1161
+ const delta = (rows6, collection) => {
1162
+ const token = query.$deltaToken;
1163
+ if (token !== void 0 && !/^\d{1,20}$/.test(token)) return { ...graphError(400, "InvalidRequest", "Invalid delta token.", sequence), collection };
1164
+ const start = token === void 0 ? 0 : Math.min(Number(token), rows6.length);
1165
+ return read(collection, {
1166
+ "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('me')/messages",
1167
+ value: rows6.slice(start).map((r) => ({ "@odata.etag": `W/"${hash(String(r.id)).slice(0, 27)}"`, ...structuredClone(r) })),
1168
+ "@odata.deltaLink": `https://graph.microsoft.com/v1.0/me/messages/delta?$deltaToken=${rows6.length}`
1169
+ });
1170
+ };
1171
+ if (rest === "subscriptions" || /^subscriptions\/[^/]+$/.test(rest)) {
1172
+ const subscriptions = table(data, "/subscriptions");
1173
+ if (rest === "subscriptions") {
1174
+ if (method === "GET") return read("/subscriptions", { value: subscriptions.map((row) => structuredClone(row)) });
1175
+ if (method !== "POST") return;
1176
+ if (Object.keys(body).some((k) => !["changeType", "notificationUrl", "resource", "expirationDateTime", "clientState", "lifecycleNotificationUrl", "includeResourceData", "encryptionCertificate", "encryptionCertificateId", "latestSupportedTlsVersion"].includes(k))) return;
1177
+ 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" };
1178
+ 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" };
1179
+ const record4 = {
1180
+ id: graphId(`subscription:${sequence}:${subscriptions.length}`),
1181
+ changeType: body.changeType,
1182
+ notificationUrl: body.notificationUrl,
1183
+ resource: body.resource,
1184
+ expirationDateTime: typeof body.expirationDateTime === "string" ? body.expirationDateTime : new Date(twinNowMs((EPOCH + sequence + 3600) * 1e3)).toISOString(),
1185
+ clientState: typeof body.clientState === "string" ? body.clientState : graphId(`clientState:${sequence}`),
1186
+ lifecycleNotificationUrl: body.lifecycleNotificationUrl ?? null,
1187
+ applicationId: "agenttwin-app",
1188
+ creatorId: "agenttwin-user"
1189
+ };
1190
+ subscriptions.push(record4);
1191
+ return write("/subscriptions", record4, record4, 201);
1192
+ }
1193
+ const id2 = decodeURIComponent(rest.slice("subscriptions/".length));
1194
+ const index = subscriptions.findIndex((row) => row.id === id2);
1195
+ if (index < 0) return notFound2("/subscriptions");
1196
+ if (method === "GET") return read("/subscriptions", subscriptions[index]);
1197
+ if (method === "PATCH" || method === "PUT") {
1198
+ if (Object.keys(body).some((k) => k !== "expirationDateTime") || typeof body.expirationDateTime !== "string") return { ...graphError(400, "InvalidRequest", "Only expirationDateTime can be renewed.", sequence), collection: "/subscriptions" };
1199
+ subscriptions[index] = { ...subscriptions[index], expirationDateTime: body.expirationDateTime };
1200
+ return write("/subscriptions", subscriptions[index], subscriptions[index]);
1201
+ }
1202
+ if (method === "DELETE") {
1203
+ const [removed] = subscriptions.splice(index, 1);
1204
+ return write("/subscriptions", removed, null, 204);
1205
+ }
1206
+ return;
1207
+ }
1208
+ if (rest === "mailFolders" && method === "GET") {
1209
+ const page = graphPage(outlookFolderRows(messages, data), query);
1210
+ return page ? read("/mailFolders", { value: page }) : void 0;
1211
+ }
1212
+ const folderMatch = /^mailFolders\/([^/]+)(\/messages(\/delta)?)?$/.exec(rest);
1213
+ if (folderMatch) {
1214
+ const folderId = decodeURIComponent(folderMatch[1]);
1215
+ const folder = outlookFolderRows(messages, data).find((f) => String(f.id) === folderId);
1216
+ if (!folder) return notFound2("/mailFolders");
1217
+ if (!folderMatch[2]) {
1218
+ if (method !== "GET") return;
1219
+ return read("/mailFolders", folder);
1220
+ }
1221
+ const inFolder = messages.filter((m) => folderId === "inbox" ? !m.parentFolderId || m.parentFolderId === "inbox" : m.parentFolderId === folderId);
1222
+ if (folderMatch[3]) {
1223
+ if (method !== "GET") return;
1224
+ return delta(inFolder, "/messages");
1225
+ }
1226
+ if (method !== "GET") return;
1227
+ const page = graphPage(inFolder, query);
1228
+ return page ? read("/messages", { value: page }) : void 0;
1229
+ }
1230
+ if (rest === "sendMail" && method === "POST") {
1082
1231
  const message = body.message;
1083
1232
  if (!isObject(message)) return { ...graphError(400, "ErrorInvalidRequest", "The message is missing.", sequence), collection: "/messages" };
1084
1233
  const recipients = [...message.toRecipients ?? [], ...message.ccRecipients ?? [], ...message.bccRecipients ?? []];
@@ -1086,22 +1235,47 @@ var init_enterprise_twins = __esm({
1086
1235
  if (message.attachments?.length) return;
1087
1236
  return write("/messages", store(message, "sentitems"), null, 202);
1088
1237
  }
1089
- if ((route === "messages" || folder) && method === "GET") {
1090
- const page = graphPage(messages.filter((r) => !folder || r.parentFolderId === folder), query);
1091
- return page ? read("/messages", { value: page }) : void 0;
1238
+ if (rest === "messages/delta") {
1239
+ if (method !== "GET") return;
1240
+ return delta(messages, "/messages");
1092
1241
  }
1093
- const record3 = id ? messages.find((r) => r.id === id) : void 0;
1094
- if (!record3) return id ? { ...graphError(404, "ErrorItemNotFound", "The specified object was not found in the store.", sequence), collection: "/messages" } : void 0;
1095
- if (!reply && method === "GET") return read("/messages", record3);
1096
- if (!reply && method === "PATCH") {
1242
+ if (rest === "messages") {
1243
+ if (method === "GET") {
1244
+ const page = graphPage(messages, query);
1245
+ return page ? read("/messages", { value: page }) : void 0;
1246
+ }
1247
+ if (method !== "POST") return;
1248
+ if (!isObject(body) || Object.keys(body).some((k) => !["subject", "body", "toRecipients", "ccRecipients", "bccRecipients", "importance", "conversationId", "isDraft"].includes(k))) return;
1249
+ return write("/messages", store(body, "drafts", true), null, 201);
1250
+ }
1251
+ const messageMatch = /^messages\/([^/]+)(?:\/(move|reply|replyAll|forward))?$/.exec(rest);
1252
+ if (!messageMatch) return;
1253
+ const id = decodeURIComponent(messageMatch[1]), action = messageMatch[2];
1254
+ const record3 = messages.find((r) => r.id === id);
1255
+ if (!record3) return notFound2("/messages");
1256
+ if (!action && method === "GET") return read("/messages", record3);
1257
+ if (!action && method === "PATCH") {
1097
1258
  if (Object.keys(body).some((k) => !["isRead", "categories", "importance", "flag"].includes(k))) return;
1098
- Object.assign(record3, body);
1259
+ Object.assign(record3, body, { lastModifiedDateTime: iso(sequence) });
1099
1260
  return write("/messages", record3, record3);
1100
1261
  }
1101
- if (reply && method === "POST") {
1102
- const to = record3.parentFolderId === "sentitems" ? record3.toRecipients : [record3.from];
1262
+ if (action === "move") {
1263
+ if (method !== "POST" || Object.keys(body).some((k) => k !== "destinationId") || typeof body.destinationId !== "string" || !body.destinationId) return;
1264
+ 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" };
1265
+ record3.parentFolderId = body.destinationId;
1266
+ record3.lastModifiedDateTime = iso(sequence);
1267
+ return write("/messages", record3, record3, 201);
1268
+ }
1269
+ if (action === "reply" || action === "replyAll") {
1270
+ if (method !== "POST" || Object.keys(body).some((k) => k !== "comment")) return;
1271
+ const to = record3.parentFolderId === "sentitems" ? record3.toRecipients : action === "replyAll" ? [record3.from, ...record3.toRecipients ?? [], ...record3.ccRecipients ?? []] : [record3.from];
1103
1272
  return write("/messages", store({ subject: `RE: ${record3.subject}`, body: { contentType: "text", content: String(body.comment ?? "") }, toRecipients: to, conversationId: record3.conversationId }, "sentitems"), null, 202);
1104
1273
  }
1274
+ if (action === "forward") {
1275
+ if (method !== "POST" || Object.keys(body).some((k) => !["comment", "toRecipients"].includes(k))) return;
1276
+ 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" };
1277
+ return write("/messages", store({ subject: `FW: ${record3.subject}`, body: { contentType: "text", content: String(body.comment ?? "") }, toRecipients: body.toRecipients, conversationId: record3.conversationId }, "sentitems"), null, 202);
1278
+ }
1105
1279
  };
1106
1280
  entra = (method, path, body, query, _headers, data, sequence) => {
1107
1281
  const m = /^\/v1\.0\/(users|groups)(?:\/([^/]+))?(?:\/members(?:\/([\w-]+))?(\/\$ref)?)?$/.exec(path);
@@ -1176,17 +1350,17 @@ var init_enterprise_twins = __esm({
1176
1350
  if (method === "GET") {
1177
1351
  const limit = limitOf(query.limit, 200, 200);
1178
1352
  if (limit === null) return;
1179
- let rows2 = users;
1353
+ let rows6 = users;
1180
1354
  if (query.filter) {
1181
1355
  const where = eqFilter(query.filter, '"');
1182
1356
  if (!where) return;
1183
- rows2 = rows2.filter(where);
1357
+ rows6 = rows6.filter(where);
1184
1358
  }
1185
1359
  if (query.q) {
1186
1360
  const q = query.q.toLowerCase();
1187
- rows2 = rows2.filter((u) => ["firstName", "lastName", "email", "login"].some((f) => String(u.profile?.[f] ?? "").toLowerCase().startsWith(q)));
1361
+ rows6 = rows6.filter((u) => ["firstName", "lastName", "email", "login"].some((f) => String(u.profile?.[f] ?? "").toLowerCase().startsWith(q)));
1188
1362
  }
1189
- return read("/users", rows2.slice(0, limit));
1363
+ return read("/users", rows6.slice(0, limit));
1190
1364
  }
1191
1365
  if (method !== "POST") return;
1192
1366
  const profile = body.profile;
@@ -1381,9 +1555,9 @@ var init_enterprise_twins = __esm({
1381
1555
  const missing = (name) => ({ status: 422, collection: "/statements", body: { code: "002003", message: `SQL compilation error:
1382
1556
  Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCase()}' does not exist or not authorized.`, sqlState: "02000", statementHandle: handle } });
1383
1557
  const known2 = (name) => Object.hasOwn(data, `/${name}`) && name !== "STATEMENTS";
1384
- const result = (columns, rows2, dml) => ({
1385
- resultSetMetaData: { numRows: rows2.length, format: "jsonv2", partitionInfo: [{ rowCount: rows2.length }], rowType: columns.map((name) => ({ name: dml ?? name, type: dml ? "fixed" : "text", nullable: !dml })) },
1386
- data: rows2.map((r) => r.map((v) => v === null || v === void 0 ? null : String(v))),
1558
+ const result = (columns, rows6, dml) => ({
1559
+ resultSetMetaData: { numRows: rows6.length, format: "jsonv2", partitionInfo: [{ rowCount: rows6.length }], rowType: columns.map((name) => ({ name: dml ?? name, type: dml ? "fixed" : "text", nullable: !dml })) },
1560
+ data: rows6.map((r) => r.map((v) => v === null || v === void 0 ? null : String(v))),
1387
1561
  code: "090001",
1388
1562
  statementStatusUrl: `/api/v2/statements/${handle}`,
1389
1563
  requestId: graphId(`sf-req:${sequence}`),
@@ -1402,15 +1576,15 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
1402
1576
  if (!known2(name)) return missing(name);
1403
1577
  const where = sqlWhere(s[3], bindings, counter);
1404
1578
  if (!where) return;
1405
- let rows2 = data[`/${name}`].filter(where);
1579
+ let rows6 = data[`/${name}`].filter(where);
1406
1580
  if (s[4]) {
1407
1581
  const col = ident(s[4]), dir = s[5]?.toUpperCase() === "DESC" ? -1 : 1;
1408
- rows2 = [...rows2].sort((a, b) => (a[col] > b[col] ? 1 : a[col] < b[col] ? -1 : 0) * dir);
1582
+ rows6 = [...rows6].sort((a, b) => (a[col] > b[col] ? 1 : a[col] < b[col] ? -1 : 0) * dir);
1409
1583
  }
1410
- if (s[6]) rows2 = rows2.slice(0, Number(s[6]));
1584
+ if (s[6]) rows6 = rows6.slice(0, Number(s[6]));
1411
1585
  const columns = s[1].trim() === "*" ? [...new Set(data[`/${name}`].flatMap((r) => Object.keys(r)))] : s[1].split(",").map((c) => ident(c.trim()));
1412
1586
  if (columns.some((c) => !/^[\w$]+$/.test(c))) return;
1413
- return remember(`/${name}`, result(columns, rows2.map((r) => columns.map((c) => r[c] ?? null))), "read");
1587
+ return remember(`/${name}`, result(columns, rows6.map((r) => columns.map((c) => r[c] ?? null))), "read");
1414
1588
  }
1415
1589
  if (s = /^INSERT\s+INTO\s+("?[\w$]+"?)\s*\(([^)]+)\)\s*VALUES\s*(.+)$/is.exec(statement)) {
1416
1590
  const name = ident(s[1]);
@@ -1459,15 +1633,15 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
1459
1633
  netsuite = (method, path, body, query, _headers, data, sequence) => {
1460
1634
  const m = /^\/services\/rest\/record\/v1\/(\w+)(?:\/(\d+))?$/.exec(path);
1461
1635
  if (!m || !NS_TYPES.includes(m[1])) return;
1462
- const [, type, id] = m, collection = `/${type}`, rows2 = table(data, collection);
1636
+ const [, type, id] = m, collection = `/${type}`, rows6 = table(data, collection);
1463
1637
  if (!id && method === "GET") {
1464
1638
  const limit = limitOf(query.limit, 1e3, 1e3), offset = Number(query.offset ?? 0);
1465
1639
  if (limit === null || !Number.isInteger(offset) || offset < 0) return;
1466
- let matched = rows2;
1640
+ let matched = rows6;
1467
1641
  if (query.q) {
1468
1642
  const tests = query.q.split(/\s+AND\s+/i).map((part) => /^\s*(\w+)\s+(IS|IS_NOT)\s+"([^"]*)"\s*$/i.exec(part));
1469
1643
  if (tests.some((t) => !t)) return;
1470
- matched = rows2.filter((r) => tests.every((t) => String(r[t[1]] ?? "") === t[3] === (t[2].toUpperCase() === "IS")));
1644
+ matched = rows6.filter((r) => tests.every((t) => String(r[t[1]] ?? "") === t[3] === (t[2].toUpperCase() === "IS")));
1471
1645
  }
1472
1646
  const page = matched.slice(offset, offset + limit);
1473
1647
  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 });
@@ -1484,12 +1658,12 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
1484
1658
  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 };
1485
1659
  total = lines.reduce((sum, l) => sum + Number(l.quantity) * Number(l.rate ?? 0), 0);
1486
1660
  }
1487
- const newId2 = String(nextNumber(rows2, "id", 1001));
1661
+ const newId2 = String(nextNumber(rows6, "id", 1001));
1488
1662
  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) };
1489
- rows2.push(record4);
1663
+ rows6.push(record4);
1490
1664
  return write(collection, record4, null, 204, { location: `/services/rest/record/v1/${type}/${newId2}` });
1491
1665
  }
1492
- const record3 = id ? rows2.find((r) => r.id === id) : void 0;
1666
+ const record3 = id ? rows6.find((r) => r.id === id) : void 0;
1493
1667
  if (!record3) return { ...nsError(404, "Record Not Found", "The record instance does not exist. Provide a valid record instance ID.", "NONEXISTENT_ID"), collection };
1494
1668
  if (method === "GET") return read(collection, { links: nsLink(type, record3.id), ...record3 });
1495
1669
  if (method === "PATCH") {
@@ -1498,7 +1672,7 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
1498
1672
  return write(collection, record3, null, 204);
1499
1673
  }
1500
1674
  if (method === "DELETE") {
1501
- rows2.splice(rows2.indexOf(record3), 1);
1675
+ rows6.splice(rows6.indexOf(record3), 1);
1502
1676
  return write(collection, record3, null, 204);
1503
1677
  }
1504
1678
  };
@@ -1607,7 +1781,7 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
1607
1781
  workday: ["/workers", "/timeOffRequests"],
1608
1782
  sap: ["/A_BusinessPartner", "/A_SalesOrder"],
1609
1783
  "microsoft-teams": ["/channels", "/chats", "/messages"],
1610
- outlook: ["/messages"],
1784
+ outlook: ["/messages", "/mailFolders", "/subscriptions", "/tokens", "/grants"],
1611
1785
  "entra-id": ["/users", "/groups", "/groupMembers"],
1612
1786
  okta: ["/users", "/groups", "/groupMemberships"],
1613
1787
  confluence: ["/pages", "/spaces", "/comments"],
@@ -1666,10 +1840,10 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
1666
1840
  limitations: ["No adaptive card rendering, mentions resolution, reactions, edits, deletes, meetings or change notifications"]
1667
1841
  },
1668
1842
  outlook: {
1669
- version: "1.0.0",
1670
- authentication: "Bearer run-scoped test token (Graph access token shape)",
1671
- 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)")],
1672
- limitations: ["No attachments, drafts, forward, rules, calendar or delta queries; inbound mail exists only as seeded records"]
1843
+ version: "1.1.0",
1844
+ authentication: "Bearer run-scoped test token (Graph access token shape); OAuth token endpoint posts form-encoded client credentials",
1845
+ 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"])],
1846
+ 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"]
1673
1847
  },
1674
1848
  "entra-id": {
1675
1849
  version: "1.0.0",
@@ -1909,6 +2083,16 @@ var init_contracts = __esm({
1909
2083
  { method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
1910
2084
  { 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"] },
1911
2085
  { 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"] },
2086
+ { 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"] },
2087
+ { 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"] },
2088
+ { 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"] },
2089
+ { method: "GET", endpoint: "/gmail/v1/users/me/labels/<id>", effect: "retrieve one label", parameters: [], errors: ["404 not found"] },
2090
+ { 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"] },
2091
+ { 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"] },
2092
+ { 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"] },
2093
+ { 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"] },
2094
+ { method: "DELETE", endpoint: "/gmail/v1/users/me/settings/filters/<id>", effect: "delete a filter (204)", parameters: [], errors: ["404 not found"] },
2095
+ { method: "GET", endpoint: "/gmail/v1/users/me/settings/forwardingAddresses", effect: "list seeded forwarding addresses", parameters: [], errors: [] },
1912
2096
  { 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"] },
1913
2097
  { 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"] },
1914
2098
  { 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"] },
@@ -1926,7 +2110,7 @@ var init_contracts = __esm({
1926
2110
  { 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"] },
1927
2111
  { 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"] }
1928
2112
  ],
1929
- 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"]
2113
+ 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"]
1930
2114
  },
1931
2115
  "upstash-redis": {
1932
2116
  version: "1.0.0",
@@ -1938,6 +2122,51 @@ var init_contracts = __esm({
1938
2122
  ],
1939
2123
  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"]
1940
2124
  },
2125
+ posthog: {
2126
+ version: "1.0.0",
2127
+ authentication: "Bearer run-scoped test token; the project api_key travels in the body",
2128
+ operations: [
2129
+ { 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"] },
2130
+ { 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"] },
2131
+ { 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"] },
2132
+ { method: "POST", endpoint: "/flags", effect: "flag detail map in the /flags response shape", parameters: ["api_key", "distinct_id"], errors: ["400 api_key required"] }
2133
+ ],
2134
+ 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"]
2135
+ },
2136
+ tinybird: {
2137
+ version: "1.0.0",
2138
+ authentication: "Bearer run-scoped test token; an existing Tinybird token is accepted as the run token",
2139
+ operations: [
2140
+ { 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"] },
2141
+ { 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"] },
2142
+ { 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"] },
2143
+ { method: "GET", endpoint: "/v0/datasources, /v0/pipes", effect: "list datasources and pipes the twin holds", parameters: [], errors: [] }
2144
+ ],
2145
+ 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"]
2146
+ },
2147
+ lemonsqueezy: {
2148
+ version: "1.0.0",
2149
+ authentication: "Bearer run-scoped test token; JSON:API bodies",
2150
+ operations: [
2151
+ { 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"] },
2152
+ { method: "GET", endpoint: "/v1/checkouts/<id>", effect: "retrieve a checkout", parameters: [], errors: ["404 Not Found"] },
2153
+ { 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"] },
2154
+ { 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"] }
2155
+ ],
2156
+ 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"]
2157
+ },
2158
+ qstash: {
2159
+ version: "1.0.0",
2160
+ authentication: "Bearer run-scoped test token (the QStash token header)",
2161
+ operations: [
2162
+ { 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)"] },
2163
+ { method: "GET|DELETE", endpoint: "/v2/messages[/<id>]", effect: "list, read or cancel recorded messages", parameters: [], errors: ["404 message not found"] },
2164
+ { 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"] },
2165
+ { method: "GET|DELETE", endpoint: "/v2/schedules[/<id>]", effect: "list, read or delete schedules", parameters: [], errors: ["404 schedule not found"] },
2166
+ { method: "GET|POST", endpoint: "/v2/signing-keys", effect: "read or rotate the current/next signing keys", parameters: [], errors: [] }
2167
+ ],
2168
+ 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"]
2169
+ },
1941
2170
  "google-calendar": {
1942
2171
  version: "1.1.0",
1943
2172
  authentication: "Bearer run-scoped test token; Google-style OAuth2 Bearer header",
@@ -2235,7 +2464,7 @@ function parseWorld(value) {
2235
2464
  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"})`);
2236
2465
  const item = service;
2237
2466
  if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
2238
- 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");
2467
+ 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");
2239
2468
  const paths = /* @__PURE__ */ new Set();
2240
2469
  for (const entry of item.collections) {
2241
2470
  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");
@@ -2524,7 +2753,11 @@ var init_spec = __esm({
2524
2753
  ADAPTER_OPTIONAL_COLLECTIONS = {
2525
2754
  slack: ["/users"],
2526
2755
  stripe: ["/v1/charges", "/v1/refunds", "/v1/events", "/v1/subscription_items", "/v1/products", "/v1/prices"],
2527
- gmail: ["/gmail/v1/users/me/drafts", "/gmail/v1/users/me/settings/sendAs", "/gmail/v1/users/me/watch", "/pubsub/subscriptions", "/pubsub/messages"],
2756
+ 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"],
2757
+ posthog: ["/feature_flags"],
2758
+ tinybird: ["/datasources", "/pipes"],
2759
+ lemonsqueezy: ["/v1/subscriptions", "/v1/orders", "/v1/webhooks"],
2760
+ qstash: ["/schedules", "/signing-keys"],
2528
2761
  ...ENTERPRISE_OPTIONAL_COLLECTIONS
2529
2762
  };
2530
2763
  ADAPTER_COLLECTIONS = {
@@ -2547,6 +2780,10 @@ var init_spec = __esm({
2547
2780
  composio: ["/connected_accounts", "/tools", "/messages"],
2548
2781
  "google-oauth": ["/clients", "/grants", "/tokens"],
2549
2782
  "upstash-redis": ["/keys"],
2783
+ posthog: ["/events"],
2784
+ tinybird: ["/events"],
2785
+ lemonsqueezy: ["/v1/checkouts"],
2786
+ qstash: ["/messages"],
2550
2787
  zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"],
2551
2788
  // Enterprise twins: any subset of their optional collections; Snowflake tables are free-form.
2552
2789
  ...Object.fromEntries(ENTERPRISE_ADAPTERS.filter((a) => !FREEFORM_COLLECTION_ADAPTERS.includes(a)).map((a) => [a, []]))
@@ -2904,9 +3141,9 @@ var init_request_source = __esm({
2904
3141
  });
2905
3142
 
2906
3143
  // src/runtime/stripe-adapter.ts
2907
- function nextId(rows2, prefix, sequence) {
3144
+ function nextId(rows6, prefix, sequence) {
2908
3145
  let suffix = sequence;
2909
- while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
3146
+ while (rows6.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
2910
3147
  return `${prefix}_at_${suffix}`;
2911
3148
  }
2912
3149
  function chargeFor(intent, data, sequence) {
@@ -2965,18 +3202,18 @@ function refundOperation(method, id, params, data, sequence) {
2965
3202
  if (events) events.push({ id: nextId(events, "evt", sequence), object: "event", type: "charge.refunded", created: twinNowSeconds(17e8), livemode: false, data: { object: structuredClone(charge) } });
2966
3203
  return { status: 200, body: refund, collection, record: structuredClone(refund), operation: "write" };
2967
3204
  }
2968
- function readOnlyOperation(method, resource, id, params, data) {
2969
- const collection = `/v1/${resource}`, rows2 = data[collection];
2970
- if (!rows2 || method !== "GET") return void 0;
3205
+ function readOnlyOperation(method, resource2, id, params, data) {
3206
+ const collection = `/v1/${resource2}`, rows6 = data[collection];
3207
+ if (!rows6 || method !== "GET") return void 0;
2971
3208
  if (id) {
2972
3209
  if (Object.keys(params).length) return void 0;
2973
- const row = rows2.find((r) => r.id === id);
2974
- return row ? { status: 200, body: row, collection, operation: "read" } : { ...stripeError(404, "resource_missing", `No such ${resource.slice(0, -1)}: '${id}'`), collection };
3210
+ const row = rows6.find((r) => r.id === id);
3211
+ return row ? { status: 200, body: row, collection, operation: "read" } : { ...stripeError(404, "resource_missing", `No such ${resource2.slice(0, -1)}: '${id}'`), collection };
2975
3212
  }
2976
3213
  if (Object.keys(params).some((k) => !["limit", "type"].includes(k))) return void 0;
2977
3214
  const limit = params.limit === void 0 ? 10 : Number(params.limit);
2978
3215
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...stripeError(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
2979
- const ordered = [...rows2].reverse().filter((r) => params.type === void 0 || r.type === params.type);
3216
+ const ordered = [...rows6].reverse().filter((r) => params.type === void 0 || r.type === params.type);
2980
3217
  return { status: 200, body: { object: "list", data: ordered.slice(0, limit), has_more: ordered.length > limit, url: collection }, collection, operation: "read" };
2981
3218
  }
2982
3219
  function subscriptionItemOperation(method, id, params, data) {
@@ -3041,21 +3278,21 @@ function stripeOperation(method, path, params, data, sequence) {
3041
3278
  if (other) return other[1] === "refunds" ? refundOperation(method, other[2], params, data, sequence) : readOnlyOperation(method, other[1], other[2], params, data);
3042
3279
  const match = /^\/v1\/(customers|payment_intents)(?:\/([^/]+))?(?:\/(confirm))?$/.exec(path);
3043
3280
  if (!match || !["GET", "POST"].includes(method)) return void 0;
3044
- const [, resource, id, action] = match, collection = `/v1/${resource}`, rows2 = data[collection];
3045
- 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;
3046
- if (!allowed || resource === "customers" && action || resource === "payment_intents" && method === "GET" && !id) return void 0;
3281
+ const [, resource2, id, action] = match, collection = `/v1/${resource2}`, rows6 = data[collection];
3282
+ 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;
3283
+ if (!allowed || resource2 === "customers" && action || resource2 === "payment_intents" && method === "GET" && !id) return void 0;
3047
3284
  if (Object.keys(params).some((k) => !allowed.includes(k.replace(/\[.*$/, "")))) return void 0;
3048
3285
  if (method === "GET" && !id) {
3049
3286
  const limit = params.limit === void 0 ? 10 : Number(params.limit);
3050
3287
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...error(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
3051
- const ordered = [...rows2].reverse();
3288
+ const ordered = [...rows6].reverse();
3052
3289
  const index = params.starting_after === void 0 ? -1 : ordered.findIndex((r) => r.id === params.starting_after);
3053
3290
  if (params.starting_after !== void 0 && index === -1) return { ...error(400, "resource_missing", "No such starting_after customer", "starting_after"), collection };
3054
3291
  const page = ordered.slice(index + 1, index + 1 + limit);
3055
3292
  return { status: 200, body: { object: "list", data: page, has_more: ordered.length > index + 1 + limit, url: collection }, collection, operation: "read" };
3056
3293
  }
3057
- const row = id ? rows2.find((r) => r.id === id) : void 0;
3058
- if (id && !row) return { ...error(404, "resource_missing", `No such ${resource}: '${id}'`), collection };
3294
+ const row = id ? rows6.find((r) => r.id === id) : void 0;
3295
+ if (id && !row) return { ...error(404, "resource_missing", `No such ${resource2}: '${id}'`), collection };
3059
3296
  if (method === "GET") return { status: 200, body: row, collection, operation: "read" };
3060
3297
  if (action === "confirm") {
3061
3298
  if (row.status === "succeeded") return { status: 200, body: row, collection, operation: "replay" };
@@ -3082,11 +3319,11 @@ function stripeOperation(method, path, params, data, sequence) {
3082
3319
  }
3083
3320
  cursor[path2.at(-1)] = value;
3084
3321
  }
3085
- const prefix = resource === "customers" ? "cus" : "pi";
3322
+ const prefix = resource2 === "customers" ? "cus" : "pi";
3086
3323
  let suffix = sequence;
3087
- while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
3088
- const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: twinNowSeconds(17e8), livemode: false };
3089
- if (resource === "customers") {
3324
+ while (rows6.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
3325
+ const created2 = { id: `${prefix}_at_${suffix}`, object: resource2 === "customers" ? "customer" : "payment_intent", created: twinNowSeconds(17e8), livemode: false };
3326
+ if (resource2 === "customers") {
3090
3327
  if (params.email !== void 0 && typeof params.email !== "string") return { ...error(400, "parameter_invalid", "email must be a string", "email"), collection };
3091
3328
  Object.assign(created2, { email: null, name: null, description: null, metadata: {}, ...nested });
3092
3329
  } else {
@@ -3100,14 +3337,14 @@ function stripeOperation(method, path, params, data, sequence) {
3100
3337
  if (confirm && !params.payment_method) return { ...error(400, "parameter_missing", "Missing payment_method", "payment_method"), collection };
3101
3338
  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 });
3102
3339
  }
3103
- if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
3104
- if (resource === "payment_intents") {
3340
+ if (rows6.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
3341
+ if (resource2 === "payment_intents") {
3105
3342
  for (const key2 of ["description", "receipt_email", "statement_descriptor", "capture_method"]) if (nested[key2] !== void 0) created2[key2] = nested[key2];
3106
3343
  }
3107
- if (resource === "payment_intents") created2.metadata = typeof nested.metadata === "object" && nested.metadata ? nested.metadata : {};
3108
- rows2.push(created2);
3344
+ if (resource2 === "payment_intents") created2.metadata = typeof nested.metadata === "object" && nested.metadata ? nested.metadata : {};
3345
+ rows6.push(created2);
3109
3346
  if (created2.status === "succeeded") chargeFor(created2, data, sequence);
3110
- const declined = resource === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
3347
+ const declined = resource2 === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
3111
3348
  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" };
3112
3349
  }
3113
3350
  var stripeError;
@@ -3364,8 +3601,8 @@ var init_composio_twin = __esm({
3364
3601
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) return;
3365
3602
  if (params.cursor !== void 0 && (typeof params.cursor !== "string" || !/^at_\d{1,4}$/.test(params.cursor))) return;
3366
3603
  const start = params.cursor ? Number(String(params.cursor).slice(3)) : 0;
3367
- 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))));
3368
- 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 } };
3604
+ 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))));
3605
+ 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 } };
3369
3606
  }
3370
3607
  const account = /^connected_accounts\/([A-Za-z0-9_-]+)$/.exec(suffix);
3371
3608
  if (method === "DELETE" && account) {
@@ -3849,6 +4086,11 @@ function commandKeys(name, args) {
3849
4086
  if (["ping", "echo", "info", "select", "auth", "hello", "client", "command", "config", "multi", "exec", "discard", "quit", "dbsize", "flushdb", "flushall", "time", "scan", "keys", "unwatch", "readonly", "memory", "script", "publish", "subscribe", "psubscribe"].includes(name)) return [];
3850
4087
  return args.length ? [args[0]] : [];
3851
4088
  }
4089
+ function commandActivity(name, args) {
4090
+ if (!["hset", "hmset"].includes(name) || args.length !== 5 || !args[0].endsWith(":meta")) return;
4091
+ const fields = /* @__PURE__ */ new Map([[args[1], args[2]], [args[3], args[4]]]);
4092
+ if (fields.size === 2 && /^\d+$/.test(fields.get("opts.maxLenEvents") ?? "") && /^bullmq:\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(fields.get("version") ?? "")) return "bookkeeping";
4093
+ }
3852
4094
  function respFrontEnd(upstreamPort, gate, events, commit) {
3853
4095
  const sockets = /* @__PURE__ */ new Set();
3854
4096
  const server = createServer2((client) => {
@@ -3880,7 +4122,7 @@ function respFrontEnd(upstreamPort, gate, events, commit) {
3880
4122
  const reply = p.replace ?? p.reply;
3881
4123
  const committed = p.write && !p.error && !(p.name === "exec" && reply.equals(encode.array(null)));
3882
4124
  if (committed) {
3883
- record(events, { engine: "redis", operation: "write", resource: p.keys.join(","), detail: `${p.name.toUpperCase()} ${p.keys.join(" ")}`.trim().slice(0, 200) });
4125
+ record(events, { engine: "redis", operation: "write", resource: p.keys.join(","), detail: `${p.name.toUpperCase()} ${p.keys.join(" ")}`.trim().slice(0, 200), ...p.activity ? { activity: p.activity } : {} });
3884
4126
  await commit(p.keys);
3885
4127
  const f = gate.take("write", p.keys, ["drop-after-commit", "timeout", "latency"]);
3886
4128
  if (f?.type === "drop-after-commit") {
@@ -3947,7 +4189,7 @@ function respFrontEnd(upstreamPort, gate, events, commit) {
3947
4189
  keys = [...new Set(multi ?? [])];
3948
4190
  multi = null;
3949
4191
  } else if (name === "discard") multi = null;
3950
- const p = { name, write: write3, keys };
4192
+ const p = { name, write: write3, keys, ...commandActivity(name, rest) ? { activity: commandActivity(name, rest) } : {} };
3951
4193
  const rejected = write3 ? gate.take("write", keys, ["error"]) : keys.length ? gate.take("read", keys, ["error"]) : void 0;
3952
4194
  if (rejected) {
3953
4195
  const error = encode.error("ERR AgentTwin injected fault: connection to Redis reset before the command ran (retryable)");
@@ -4089,6 +4331,9 @@ async function startRedisEngine(options = {}) {
4089
4331
  await waitFor(async () => {
4090
4332
  await client.call("PING");
4091
4333
  }, 2e4);
4334
+ } catch (error) {
4335
+ await c.stop();
4336
+ throw error;
4092
4337
  } finally {
4093
4338
  client.close();
4094
4339
  }
@@ -4299,7 +4544,7 @@ var init_redis = __esm({
4299
4544
  return Number(s);
4300
4545
  }
4301
4546
  command(name, a) {
4302
- const now = Date.now(), ok2 = encode.simple("OK"), key2 = a[0];
4547
+ const now5 = Date.now(), ok2 = encode.simple("OK"), key2 = a[0];
4303
4548
  const str2 = (k) => this.get(k, "string");
4304
4549
  const bulks = (list2) => encode.array(list2.map((v) => encode.bulk(v ?? null)));
4305
4550
  const setString = (k, v, expireAt) => this.data.set(k, { type: "string", value: v, ...expireAt !== void 0 ? { expireAt } : {} });
@@ -4343,7 +4588,7 @@ var init_redis = __esm({
4343
4588
  case "config":
4344
4589
  return (a[0] ?? "").toLowerCase() === "get" ? encode.array([]) : ok2;
4345
4590
  case "time":
4346
- return bulks([String(Math.floor(now / 1e3)), String(now % 1e3 * 1e3)]);
4591
+ return bulks([String(Math.floor(now5 / 1e3)), String(now5 % 1e3 * 1e3)]);
4347
4592
  case "dbsize":
4348
4593
  return encode.int([...this.data.keys()].filter((k) => this.live(k)).length);
4349
4594
  case "flushdb":
@@ -4360,8 +4605,8 @@ var init_redis = __esm({
4360
4605
  else if (o === "xx") xx = true;
4361
4606
  else if (o === "get") get = true;
4362
4607
  else if (o === "keepttl") keep = true;
4363
- else if (o === "ex") expireAt = now + this.int(a[++i]) * 1e3;
4364
- else if (o === "px") expireAt = now + this.int(a[++i]);
4608
+ else if (o === "ex") expireAt = now5 + this.int(a[++i]) * 1e3;
4609
+ else if (o === "px") expireAt = now5 + this.int(a[++i]);
4365
4610
  else if (o === "exat") expireAt = this.int(a[++i]) * 1e3;
4366
4611
  else if (o === "pxat") expireAt = this.int(a[++i]);
4367
4612
  else return encode.error("ERR syntax error");
@@ -4378,10 +4623,10 @@ var init_redis = __esm({
4378
4623
  setString(key2, a[1]);
4379
4624
  return encode.int(1);
4380
4625
  case "setex":
4381
- setString(key2, a[2], now + this.int(a[1]) * 1e3);
4626
+ setString(key2, a[2], now5 + this.int(a[1]) * 1e3);
4382
4627
  return ok2;
4383
4628
  case "psetex":
4384
- setString(key2, a[2], now + this.int(a[1]));
4629
+ setString(key2, a[2], now5 + this.int(a[1]));
4385
4630
  return ok2;
4386
4631
  case "getset": {
4387
4632
  const old = str2(key2);
@@ -4446,8 +4691,8 @@ var init_redis = __esm({
4446
4691
  const e = this.live(key2);
4447
4692
  if (!e) return encode.int(0);
4448
4693
  const n = this.int(a[1]);
4449
- e.expireAt = name === "expire" ? now + n * 1e3 : name === "pexpire" ? now + n : name === "expireat" ? n * 1e3 : n;
4450
- if (e.expireAt <= now) this.data.delete(key2);
4694
+ e.expireAt = name === "expire" ? now5 + n * 1e3 : name === "pexpire" ? now5 + n : name === "expireat" ? n * 1e3 : n;
4695
+ if (e.expireAt <= now5) this.data.delete(key2);
4451
4696
  return encode.int(1);
4452
4697
  }
4453
4698
  case "ttl":
@@ -4455,7 +4700,7 @@ var init_redis = __esm({
4455
4700
  const e = this.live(key2);
4456
4701
  if (!e) return encode.int(-2);
4457
4702
  if (e.expireAt === void 0) return encode.int(-1);
4458
- const ms = e.expireAt - now;
4703
+ const ms = e.expireAt - now5;
4459
4704
  return encode.int(name === "ttl" ? Math.round(ms / 1e3) : ms);
4460
4705
  }
4461
4706
  case "persist": {
@@ -4728,61 +4973,61 @@ function toRow(key2, entry) {
4728
4973
  const value = v instanceof Map ? Object.fromEntries([...v].map(([k, x]) => [fromBytes(k), text2(x)])) : v instanceof Set ? [...v].map(text2) : Array.isArray(v) ? v.map(text2) : text2(v);
4729
4974
  return { key: fromBytes(key2), type: entry.type, value, ...entry.expireAt !== void 0 ? { expireAt: entry.expireAt } : {} };
4730
4975
  }
4731
- function resync(rows2, cache2) {
4732
- const now = Date.now();
4733
- for (const [k, e] of cache2.engine.data) if (e.expireAt !== void 0 && e.expireAt <= now) cache2.engine.data.delete(k);
4734
- rows2.splice(0, rows2.length, ...[...cache2.engine.data].map(([k, e]) => toRow(k, e)));
4735
- cache2.mirror = rows2.slice();
4976
+ function resync(rows6, cache2) {
4977
+ const now5 = Date.now();
4978
+ for (const [k, e] of cache2.engine.data) if (e.expireAt !== void 0 && e.expireAt <= now5) cache2.engine.data.delete(k);
4979
+ rows6.splice(0, rows6.length, ...[...cache2.engine.data].map(([k, e]) => toRow(k, e)));
4980
+ cache2.mirror = rows6.slice();
4736
4981
  cache2.index = new Map([...cache2.engine.data.keys()].map((k, i) => [k, i]));
4737
- cache2.nextExpiry = rows2.reduce((min, r) => r.expireAt !== void 0 && r.expireAt < min ? r.expireAt : min, Infinity);
4982
+ cache2.nextExpiry = rows6.reduce((min, r) => r.expireAt !== void 0 && r.expireAt < min ? r.expireAt : min, Infinity);
4738
4983
  }
4739
- function remove(rows2, cache2, key2) {
4984
+ function remove(rows6, cache2, key2) {
4740
4985
  const at = cache2.index.get(key2);
4741
4986
  if (at === void 0) return;
4742
4987
  cache2.index.delete(key2);
4743
- const last = rows2.length - 1;
4988
+ const last = rows6.length - 1;
4744
4989
  if (at !== last) {
4745
- rows2[at] = rows2[last];
4746
- cache2.mirror[at] = rows2[last];
4747
- cache2.index.set(toBytes(rows2[at].key), at);
4990
+ rows6[at] = rows6[last];
4991
+ cache2.mirror[at] = rows6[last];
4992
+ cache2.index.set(toBytes(rows6[at].key), at);
4748
4993
  }
4749
- rows2.pop();
4994
+ rows6.pop();
4750
4995
  cache2.mirror.pop();
4751
4996
  }
4752
- function syncKey(rows2, cache2, key2, now) {
4997
+ function syncKey(rows6, cache2, key2, now5) {
4753
4998
  const entry = cache2.engine.data.get(key2);
4754
- if (!entry || entry.expireAt !== void 0 && entry.expireAt <= now) {
4999
+ if (!entry || entry.expireAt !== void 0 && entry.expireAt <= now5) {
4755
5000
  if (entry) cache2.engine.data.delete(key2);
4756
- remove(rows2, cache2, key2);
5001
+ remove(rows6, cache2, key2);
4757
5002
  return;
4758
5003
  }
4759
5004
  const row = toRow(key2, entry);
4760
5005
  const at = cache2.index.get(key2);
4761
5006
  if (at === void 0) {
4762
- cache2.index.set(key2, rows2.length);
4763
- rows2.push(row);
5007
+ cache2.index.set(key2, rows6.length);
5008
+ rows6.push(row);
4764
5009
  cache2.mirror.push(row);
4765
5010
  } else {
4766
- rows2[at] = row;
5011
+ rows6[at] = row;
4767
5012
  cache2.mirror[at] = row;
4768
5013
  }
4769
5014
  if (row.expireAt !== void 0) cache2.nextExpiry = Math.min(cache2.nextExpiry, row.expireAt);
4770
5015
  }
4771
- function engineFor(rows2) {
4772
- const cached2 = caches.get(rows2);
4773
- if (cached2 && consistent(rows2, cached2)) return cached2;
5016
+ function engineFor(rows6) {
5017
+ const cached2 = caches.get(rows6);
5018
+ if (cached2 && consistent(rows6, cached2)) return cached2;
4774
5019
  const engine = new InProcessRedis();
4775
- for (const row of rows2) {
5020
+ for (const row of rows6) {
4776
5021
  const entry = row && typeof row.key === "string" ? toEntry(row) : void 0;
4777
5022
  if (!entry) {
4778
- caches.delete(rows2);
5023
+ caches.delete(rows6);
4779
5024
  return { error: `ERR invalid seeded key row ${JSON.stringify(row?.key)}` };
4780
5025
  }
4781
5026
  engine.data.set(toBytes(row.key), entry);
4782
5027
  }
4783
5028
  const cache2 = { engine, mirror: [], index: /* @__PURE__ */ new Map(), nextExpiry: Infinity };
4784
- resync(rows2, cache2);
4785
- caches.set(rows2, cache2);
5029
+ resync(rows6, cache2);
5030
+ caches.set(rows6, cache2);
4786
5031
  return cache2;
4787
5032
  }
4788
5033
  function upstashReply(reply, base64) {
@@ -4812,17 +5057,17 @@ function upstashRedisOperation(method, path, params, headers, data, _sequence, r
4812
5057
  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 };
4813
5058
  const args = commands.map((c) => c.map((a) => toBytes(String(a))));
4814
5059
  if (args.some((c) => REJECTED.has(c[0].toLowerCase()))) return void 0;
4815
- const rows2 = data[UPSTASH_KEYS];
4816
- const cache2 = engineFor(rows2);
5060
+ const rows6 = data[UPSTASH_KEYS];
5061
+ const cache2 = engineFor(rows6);
4817
5062
  if ("error" in cache2) return { status: 500, body: { error: cache2.error }, collection: UPSTASH_KEYS };
4818
5063
  const { engine } = cache2;
4819
5064
  engine.unsupported.length = 0;
4820
5065
  const replies = args.map((c) => engine.run(c));
4821
5066
  if (engine.unsupported.length) {
4822
- caches.delete(rows2);
5067
+ caches.delete(rows6);
4823
5068
  return void 0;
4824
5069
  }
4825
- const now = Date.now();
5070
+ const now5 = Date.now();
4826
5071
  const touched = /* @__PURE__ */ new Set();
4827
5072
  let full = false;
4828
5073
  for (const c of args) {
@@ -4830,8 +5075,8 @@ function upstashRedisOperation(method, path, params, headers, data, _sequence, r
4830
5075
  if (GLOBAL_WRITES.has(name) || !keys.length && (WRITE_COMMANDS.has(name) || /^eval/.test(name))) full = true;
4831
5076
  for (const k of keys) touched.add(k);
4832
5077
  }
4833
- if (full || cache2.nextExpiry <= now) resync(rows2, cache2);
4834
- else for (const k of touched) syncKey(rows2, cache2, k, now);
5078
+ if (full || cache2.nextExpiry <= now5) resync(rows6, cache2);
5079
+ else for (const k of touched) syncKey(rows6, cache2, k, now5);
4835
5080
  const encoding = headers["upstash-encoding"];
4836
5081
  const base64 = typeof encoding === "string" && encoding.toLowerCase() === "base64";
4837
5082
  const results = replies.map((r) => upstashReply(r, base64));
@@ -4856,7 +5101,353 @@ var init_upstash_redis_twin = __esm({
4856
5101
  fromBytes = (v) => Buffer.from(v, "latin1").toString("utf8");
4857
5102
  caches = /* @__PURE__ */ new WeakMap();
4858
5103
  GLOBAL_WRITES = /* @__PURE__ */ new Set(["flushdb", "flushall"]);
4859
- consistent = (rows2, cache2) => rows2.length === cache2.mirror.length && rows2.every((r, i) => r === cache2.mirror[i]);
5104
+ consistent = (rows6, cache2) => rows6.length === cache2.mirror.length && rows6.every((r, i) => r === cache2.mirror[i]);
5105
+ }
5106
+ });
5107
+
5108
+ // src/runtime/posthog-twin.ts
5109
+ var EVENTS, FLAGS, rows, now, eventRows, flagRows, eventName, distinctId, validProperties, append, flagsFor, flagPayloads, posthogOperation;
5110
+ var init_posthog_twin = __esm({
5111
+ "src/runtime/posthog-twin.ts"() {
5112
+ "use strict";
5113
+ init_twin_clock();
5114
+ EVENTS = "/events";
5115
+ FLAGS = "/feature_flags";
5116
+ rows = (data, path) => data[path] ??= [];
5117
+ now = () => new Date(twinNowMs(17e11)).toISOString();
5118
+ eventRows = (data) => rows(data, EVENTS);
5119
+ flagRows = (data) => rows(data, FLAGS);
5120
+ eventName = (value) => typeof value === "string" && value.trim() ? value : void 0;
5121
+ distinctId = (event) => {
5122
+ const direct = event.distinct_id ?? event.distinctId;
5123
+ const properties = event.properties;
5124
+ const nested = properties && typeof properties === "object" && !Array.isArray(properties) ? properties.distinct_id : void 0;
5125
+ return typeof direct === "string" && direct ? direct : typeof nested === "string" && nested ? nested : void 0;
5126
+ };
5127
+ validProperties = (value) => value === void 0 || !!value && typeof value === "object" && !Array.isArray(value);
5128
+ append = (data, event, sequence) => {
5129
+ const name = eventName(event.event), id = distinctId(event);
5130
+ if (!name || !id) return void 0;
5131
+ if (!validProperties(event.properties)) return void 0;
5132
+ const record3 = {
5133
+ uuid: `ph_${sequence}_${eventRows(data).length}`,
5134
+ event: name,
5135
+ distinct_id: id,
5136
+ properties: event.properties ?? {},
5137
+ timestamp: typeof event.timestamp === "string" ? event.timestamp : now(),
5138
+ sentAt: now(),
5139
+ sequence
5140
+ };
5141
+ eventRows(data).push(record3);
5142
+ return record3;
5143
+ };
5144
+ flagsFor = (data) => Object.fromEntries(flagRows(data).map((flag) => {
5145
+ const key2 = String(flag.key ?? flag.name ?? "");
5146
+ return [key2, flag.active === true || flag.enabled === true];
5147
+ }).filter(([key2]) => key2));
5148
+ flagPayloads = (data) => Object.fromEntries(flagRows(data).filter((flag) => flag.payload !== void 0).map((flag) => [String(flag.key ?? flag.name ?? ""), flag.payload]));
5149
+ posthogOperation = (method, path, params, _headers, data, sequence) => {
5150
+ const route = path.replace(/\/+$/, "") || "/";
5151
+ const respond = (status, body, record3, operation = "read") => ({ status, body, collection: EVENTS, ...record3 ? { record: structuredClone(record3), operation } : { operation } });
5152
+ if (method === "POST" && (route === "/capture" || route === "/e" || route === "/i/v0/e")) {
5153
+ const record3 = append(data, params, sequence);
5154
+ if (!record3) return { status: 400, body: { status: 0, error: "event and distinct_id are required" }, collection: EVENTS };
5155
+ return respond(200, { status: 1 }, record3, "write");
5156
+ }
5157
+ if (method === "POST" && route === "/batch") {
5158
+ const batch = Array.isArray(params.batch) ? params.batch : void 0;
5159
+ if (!batch || !batch.length) return { status: 400, body: { status: 0, error: "batch must be a non-empty array" }, collection: EVENTS };
5160
+ const records = [];
5161
+ for (const item of batch) {
5162
+ if (!item || typeof item !== "object" || Array.isArray(item)) return { status: 400, body: { status: 0, error: "batch entries must be objects" }, collection: EVENTS };
5163
+ const record3 = append(data, item, sequence + records.length);
5164
+ if (!record3) return { status: 400, body: { status: 0, error: "every batch entry needs event and distinct_id" }, collection: EVENTS };
5165
+ records.push(record3);
5166
+ }
5167
+ return { status: 200, body: { status: 1 }, collection: EVENTS, operation: "write", record: { events: records.map((r) => r.event), count: records.length } };
5168
+ }
5169
+ if (method === "POST" && (route === "/decide" || route === "/flags")) {
5170
+ const key2 = typeof params.api_key === "string" ? params.api_key : typeof params.token === "string" ? params.token : void 0;
5171
+ if (!key2) return { status: 400, body: { error: "api_key is required" }, collection: FLAGS };
5172
+ const flags = flagsFor(data), payloads = flagPayloads(data);
5173
+ if (route === "/decide") {
5174
+ 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: {} });
5175
+ }
5176
+ 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 } });
5177
+ }
5178
+ if (method === "GET" && route === "/") return respond(200, { status: "ok" });
5179
+ return void 0;
5180
+ };
5181
+ }
5182
+ });
5183
+
5184
+ // src/runtime/tinybird-twin.ts
5185
+ function parseBody(raw, params) {
5186
+ if (raw !== void 0 && raw.trim()) {
5187
+ const text2 = raw.trim();
5188
+ try {
5189
+ if (text2.startsWith("[")) {
5190
+ const parsed = JSON.parse(text2);
5191
+ return Array.isArray(parsed) ? parsed.filter(isObject2) : "the body must be a JSON object or array";
5192
+ }
5193
+ if (text2.startsWith("{")) return text2.includes("\n") ? text2.split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line)) : [JSON.parse(text2)];
5194
+ return "CSV and TSV bodies are outside the Tinybird twin subset; send NDJSON or JSON";
5195
+ } catch {
5196
+ return "the body is not valid NDJSON or JSON";
5197
+ }
5198
+ }
5199
+ if (Array.isArray(params.data)) return params.data.filter(isObject2);
5200
+ if (isObject2(params.data)) return [params.data];
5201
+ return "the request has no rows";
5202
+ }
5203
+ var EVENTS2, rows2, now2, isObject2, fieldType, tinybirdOperation;
5204
+ var init_tinybird_twin = __esm({
5205
+ "src/runtime/tinybird-twin.ts"() {
5206
+ "use strict";
5207
+ init_twin_clock();
5208
+ EVENTS2 = "/events";
5209
+ rows2 = (data, path) => data[path] ??= [];
5210
+ now2 = () => new Date(twinNowMs(17e11)).toISOString();
5211
+ isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
5212
+ fieldType = (value) => typeof value === "number" ? "Float64" : typeof value === "boolean" ? "Bool" : "String";
5213
+ tinybirdOperation = (method, path, params, _headers, data, sequence, raw) => {
5214
+ const EVENTS_API = "/v0/events", DATASOURCES = "/v0/datasources";
5215
+ if (method === "POST" && (path === EVENTS_API || path === DATASOURCES)) {
5216
+ const datasource = typeof params.name === "string" && params.name ? params.name : void 0;
5217
+ 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 };
5218
+ const parsed = parseBody(raw, params);
5219
+ if (typeof parsed === "string") return { status: 400, body: { error: parsed }, collection: EVENTS2 };
5220
+ if (params.mode !== void 0 && params.mode !== "append" && params.mode !== "replace") return void 0;
5221
+ const target = rows2(data, EVENTS2);
5222
+ if (params.mode === "replace") target.splice(0, Infinity, ...target.filter((row) => row.datasource !== datasource));
5223
+ for (const row of parsed) target.push({ ...structuredClone(row), datasource, timestamp: typeof row.timestamp === "string" ? row.timestamp : now2(), _file: `${datasource}-${sequence}` });
5224
+ return { status: 202, body: { successful_rows: parsed.length, quarantined_rows: 0 }, collection: EVENTS2, operation: "write", record: { datasource, rows: parsed.length } };
5225
+ }
5226
+ if (method === "GET" && path === DATASOURCES) {
5227
+ const seeded = rows2(data, "/datasources");
5228
+ const names = new Set([...seeded.map((row) => String(row.name)), ...rows2(data, EVENTS2).map((row) => String(row.datasource))].filter(Boolean));
5229
+ return { status: 200, body: { datasources: [...names].map((name) => seeded.find((row) => row.name === name) ?? { name, type: "datasource" }) }, collection: DATASOURCES };
5230
+ }
5231
+ if (method === "GET" && path === "/v0/pipes") {
5232
+ const seeded = rows2(data, "/pipes");
5233
+ 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" };
5234
+ }
5235
+ const pipe = /^\/v0\/pipes\/([^/]+?)(?:\.json)?$/.exec(path);
5236
+ if (pipe && method === "GET") {
5237
+ const name = decodeURIComponent(pipe[1]);
5238
+ const seeded = rows2(data, `/pipe:${name}`);
5239
+ const all = rows2(data, EVENTS2);
5240
+ const controls = /* @__PURE__ */ new Set(["format", "limit", "offset", "page", "token", "sql", "q"]);
5241
+ 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));
5242
+ if (params.limit !== void 0) {
5243
+ const limit = Number(params.limit);
5244
+ if (!Number.isInteger(limit) || limit < 0) return { status: 400, body: { error: "limit must be a non-negative integer" }, collection: EVENTS2 };
5245
+ result = result.slice(0, limit);
5246
+ }
5247
+ const sample = result[0] ?? {};
5248
+ 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 };
5249
+ }
5250
+ return void 0;
5251
+ };
5252
+ }
5253
+ });
5254
+
5255
+ // src/runtime/lemonsqueezy-twin.ts
5256
+ import { createHmac } from "crypto";
5257
+ var CHECKOUTS, SUBSCRIPTIONS, rows3, now3, isObject3, SUBSCRIPTION_STATUSES, jsonApiError, resource, lemonsqueezyOperation;
5258
+ var init_lemonsqueezy_twin = __esm({
5259
+ "src/runtime/lemonsqueezy-twin.ts"() {
5260
+ "use strict";
5261
+ init_twin_clock();
5262
+ CHECKOUTS = "/v1/checkouts";
5263
+ SUBSCRIPTIONS = "/v1/subscriptions";
5264
+ rows3 = (data, path) => data[path] ??= [];
5265
+ now3 = () => new Date(twinNowMs(17e11)).toISOString();
5266
+ isObject3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
5267
+ SUBSCRIPTION_STATUSES = ["on_trial", "active", "paused", "past_due", "unpaid", "cancelled", "expired"];
5268
+ jsonApiError = (status, collection, title, detail) => ({
5269
+ status,
5270
+ collection,
5271
+ body: { errors: [{ status: String(status), title, detail }] }
5272
+ });
5273
+ resource = (type, id, attributes) => ({
5274
+ type,
5275
+ id,
5276
+ attributes,
5277
+ links: { self: `https://api.lemonsqueezy.com/v1/${type}/${id}` }
5278
+ });
5279
+ lemonsqueezyOperation = (method, path, params, _headers, data, sequence) => {
5280
+ const checkout = /^\/v1\/checkouts(?:\/([^/]+))?$/.exec(path);
5281
+ if (checkout) {
5282
+ const id = checkout[1] && decodeURIComponent(checkout[1]);
5283
+ if (method === "GET" && !id) {
5284
+ const all = rows3(data, CHECKOUTS);
5285
+ const page = typeof params["page[number]"] === "string" ? Math.max(1, Number(params["page[number]"]) || 1) : 1;
5286
+ const size = typeof params["page[size]"] === "string" ? Math.min(100, Math.max(1, Number(params["page[size]"]) || 10)) : 10;
5287
+ const selected = all.slice((page - 1) * size, page * size);
5288
+ 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 };
5289
+ }
5290
+ if (method === "GET") {
5291
+ const found = rows3(data, CHECKOUTS).find((row) => row.id === id);
5292
+ 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.`);
5293
+ }
5294
+ if (method !== "POST") return void 0;
5295
+ const input = params.data;
5296
+ if (!isObject3(input) || input.type !== "checkouts" || !isObject3(input.attributes)) return jsonApiError(400, CHECKOUTS, "Bad Request", "data.type must be checkouts with an attributes object.");
5297
+ const attributes = input.attributes;
5298
+ 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;
5299
+ 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.");
5300
+ const newId2 = String(rows3(data, CHECKOUTS).length + 1);
5301
+ 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 } };
5302
+ rows3(data, CHECKOUTS).push(record3);
5303
+ 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 };
5304
+ }
5305
+ const subscription = /^\/v1\/subscriptions(?:\/([^/]+))?$/.exec(path);
5306
+ if (subscription) {
5307
+ const id = subscription[1] && decodeURIComponent(subscription[1]);
5308
+ if (method === "GET" && !id) {
5309
+ const all = rows3(data, SUBSCRIPTIONS);
5310
+ return { status: 200, body: { data: all.map((row) => resource("subscriptions", String(row.id), row.attributes)) }, collection: SUBSCRIPTIONS };
5311
+ }
5312
+ if (method === "GET") {
5313
+ const found = rows3(data, SUBSCRIPTIONS).find((row) => row.id === id);
5314
+ 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.`);
5315
+ }
5316
+ if (method === "POST") {
5317
+ const input = params.data;
5318
+ if (!isObject3(input) || input.type !== "subscriptions" || !isObject3(input.attributes)) return jsonApiError(400, SUBSCRIPTIONS, "Unprocessable Entity", "data.type must be subscriptions with an attributes object.");
5319
+ const attributes = input.attributes;
5320
+ if (typeof attributes.store_id !== "number") return jsonApiError(400, SUBSCRIPTIONS, "Unprocessable Entity", "data.attributes.store_id is required.");
5321
+ const newId2 = String(rows3(data, SUBSCRIPTIONS).length + 1);
5322
+ const status = typeof attributes.status === "string" && SUBSCRIPTION_STATUSES.includes(attributes.status) ? attributes.status : "active";
5323
+ const record3 = { id: newId2, attributes: { ...structuredClone(attributes), status, cancelled: status === "cancelled", created_at: now3(), updated_at: now3(), renews_at: now3(), test_mode: true } };
5324
+ rows3(data, SUBSCRIPTIONS).push(record3);
5325
+ return { status: 201, body: { data: resource("subscriptions", newId2, record3.attributes) }, collection: SUBSCRIPTIONS, operation: "write", record: record3 };
5326
+ }
5327
+ if (method === "PATCH") {
5328
+ const index = rows3(data, SUBSCRIPTIONS).findIndex((row) => row.id === id);
5329
+ if (index < 0) return jsonApiError(404, SUBSCRIPTIONS, "Not Found", `The requested subscription ${id} could not be found.`);
5330
+ const input = params.data;
5331
+ if (!isObject3(input) || !isObject3(input.attributes)) return void 0;
5332
+ const changes = input.attributes;
5333
+ if (Object.keys(changes).some((key2) => !["status", "cancelled", "pause"].includes(key2))) return void 0;
5334
+ const attributes = rows3(data, SUBSCRIPTIONS)[index].attributes;
5335
+ 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(", ")}.`);
5336
+ if (changes.status !== void 0) attributes.status = changes.status;
5337
+ if (changes.cancelled !== void 0) attributes.cancelled = changes.cancelled === true;
5338
+ if (attributes.status === "cancelled") attributes.cancelled = true;
5339
+ attributes.updated_at = now3();
5340
+ return { status: 200, body: { data: resource("subscriptions", String(id), attributes) }, collection: SUBSCRIPTIONS, operation: "write", record: rows3(data, SUBSCRIPTIONS)[index] };
5341
+ }
5342
+ return void 0;
5343
+ }
5344
+ return void 0;
5345
+ };
5346
+ }
5347
+ });
5348
+
5349
+ // src/runtime/qstash-twin.ts
5350
+ import { createHmac as createHmac2 } from "crypto";
5351
+ var MESSAGES, SCHEDULES, SIGNING, rows4, now4, header3, forwarded, numberHeader, base64url, signingKeys, qstashOperation;
5352
+ var init_qstash_twin = __esm({
5353
+ "src/runtime/qstash-twin.ts"() {
5354
+ "use strict";
5355
+ init_twin_clock();
5356
+ MESSAGES = "/messages";
5357
+ SCHEDULES = "/schedules";
5358
+ SIGNING = "/signing-keys";
5359
+ rows4 = (data, path) => data[path] ??= [];
5360
+ now4 = () => new Date(twinNowMs(17e11)).toISOString();
5361
+ header3 = (headers, name) => {
5362
+ const value = headers[name];
5363
+ return Array.isArray(value) ? value[0] : value;
5364
+ };
5365
+ 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]));
5366
+ numberHeader = (value) => value !== void 0 && /^\d{1,9}$/.test(value) ? Number(value) : void 0;
5367
+ base64url = (value) => Buffer.from(value).toString("base64url");
5368
+ signingKeys = (data) => {
5369
+ const keys = rows4(data, SIGNING);
5370
+ if (!keys.length) keys.push({ id: "current", current: "sig_current_agenttwin", next: "sig_next_agenttwin" });
5371
+ return keys[0];
5372
+ };
5373
+ qstashOperation = (method, path, params, headers, data, sequence, raw) => {
5374
+ const publish = /^\/v2\/publish\/(.+)$/.exec(path);
5375
+ if (publish) {
5376
+ if (method !== "POST") return void 0;
5377
+ const destination = decodeURIComponent(publish[1]);
5378
+ if (!/^https?:\/\//.test(destination)) return { status: 400, body: { error: "destination must be an http(s) URL" }, collection: MESSAGES };
5379
+ const record3 = {
5380
+ messageId: `msg_${sequence}_${rows4(data, MESSAGES).length}`,
5381
+ destination,
5382
+ body: raw && raw.trim() ? raw : params,
5383
+ headers: forwarded(headers),
5384
+ method: header3(headers, "upstash-method") ?? "POST",
5385
+ retries: numberHeader(header3(headers, "upstash-retries")) ?? 3,
5386
+ delay: numberHeader(header3(headers, "upstash-delay")),
5387
+ notBefore: header3(headers, "upstash-not-before"),
5388
+ cron: header3(headers, "upstash-cron"),
5389
+ callback: header3(headers, "upstash-callback"),
5390
+ failureCallback: header3(headers, "upstash-failure-callback"),
5391
+ createdAt: now4(),
5392
+ status: "pending"
5393
+ };
5394
+ rows4(data, MESSAGES).push(record3);
5395
+ return { status: 200, body: { messageId: record3.messageId }, collection: MESSAGES, operation: "write", record: record3 };
5396
+ }
5397
+ const schedule = /^\/v2\/schedules\/(.+)$/.exec(path);
5398
+ if (schedule && method === "POST") {
5399
+ const destination = decodeURIComponent(schedule[1]);
5400
+ if (!/^https?:\/\//.test(destination)) return { status: 400, body: { error: "destination must be an http(s) URL" }, collection: SCHEDULES };
5401
+ const cron = header3(headers, "upstash-cron");
5402
+ 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 };
5403
+ const record3 = {
5404
+ scheduleId: `sched_${sequence}_${rows4(data, SCHEDULES).length}`,
5405
+ destination,
5406
+ cron: cron ?? null,
5407
+ notBefore: header3(headers, "upstash-not-before") ?? null,
5408
+ body: raw && raw.trim() ? raw : params,
5409
+ headers: forwarded(headers),
5410
+ createdAt: now4(),
5411
+ status: "active"
5412
+ };
5413
+ rows4(data, SCHEDULES).push(record3);
5414
+ return { status: 200, body: { scheduleId: record3.scheduleId }, collection: SCHEDULES, operation: "write", record: record3 };
5415
+ }
5416
+ if (path === "/v2/schedules" && method === "GET") return { status: 200, body: { schedules: rows4(data, SCHEDULES).map((row) => structuredClone(row)) }, collection: SCHEDULES };
5417
+ const scheduleId = /^\/v2\/schedules\/([^/]+)$/.exec(path);
5418
+ if (scheduleId) {
5419
+ const id = decodeURIComponent(scheduleId[1]), list2 = rows4(data, SCHEDULES), index = list2.findIndex((row) => row.scheduleId === id);
5420
+ if (index < 0) return { status: 404, body: { error: "schedule not found" }, collection: SCHEDULES };
5421
+ if (method === "GET") return { status: 200, body: structuredClone(list2[index]), collection: SCHEDULES };
5422
+ if (method === "DELETE") {
5423
+ const [removed] = list2.splice(index, 1);
5424
+ return { status: 200, body: { deleted: removed.scheduleId }, collection: SCHEDULES, operation: "write", record: { deleted: removed.scheduleId } };
5425
+ }
5426
+ return void 0;
5427
+ }
5428
+ if (path === "/v2/messages" && method === "GET") return { status: 200, body: { messages: rows4(data, MESSAGES).map((row) => structuredClone(row)) }, collection: MESSAGES };
5429
+ const messageId = /^\/v2\/messages\/([^/]+)$/.exec(path);
5430
+ if (messageId) {
5431
+ const id = decodeURIComponent(messageId[1]), list2 = rows4(data, MESSAGES), index = list2.findIndex((row) => row.messageId === id);
5432
+ if (index < 0) return { status: 404, body: { error: "message not found" }, collection: MESSAGES };
5433
+ if (method === "GET") return { status: 200, body: structuredClone(list2[index]), collection: MESSAGES };
5434
+ if (method === "DELETE") {
5435
+ const [removed] = list2.splice(index, 1);
5436
+ return { status: 200, body: { deleted: removed.messageId }, collection: MESSAGES, operation: "write", record: { deleted: removed.messageId } };
5437
+ }
5438
+ return void 0;
5439
+ }
5440
+ if (path === "/v2/signing-keys") {
5441
+ if (method === "GET") return { status: 200, body: { ...signingKeys(data) }, collection: SIGNING };
5442
+ if (method === "POST") {
5443
+ const keys = signingKeys(data);
5444
+ keys.next = keys.current;
5445
+ keys.current = `sig_${sequence}_${base64url(String(sequence)).replace(/[^A-Za-z0-9]/g, "").slice(0, 16)}`;
5446
+ return { status: 200, body: { current: keys.current, next: keys.next }, collection: SIGNING, operation: "write", record: { current: keys.current, next: keys.next } };
5447
+ }
5448
+ }
5449
+ return void 0;
5450
+ };
4860
5451
  }
4861
5452
  });
4862
5453
 
@@ -4877,10 +5468,10 @@ function parseGmailRaw(raw) {
4877
5468
  if (headers.some((h) => h.name.toLowerCase() === match[1].toLowerCase())) return { error: "Duplicate MIME headers are outside the verified subset", unsupported: true };
4878
5469
  headers.push({ name: match[1], value: match[2] });
4879
5470
  }
4880
- const header3 = (name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
4881
- if (!header3("to")) return { error: "MIME To header is required", unsupported: false };
4882
- 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 };
4883
- 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 };
5471
+ const header4 = (name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
5472
+ if (!header4("to")) return { error: "MIME To header is required", unsupported: false };
5473
+ 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 };
5474
+ 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 };
4884
5475
  const text2 = mime.slice(boundary + 4);
4885
5476
  return { headers, text: text2, encodedBody: Buffer.from(text2).toString("base64url"), bytes: bytes.length };
4886
5477
  }
@@ -5083,18 +5674,18 @@ var init_gmail_mime = __esm({
5083
5674
  import { createHash as createHash5 } from "crypto";
5084
5675
  function githubOperation(method, path, params, _headers, data, sequence) {
5085
5676
  const errors = (status, message, extra) => ({ status, body: { message, documentation_url: "https://docs.github.com/rest", ...extra ?? {} }, collection: "/repos" });
5086
- if (path === "/repos") return method === "GET" ? ok("/repos", rows(data, "/repos").map((row) => structuredClone(row))) : void 0;
5677
+ if (path === "/repos") return method === "GET" ? ok("/repos", rows5(data, "/repos").map((row) => structuredClone(row))) : void 0;
5087
5678
  const match = /^\/repos\/([^/]+)\/([^/]+)(?:\/(issues|pulls|check-runs)(?:\/(\d+))?(?:\/(comments|merge))?)?$/.exec(path);
5088
5679
  if (!match) return void 0;
5089
- const [, owner, name, resource, id, sub] = match;
5680
+ const [, owner, name, resource2, id, sub] = match;
5090
5681
  const repo = `${owner}/${name}`;
5091
- 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" });
5092
- if (!resource) {
5682
+ 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" });
5683
+ if (!resource2) {
5093
5684
  if (method !== "GET") return void 0;
5094
- const repository = rows(data, "/repos").find((r) => r.name === repo || r.full_name === repo);
5685
+ const repository = rows5(data, "/repos").find((r) => r.name === repo || r.full_name === repo);
5095
5686
  return ok("/repos", structuredClone(repository));
5096
5687
  }
5097
- if (resource === "check-runs") {
5688
+ if (resource2 === "check-runs") {
5098
5689
  if (method !== "POST" || id) return void 0;
5099
5690
  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" }] });
5100
5691
  const allowed = ["name", "head_sha", "status", "conclusion"];
@@ -5102,11 +5693,11 @@ function githubOperation(method, path, params, _headers, data, sequence) {
5102
5693
  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" }] });
5103
5694
  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" }] });
5104
5695
  const run4 = { 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() };
5105
- rows(data, "/check-runs").push(run4);
5696
+ rows5(data, "/check-runs").push(run4);
5106
5697
  return created("/check-runs", structuredClone(run4), run4);
5107
5698
  }
5108
- if (resource === "issues") {
5109
- const inRepo = rows(data, "/issues").filter((r) => r.repo === repo);
5699
+ if (resource2 === "issues") {
5700
+ const inRepo = rows5(data, "/issues").filter((r) => r.repo === repo);
5110
5701
  if (method === "GET" && !id && !sub) {
5111
5702
  if (Object.keys(params).some((k) => !["state", "page", "per_page"].includes(k))) return void 0;
5112
5703
  const page = pagination(params, 30, 100);
@@ -5123,7 +5714,7 @@ function githubOperation(method, path, params, _headers, data, sequence) {
5123
5714
  if (typeof params.title !== "string" || !params.title) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "title", code: "missing_field" }] });
5124
5715
  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" }] });
5125
5716
  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 };
5126
- rows(data, "/issues").push(issue2);
5717
+ rows5(data, "/issues").push(issue2);
5127
5718
  return created("/issues", structuredClone(issue2), issue2);
5128
5719
  }
5129
5720
  const issue = id ? inRepo.find((r) => String(r.number) === id) : void 0;
@@ -5148,14 +5739,14 @@ function githubOperation(method, path, params, _headers, data, sequence) {
5148
5739
  if (typeof params.body !== "string" || !params.body) return errors(422, "Validation Failed", { errors: [{ resource: "IssueComment", field: "body", code: "missing_field" }] });
5149
5740
  if (Object.keys(params).some((k) => k !== "body")) return void 0;
5150
5741
  const comment = { id: `github_at_${sequence}`, repo, issue_number: issue.number, body: params.body, user: { login: "agenttwin-test" }, created_at: iso2(), updated_at: iso2() };
5151
- rows(data, "/comments").push(comment);
5742
+ rows5(data, "/comments").push(comment);
5152
5743
  return created("/comments", structuredClone(comment), comment);
5153
5744
  }
5154
- 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)));
5745
+ 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)));
5155
5746
  return void 0;
5156
5747
  }
5157
- if (resource === "pulls") {
5158
- const inRepo = rows(data, "/pulls").filter((r) => r.repo === repo);
5748
+ if (resource2 === "pulls") {
5749
+ const inRepo = rows5(data, "/pulls").filter((r) => r.repo === repo);
5159
5750
  const pull = id ? inRepo.find((r) => String(r.number) === id) : void 0;
5160
5751
  if (method === "GET" && !id && !sub) {
5161
5752
  if (Object.keys(params).some((k) => k !== "state")) return void 0;
@@ -5189,45 +5780,45 @@ function linearOperation(method, path, params, _headers, data, sequence) {
5189
5780
  const isMutation = /\bmutation\b/.test(query.slice(0, query.indexOf("{") + 1));
5190
5781
  const root = new RegExp(isMutation ? "\\bmutation\\b[^{]*\\{\\s*(\\w+)" : "\\bquery\\b[^{]*\\{\\s*(\\w+)").exec(query);
5191
5782
  if (!root) return void 0;
5192
- const variables = isObject2(params.variables) ? params.variables : {};
5783
+ const variables = isObject4(params.variables) ? params.variables : {};
5193
5784
  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);
5194
5785
  const input = variables.input ?? void 0;
5195
5786
  if (!isMutation) {
5196
5787
  if (root[1] === "viewer") {
5197
5788
  if (Object.keys(variables).length) return void 0;
5198
- return ok("/users", { data: { viewer: rows(data, "/users")[0] ?? { id: "linear_at_viewer", name: "Test User", email: "user@example.test", displayName: "Test User" } } });
5789
+ return ok("/users", { data: { viewer: rows5(data, "/users")[0] ?? { id: "linear_at_viewer", name: "Test User", email: "user@example.test", displayName: "Test User" } } });
5199
5790
  }
5200
5791
  if (root[1] === "issues") {
5201
5792
  if (Object.keys(variables).length) return void 0;
5202
- return ok("/issues", { data: { issues: { nodes: rows(data, "/issues").map((row) => structuredClone(row)) } } });
5793
+ return ok("/issues", { data: { issues: { nodes: rows5(data, "/issues").map((row) => structuredClone(row)) } } });
5203
5794
  }
5204
5795
  if (root[1] === "projects") {
5205
5796
  if (Object.keys(variables).length) return void 0;
5206
- return ok("/projects", { data: { projects: { nodes: rows(data, "/projects").map((row) => structuredClone(row)) } } });
5797
+ return ok("/projects", { data: { projects: { nodes: rows5(data, "/projects").map((row) => structuredClone(row)) } } });
5207
5798
  }
5208
5799
  if (root[1] === "issue") {
5209
- const issue = rows(data, "/issues").find((r) => r.id === arg2("id"));
5800
+ const issue = rows5(data, "/issues").find((r) => r.id === arg2("id"));
5210
5801
  if (Object.keys(variables).some((k) => k !== "id") || arg2("id") === void 0) return void 0;
5211
5802
  return issue ? ok("/issues", { data: { issue: structuredClone(issue) } }) : notFoundNode("Issue");
5212
5803
  }
5213
5804
  if (root[1] === "project") {
5214
- const project = rows(data, "/projects").find((r) => r.id === arg2("id"));
5805
+ const project = rows5(data, "/projects").find((r) => r.id === arg2("id"));
5215
5806
  if (Object.keys(variables).some((k) => k !== "id") || arg2("id") === void 0) return void 0;
5216
5807
  return project ? ok("/projects", { data: { project: structuredClone(project) } }) : notFoundNode("Project");
5217
5808
  }
5218
5809
  return void 0;
5219
5810
  }
5220
5811
  if (root[1] === "issueCreate") {
5221
- if (!isObject2(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
5812
+ if (!isObject4(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
5222
5813
  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;
5223
5814
  if (typeof input.title !== "string" || !input.title) return { status: 200, body: { data: null, errors: [{ message: "Issue title required" }] }, collection: "/issues" };
5224
5815
  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() };
5225
- rows(data, "/issues").push(issue);
5816
+ rows5(data, "/issues").push(issue);
5226
5817
  return write2(200, "/issues", { data: { issueCreate: { success: true, lastSyncId: sequence, issue: structuredClone(issue) } } }, issue);
5227
5818
  }
5228
5819
  if (root[1] === "issueUpdate") {
5229
- if (!isObject2(input) || arg2("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
5230
- const issue = rows(data, "/issues").find((r) => r.id === arg2("id"));
5820
+ if (!isObject4(input) || arg2("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
5821
+ const issue = rows5(data, "/issues").find((r) => r.id === arg2("id"));
5231
5822
  if (!issue) return notFoundNode("Issue");
5232
5823
  if (Object.keys(input).some((k) => !["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k))) return void 0;
5233
5824
  for (const [k, v] of Object.entries(input)) if (["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k)) issue[k] = v;
@@ -5235,13 +5826,13 @@ function linearOperation(method, path, params, _headers, data, sequence) {
5235
5826
  return write2(200, "/issues", { data: { issueUpdate: { success: true, issue: structuredClone(issue) } } }, issue);
5236
5827
  }
5237
5828
  if (root[1] === "commentCreate") {
5238
- if (!isObject2(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
5829
+ if (!isObject4(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
5239
5830
  if (Object.keys(input).some((k) => !["issueId", "body"].includes(k))) return void 0;
5240
- const issue = rows(data, "/issues").find((r) => r.id === input.issueId);
5831
+ const issue = rows5(data, "/issues").find((r) => r.id === input.issueId);
5241
5832
  if (!issue) return notFoundNode("Issue");
5242
5833
  if (typeof input.body !== "string" || !input.body) return { status: 200, body: { data: null, errors: [{ message: "Comment body required" }] }, collection: "/comments" };
5243
- const comment = { id: `linear_at_${sequence}`, issueId: input.issueId, body: input.body, userId: rows(data, "/users")[0]?.id ?? "linear_at_viewer", createdAt: iso2() };
5244
- rows(data, "/comments").push(comment);
5834
+ const comment = { id: `linear_at_${sequence}`, issueId: input.issueId, body: input.body, userId: rows5(data, "/users")[0]?.id ?? "linear_at_viewer", createdAt: iso2() };
5835
+ rows5(data, "/comments").push(comment);
5245
5836
  return write2(200, "/comments", { data: { commentCreate: { success: true, comment: structuredClone(comment) } } }, comment);
5246
5837
  }
5247
5838
  return void 0;
@@ -5253,24 +5844,24 @@ function notionOperation(method, path, params, headers, data, sequence) {
5253
5844
  if (path === "/v1/pages") {
5254
5845
  if (method !== "POST") return void 0;
5255
5846
  if (Object.keys(params).some((k) => !["parent", "properties"].includes(k))) return void 0;
5256
- const parent = isObject2(params.parent) ? params.parent : void 0;
5847
+ const parent = isObject4(params.parent) ? params.parent : void 0;
5257
5848
  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.");
5258
- const database = rows(data, "/databases").find((d) => d.id === parent.database_id);
5849
+ const database = rows5(data, "/databases").find((d) => d.id === parent.database_id);
5259
5850
  if (!database) return notionError("/pages", 404, "object_not_found", "Could not find database with ID.");
5260
- if (!isObject2(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be defined.");
5851
+ if (!isObject4(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be defined.");
5261
5852
  const page = notionPage(detUuid(`page:${sequence}`), { type: "database_id", database_id: database.id }, structuredClone(params.properties));
5262
- rows(data, "/pages").push(page);
5853
+ rows5(data, "/pages").push(page);
5263
5854
  return { status: 200, body: structuredClone(page), collection: "/pages", record: structuredClone(page), operation: "write" };
5264
5855
  }
5265
5856
  const pageMatch = /^\/v1\/pages\/([^/]+)$/.exec(path);
5266
5857
  if (pageMatch) {
5267
- const page = rows(data, "/pages").find((p) => p.id === pageMatch[1]);
5858
+ const page = rows5(data, "/pages").find((p) => p.id === pageMatch[1]);
5268
5859
  if (!page) return notionError("/pages", 404, "object_not_found", "Could not find page with ID.");
5269
5860
  if (method === "GET") return ok("/pages", structuredClone(page));
5270
5861
  if (method === "PATCH") {
5271
5862
  if (Object.keys(params).some((k) => !["properties", "archived", "in_trash"].includes(k))) return void 0;
5272
5863
  if (params.properties !== void 0) {
5273
- if (!isObject2(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be an object.");
5864
+ if (!isObject4(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be an object.");
5274
5865
  Object.assign(page.properties, structuredClone(params.properties));
5275
5866
  }
5276
5867
  if (params.archived !== void 0) {
@@ -5284,7 +5875,7 @@ function notionOperation(method, path, params, headers, data, sequence) {
5284
5875
  }
5285
5876
  const databaseMatch = /^\/v1\/databases\/([^/]+)(?:\/(query))?$/.exec(path);
5286
5877
  if (databaseMatch) {
5287
- const database = rows(data, "/databases").find((d) => d.id === databaseMatch[1]);
5878
+ const database = rows5(data, "/databases").find((d) => d.id === databaseMatch[1]);
5288
5879
  if (!database) return notionError("/databases", 404, "object_not_found", "Could not find database with ID.");
5289
5880
  if (!databaseMatch[2]) {
5290
5881
  if (method !== "GET") return void 0;
@@ -5298,13 +5889,13 @@ function notionOperation(method, path, params, headers, data, sequence) {
5298
5889
  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.");
5299
5890
  limit = Number(params.page_size);
5300
5891
  }
5301
- const pages = rows(data, "/pages").filter((p) => p.parent && p.parent.database_id === database.id);
5892
+ const pages = rows5(data, "/pages").filter((p) => p.parent && p.parent.database_id === database.id);
5302
5893
  if (params.filter !== void 0) {
5303
5894
  const filter = params.filter;
5304
- if (!isObject2(filter) || Object.keys(filter).length !== 2 || typeof filter.property !== "string") return void 0;
5895
+ if (!isObject4(filter) || Object.keys(filter).length !== 2 || typeof filter.property !== "string") return void 0;
5305
5896
  const [condition] = Object.keys(filter).filter((k) => k !== "property");
5306
5897
  if (!["title", "rich_text", "number", "select", "status", "checkbox"].includes(condition)) return void 0;
5307
- const expected = isObject2(filter[condition]) ? filter[condition].equals : void 0;
5898
+ const expected = isObject4(filter[condition]) ? filter[condition].equals : void 0;
5308
5899
  if (expected === void 0 || Object.keys(filter[condition]).length !== 1) return void 0;
5309
5900
  const property = filter.property;
5310
5901
  const results = pages.filter((p) => notionPropValue(p.properties[property]) === expected);
@@ -5317,15 +5908,15 @@ function notionOperation(method, path, params, headers, data, sequence) {
5317
5908
  if (method !== "PATCH" || blockMatch[2] !== "children") return void 0;
5318
5909
  if (Object.keys(params).some((k) => k !== "children")) return void 0;
5319
5910
  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.");
5320
- if (!params.children.every(isObject2)) return notionError("/blocks", 400, "validation_error", "children should be block objects.");
5911
+ if (!params.children.every(isObject4)) return notionError("/blocks", 400, "validation_error", "children should be block objects.");
5321
5912
  if (params.children.some((c) => typeof c.type !== "string" || !c.type)) return notionError("/blocks", 400, "validation_error", "Each child block requires a type.");
5322
- const page = rows(data, "/pages").find((p) => p.id === blockMatch[1]);
5323
- const block = rows(data, "/blocks").find((b) => b.id === blockMatch[1]);
5913
+ const page = rows5(data, "/pages").find((p) => p.id === blockMatch[1]);
5914
+ const block = rows5(data, "/blocks").find((b) => b.id === blockMatch[1]);
5324
5915
  if (!page && !block) return notionError("/blocks", 404, "object_not_found", "Could not find block with ID.");
5325
5916
  const parent = page ? { type: "page_id", page_id: page.id } : { type: "block_id", block_id: block.id };
5326
5917
  const createdBlocks = params.children.map((child, index) => {
5327
5918
  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) };
5328
- rows(data, "/blocks").push(record3);
5919
+ rows5(data, "/blocks").push(record3);
5329
5920
  return record3;
5330
5921
  });
5331
5922
  return write2(200, "/blocks", { object: "list", results: structuredClone(createdBlocks), has_more: false, next_cursor: null, type: "block", block: {} }, createdBlocks[createdBlocks.length - 1]);
@@ -5337,8 +5928,8 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5337
5928
  if (!match) return void 0;
5338
5929
  const [, object4, search, id] = match;
5339
5930
  const collection = `/crm/v3/objects/${object4}`;
5340
- const properties = isObject2(params.properties) ? params.properties : void 0;
5341
- const validProperties = (value) => Object.values(value).every((v) => ["string", "number", "boolean", "object"].includes(v === null ? "object" : typeof v));
5931
+ const properties = isObject4(params.properties) ? params.properties : void 0;
5932
+ const validProperties2 = (value) => Object.values(value).every((v) => ["string", "number", "boolean", "object"].includes(v === null ? "object" : typeof v));
5342
5933
  if (search) {
5343
5934
  if (method !== "POST" || id) return void 0;
5344
5935
  if (Object.keys(params).some((k) => !["query", "filterGroups", "limit", "after", "properties", "sorts"].includes(k))) return void 0;
@@ -5348,7 +5939,7 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5348
5939
  const searchAfter = boundedInt(params.after, 0, Number.MAX_SAFE_INTEGER);
5349
5940
  if (searchAfter === null) return badRequest(collection, { status: "error", message: "Unable to process: after must be a nonnegative integer offset", category: "VALIDATION_ERROR" });
5350
5941
  const limit = searchLimit ?? 10, after = searchAfter ?? 0;
5351
- let filtered = rows(data, collection);
5942
+ let filtered = rows5(data, collection);
5352
5943
  if (params.query !== void 0) {
5353
5944
  if (typeof params.query !== "string") return void 0;
5354
5945
  const needle = params.query.toLowerCase();
@@ -5357,9 +5948,9 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5357
5948
  if (params.filterGroups !== void 0) {
5358
5949
  if (!Array.isArray(params.filterGroups) || params.filterGroups.length !== 1) return void 0;
5359
5950
  const group = params.filterGroups[0];
5360
- if (!isObject2(group) || Object.keys(group).some((k) => k !== "filters") || !Array.isArray(group.filters) || !group.filters.length || group.filters.length > 3) return void 0;
5951
+ if (!isObject4(group) || Object.keys(group).some((k) => k !== "filters") || !Array.isArray(group.filters) || !group.filters.length || group.filters.length > 3) return void 0;
5361
5952
  for (const filter of group.filters) {
5362
- 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;
5953
+ 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;
5363
5954
  const propertyName = filter.propertyName;
5364
5955
  filtered = filtered.filter((r) => r.properties[propertyName] === filter.value);
5365
5956
  }
@@ -5374,20 +5965,20 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5374
5965
  if (listLimit === null) return badRequest(collection, { status: "error", message: "Unable to process: limit must be between 1 and 100", category: "VALIDATION_ERROR" });
5375
5966
  const listAfter = boundedInt(params.after, 0, Number.MAX_SAFE_INTEGER);
5376
5967
  if (listAfter === null) return badRequest(collection, { status: "error", message: "Unable to process: after must be a nonnegative integer offset", category: "VALIDATION_ERROR" });
5377
- const page = rows(data, collection).slice(listAfter ?? 0, (listAfter ?? 0) + (listLimit ?? 10));
5378
- return ok(collection, { total: rows(data, collection).length, results: page.map((r) => hubspotEnvelope(r)) });
5968
+ const page = rows5(data, collection).slice(listAfter ?? 0, (listAfter ?? 0) + (listLimit ?? 10));
5969
+ return ok(collection, { total: rows5(data, collection).length, results: page.map((r) => hubspotEnvelope(r)) });
5379
5970
  }
5380
5971
  if (method !== "POST") return void 0;
5381
- 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 ${object4}`, category: "VALIDATION_ERROR" });
5382
- const record4 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso2(), updatedAt: iso2() };
5383
- rows(data, collection).push(record4);
5972
+ 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 ${object4}`, category: "VALIDATION_ERROR" });
5973
+ const record4 = { id: uniqueId(rows5(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso2(), updatedAt: iso2() };
5974
+ rows5(data, collection).push(record4);
5384
5975
  return created(collection, hubspotEnvelope(record4), record4);
5385
5976
  }
5386
- const record3 = rows(data, collection).find((r) => r.id === id);
5977
+ const record3 = rows5(data, collection).find((r) => r.id === id);
5387
5978
  if (!record3) return { status: 404, body: { status: "error", message: `Object not found: ${object4} with id ${id}`, category: "OBJECT_NOT_FOUND" }, collection };
5388
5979
  if (method === "GET") return ok(collection, hubspotEnvelope(record3));
5389
5980
  if (method === "PATCH") {
5390
- 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" });
5981
+ 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" });
5391
5982
  Object.assign(record3.properties, structuredClone(properties));
5392
5983
  record3.updatedAt = iso2();
5393
5984
  return write2(200, collection, hubspotEnvelope(record3), record3);
@@ -5397,10 +5988,10 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
5397
5988
  function shopifyOperation(method, path, params, _headers, data, sequence) {
5398
5989
  const match = new RegExp(`^/admin/api/${SHOPIFY_VERSION}/(products|orders|customers)(?:/(\\d+))?\\.json$`).exec(path);
5399
5990
  if (!match) return void 0;
5400
- const [, resource, id] = match;
5401
- const collection = `/admin/${resource}`;
5402
- const wrap = resource === "products" ? "product" : resource === "orders" ? "order" : "customer";
5403
- const rowsIn2 = rows(data, collection);
5991
+ const [, resource2, id] = match;
5992
+ const collection = `/admin/${resource2}`;
5993
+ const wrap = resource2 === "products" ? "product" : resource2 === "orders" ? "order" : "customer";
5994
+ const rowsIn2 = rows5(data, collection);
5404
5995
  const notFoundShopify = () => notFound(collection, { errors: "Not Found" });
5405
5996
  const enriched = (record4) => ({ ...structuredClone(record4), created_at: record4.created_at ?? iso2(), updated_at: iso2() });
5406
5997
  if (!id) {
@@ -5413,22 +6004,22 @@ function shopifyOperation(method, path, params, _headers, data, sequence) {
5413
6004
  if (!Number.isInteger(Number(params.since_id)) || Number(params.since_id) < 0) return badRequest(collection, { errors: "since_id must be a nonnegative integer" });
5414
6005
  filtered = filtered.filter((r) => Number(r.id) > Number(params.since_id));
5415
6006
  }
5416
- return ok(collection, { [`${resource}`]: filtered.slice(0, page.limit).map(enriched) });
6007
+ return ok(collection, { [`${resource2}`]: filtered.slice(0, page.limit).map(enriched) });
5417
6008
  }
5418
6009
  if (method !== "POST") return void 0;
5419
- if (Object.keys(params).some((k) => k !== wrap) || !isObject2(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
6010
+ if (Object.keys(params).some((k) => k !== wrap) || !isObject4(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
5420
6011
  const body = params[wrap];
5421
- if (resource === "products" && (typeof body.title !== "string" || !body.title)) return { status: 422, body: { errors: { title: ["can't be blank"] } }, collection };
5422
- if (resource === "orders") {
5423
- 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 };
6012
+ if (resource2 === "products" && (typeof body.title !== "string" || !body.title)) return { status: 422, body: { errors: { title: ["can't be blank"] } }, collection };
6013
+ if (resource2 === "orders") {
6014
+ 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 };
5424
6015
  if (body.line_items.some((item) => Object.keys(item).some((k) => !["title", "quantity", "price", "sku"].includes(k)))) return void 0;
5425
6016
  }
5426
- 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];
6017
+ 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];
5427
6018
  if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
5428
- const record4 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource] + sequence), created_at: iso2(), updated_at: iso2() };
5429
- 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: [] });
5430
- 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 });
5431
- 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 });
6019
+ const record4 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource2] + sequence), created_at: iso2(), updated_at: iso2() };
6020
+ 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: [] });
6021
+ 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 });
6022
+ 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 });
5432
6023
  rowsIn2.push(record4);
5433
6024
  return created(collection, { [wrap]: enriched(record4) }, record4);
5434
6025
  }
@@ -5436,12 +6027,12 @@ function shopifyOperation(method, path, params, _headers, data, sequence) {
5436
6027
  if (!record3) return notFoundShopify();
5437
6028
  if (method === "GET") return ok(collection, { [wrap]: enriched(record3) });
5438
6029
  if (method === "PUT") {
5439
- if (Object.keys(params).some((k) => k !== wrap) || !isObject2(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
6030
+ if (Object.keys(params).some((k) => k !== wrap) || !isObject4(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
5440
6031
  const body = params[wrap];
5441
- 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];
6032
+ 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];
5442
6033
  if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
5443
6034
  for (const [k, v] of Object.entries(body)) record3[k] = v;
5444
- if (resource === "products" && body.title !== void 0) record3.handle = shopifySlug(String(body.title));
6035
+ if (resource2 === "products" && body.title !== void 0) record3.handle = shopifySlug(String(body.title));
5445
6036
  record3.updated_at = iso2();
5446
6037
  return write2(200, collection, { [wrap]: enriched(record3) }, record3);
5447
6038
  }
@@ -5454,22 +6045,22 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
5454
6045
  if (!id) {
5455
6046
  if (method === "GET") {
5456
6047
  if (Object.keys(params).some((k) => k !== "name")) return void 0;
5457
- const filtered = params.name === void 0 ? rows(data, "/monitors") : rows(data, "/monitors").filter((m) => typeof params.name === "string" && String(m.name).includes(params.name));
6048
+ const filtered = params.name === void 0 ? rows5(data, "/monitors") : rows5(data, "/monitors").filter((m) => typeof params.name === "string" && String(m.name).includes(params.name));
5458
6049
  return ok("/monitors", filtered.map((row) => structuredClone(row)));
5459
6050
  }
5460
6051
  if (method !== "POST") return void 0;
5461
6052
  if (Object.keys(params).some((k) => !["name", "type", "query", "message", "tags", "options", "priority"].includes(k))) return void 0;
5462
6053
  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"] });
5463
- 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() };
5464
- rows(data, "/monitors").push(monitor2);
6054
+ 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() };
6055
+ rows5(data, "/monitors").push(monitor2);
5465
6056
  return { status: 200, body: structuredClone(monitor2), collection: "/monitors", record: structuredClone(monitor2), operation: "write" };
5466
6057
  }
5467
- const monitor = rows(data, "/monitors").find((m) => String(m.id) === id);
6058
+ const monitor = rows5(data, "/monitors").find((m) => String(m.id) === id);
5468
6059
  if (!monitor) return notFound("/monitors", { errors: ["Monitor not found"] });
5469
6060
  if (method === "GET" && !mute) return ok("/monitors", structuredClone(monitor));
5470
6061
  if (method === "POST" && mute === "mute") {
5471
6062
  if (Object.keys(params).some((k) => !["scope", "end"].includes(k))) return void 0;
5472
- const options = isObject2(monitor.options) ? monitor.options : {};
6063
+ const options = isObject4(monitor.options) ? monitor.options : {};
5473
6064
  monitor.options = { ...options, muted: true };
5474
6065
  monitor.modified = iso2();
5475
6066
  return write2(200, "/monitors", structuredClone(monitor), monitor);
@@ -5481,14 +6072,14 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
5481
6072
  if (Object.keys(params).some((k) => !["title", "text", "tags", "priority", "alert_type", "source"].includes(k))) return void 0;
5482
6073
  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"] });
5483
6074
  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" };
5484
- rows(data, "/events").push(event);
6075
+ rows5(data, "/events").push(event);
5485
6076
  return { status: 200, body: { status: "ok", event: structuredClone(event) }, collection: "/events", record: structuredClone(event), operation: "write" };
5486
6077
  }
5487
6078
  if (method === "GET") {
5488
6079
  if (Object.keys(params).some((k) => !["start", "end", "priority", "tags", "sources"].includes(k))) return void 0;
5489
6080
  if (params.start === void 0 || params.end === void 0) return badRequest("/events", { errors: ["start and end parameters are required"] });
5490
6081
  if (!Number.isInteger(Number(params.start)) || !Number.isInteger(Number(params.end))) return badRequest("/events", { errors: ["start and end parameters must be integers"] });
5491
- let filtered = rows(data, "/events").filter((e) => Number(e.date_happened) >= Number(params.start) && Number(e.date_happened) <= Number(params.end));
6082
+ let filtered = rows5(data, "/events").filter((e) => Number(e.date_happened) >= Number(params.start) && Number(e.date_happened) <= Number(params.end));
5492
6083
  if (params.priority !== void 0) filtered = filtered.filter((e) => e.priority === params.priority);
5493
6084
  if (params.tags !== void 0) {
5494
6085
  if (typeof params.tags !== "string") return void 0;
@@ -5508,14 +6099,14 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
5508
6099
  if (to <= from) return badRequest("/api/v1/query", { errors: ["to must be after from"] });
5509
6100
  const parsed = /^(?:avg|min|max|sum):([a-zA-Z0-9_.]+)\{[^}]*\}$/.exec(params.query);
5510
6101
  if (!parsed) return badRequest("/api/v1/query", { errors: ["query must look like avg:metric.name{scope}"] });
5511
- const metric = rows(data, "/metrics").find((m) => m.metric === parsed[1]);
6102
+ const metric = rows5(data, "/metrics").find((m) => m.metric === parsed[1]);
5512
6103
  const pointlist = metric ? metric.points.filter(([ts]) => ts >= from && ts <= to) : [];
5513
6104
  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 }] });
5514
6105
  }
5515
6106
  return void 0;
5516
6107
  }
5517
- function startingRows(adapter, path, rows2, nowMs) {
5518
- const copy = structuredClone(rows2);
6108
+ function startingRows(adapter, path, rows6, nowMs) {
6109
+ const copy = structuredClone(rows6);
5519
6110
  if (adapter !== "gmail" || path !== GMAIL_MESSAGES) return copy;
5520
6111
  const at = nowMs - 6e4;
5521
6112
  for (const message of copy) {
@@ -5528,14 +6119,27 @@ function startingRows(adapter, path, rows2, nowMs) {
5528
6119
  return copy;
5529
6120
  }
5530
6121
  function gmailQueryMatcher(q) {
5531
- const clauses = q.trim().split(/\s+OR\s+/);
5532
- const parsed = [];
5533
- for (const clause of clauses) {
5534
- const terms = clause.trim().split(/\s+/).map((token) => /^(from|to):([^\s()"]+@[^\s()"]+)$/i.exec(token));
5535
- if (!terms.length || terms.some((t) => !t)) return void 0;
5536
- parsed.push(terms.map((t) => ({ field: t[1].toLowerCase(), address: t[2].toLowerCase() })));
5537
- }
5538
- return (message) => parsed.some((terms) => terms.every((t) => headerAddresses(gmailHeader(message, t.field)).includes(t.address)));
6122
+ const clauses = q.trim().split(/\s+OR\s+/).map((clause) => clause.trim()).filter(Boolean);
6123
+ if (!clauses.length) return () => true;
6124
+ const text2 = (message) => [message.snippet, gmailHeader(message, "subject"), gmailHeader(message, "from"), gmailHeader(message, "to")].filter((v) => typeof v === "string").join(" ").toLowerCase();
6125
+ const matchers = clauses.map((clause) => {
6126
+ const tests = clause.split(/\s+/).map((token) => {
6127
+ const messageId = /^rfc822msgid:(.+)$/i.exec(token);
6128
+ if (messageId) {
6129
+ const want2 = messageId[1].replace(/[<>]/g, "").toLowerCase();
6130
+ return (message) => String(gmailHeader(message, "message-id") ?? "").replace(/[<>]/g, "").toLowerCase() === want2;
6131
+ }
6132
+ const address2 = /^(from|to):(.+)$/i.exec(token);
6133
+ if (address2) {
6134
+ const want2 = address2[2].toLowerCase();
6135
+ return (message) => headerAddresses(gmailHeader(message, address2[1].toLowerCase())).some((found) => found.includes(want2));
6136
+ }
6137
+ const want = token.toLowerCase();
6138
+ return (message) => text2(message).includes(want);
6139
+ });
6140
+ return (message) => tests.every((test) => test(message));
6141
+ });
6142
+ return (message) => matchers.some((match) => match(message));
5539
6143
  }
5540
6144
  function gmailBatch(params, headers, data, sequence, raw) {
5541
6145
  if (raw === void 0 || Object.keys(params).length) return void 0;
@@ -5616,9 +6220,29 @@ function gmailDraftWrite(data, raw, threadIdInput, sequence, index) {
5616
6220
  return gmailStoreDraft(data, mime, threadId, sequence, index);
5617
6221
  }
5618
6222
  function gmailOperation(method, path, params, headers, data, sequence, raw) {
5619
- const MESSAGES = GMAIL_MESSAGES, LABELS = "/gmail/v1/users/me/labels";
5620
- const fail = (status, message) => googleError(MESSAGES, status, message);
6223
+ const MESSAGES2 = GMAIL_MESSAGES, LABELS = "/gmail/v1/users/me/labels";
6224
+ const fail = (status, message) => googleError(MESSAGES2, status, message);
5621
6225
  if (path === "/batch/gmail/v1") return method === "POST" ? gmailBatch(params, headers, data, sequence, raw) : void 0;
6226
+ if (path === `${MESSAGES2}/batchModify`) {
6227
+ if (method !== "POST" || Object.keys(params).some((k) => !["ids", "addLabelIds", "removeLabelIds"].includes(k))) return void 0;
6228
+ 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.");
6229
+ if (params.ids.length > 1e3) return fail(400, "ids must contain at most 1000 message ids.");
6230
+ const list2 = (v) => v === void 0 ? [] : Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
6231
+ const add = list2(params.addLabelIds), remove2 = list2(params.removeLabelIds);
6232
+ if (!add || !remove2) return fail(400, "Invalid label list.");
6233
+ const known2 = gmailLabelKnown(data), unknown = [...add, ...remove2].find((id) => !known2(id));
6234
+ if (unknown) return fail(400, `Invalid label: ${unknown}`);
6235
+ const targets = rowsIn(data, MESSAGES2).filter((m) => params.ids.includes(String(m.id)));
6236
+ const next = gmailNextHistoryId(data);
6237
+ for (const message of targets) {
6238
+ const labels = new Set(message.labelIds ?? []);
6239
+ for (const l of add) labels.add(l);
6240
+ for (const l of remove2) labels.delete(l);
6241
+ message.labelIds = [...labels];
6242
+ message.historyId = next;
6243
+ }
6244
+ return { status: 204, body: null, collection: MESSAGES2, operation: "write", record: { batchModify: params.ids.length, matched: targets.length, addLabelIds: add, removeLabelIds: remove2 } };
6245
+ }
5622
6246
  const uploadMatch = /^\/upload\/gmail\/v1\/users\/me\/drafts(?:\/([^/]+))?$/.exec(path);
5623
6247
  if (uploadMatch) {
5624
6248
  const id = uploadMatch[1] === void 0 ? void 0 : decodeURIComponent(uploadMatch[1]);
@@ -5640,25 +6264,52 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5640
6264
  return gmailDraftWrite(data, upload.raw, threadId === null ? void 0 : threadId, sequence, index);
5641
6265
  }
5642
6266
  if (path === GMAIL_THREADS) {
5643
- if (method !== "GET" || Object.keys(params).some((k) => !["q", "maxResults", "labelIds"].includes(k))) return void 0;
6267
+ if (method !== "GET" || Object.keys(params).some((k) => !["q", "maxResults", "labelIds", "pageToken", "includeSpamTrash"].includes(k))) return void 0;
5644
6268
  if (params.q !== void 0 && typeof params.q !== "string") return googleError(GMAIL_THREADS, 400, "q must be a string.");
6269
+ if (params.includeSpamTrash !== void 0 && !["true", "false", true, false].includes(params.includeSpamTrash)) return googleError(GMAIL_THREADS, 400, "includeSpamTrash must be true or false.");
5645
6270
  const matcher = params.q === void 0 || params.q === "" ? () => true : gmailQueryMatcher(params.q);
5646
6271
  if (!matcher) return void 0;
5647
6272
  const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
5648
6273
  if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(GMAIL_THREADS, 400, "maxResults must be an integer from 1 to 500.");
5649
- const labels = params.labelIds === void 0 ? [] : Array.isArray(params.labelIds) ? params.labelIds.map(String) : [String(params.labelIds)];
6274
+ const labels = gmailLabelFilter(params), spamTrash = params.includeSpamTrash === true || params.includeSpamTrash === "true";
5650
6275
  const latest = /* @__PURE__ */ new Map();
5651
- for (const message of rowsIn(data, MESSAGES)) {
6276
+ for (const message of rowsIn(data, MESSAGES2)) {
5652
6277
  const ids = Array.isArray(message.labelIds) ? message.labelIds : [];
5653
- if (ids.includes("SPAM") || ids.includes("TRASH") || !labels.every((l) => ids.includes(l)) || !matcher(message)) continue;
6278
+ if (!spamTrash && (ids.includes("SPAM") || ids.includes("TRASH")) || !labels.every((l) => ids.includes(l)) || !matcher(message)) continue;
5654
6279
  const thread = String(message.threadId ?? message.id);
5655
6280
  if (!latest.has(thread) || gmailDate(message) > gmailDate(latest.get(thread))) latest.set(thread, message);
5656
6281
  }
5657
- const threads = [...latest.entries()].sort((a, b) => gmailDate(b[1]) - gmailDate(a[1])).slice(0, max).map(([id]) => {
6282
+ const ordered = [...latest.entries()].sort((a, b) => gmailDate(b[1]) - gmailDate(a[1]));
6283
+ const offset = gmailPageOffset(params.pageToken, ordered.length);
6284
+ if (offset === void 0) return void 0;
6285
+ const threads = ordered.slice(offset, offset + max).map(([id]) => {
5658
6286
  const messages = gmailThreadMessages(data, id);
5659
6287
  return { id, snippet: messages.at(-1)?.snippet ?? "", historyId: gmailHistoryId(messages) };
5660
6288
  });
5661
- return ok(GMAIL_THREADS, threads.length ? { threads, resultSizeEstimate: threads.length } : { resultSizeEstimate: 0 });
6289
+ const nextPageToken = offset + max < ordered.length ? String(offset + max) : void 0;
6290
+ return ok(GMAIL_THREADS, { ...threads.length ? { threads } : {}, resultSizeEstimate: ordered.length, ...nextPageToken ? { nextPageToken } : {} });
6291
+ }
6292
+ const trashMatch = /^\/gmail\/v1\/users\/me\/(messages|threads)\/([^/]+)\/(trash|untrash)$/.exec(path);
6293
+ if (trashMatch) {
6294
+ if (method !== "POST" || Object.keys(params).length) return void 0;
6295
+ const [, kind, rawId, action] = trashMatch, id = decodeURIComponent(rawId);
6296
+ const targets = kind === "messages" ? rowsIn(data, MESSAGES2).filter((m) => m.id === id) : rowsIn(data, MESSAGES2).filter((m) => m.threadId === id);
6297
+ if (!targets.length) return googleError(kind === "messages" ? MESSAGES2 : GMAIL_THREADS, 404, "Requested entity was not found.");
6298
+ const next = gmailNextHistoryId(data);
6299
+ for (const message of targets) {
6300
+ const labels = new Set(message.labelIds ?? []);
6301
+ if (action === "trash") {
6302
+ labels.delete("INBOX");
6303
+ labels.add("TRASH");
6304
+ } else {
6305
+ labels.delete("TRASH");
6306
+ labels.add("INBOX");
6307
+ }
6308
+ message.labelIds = [...labels];
6309
+ message.historyId = next;
6310
+ }
6311
+ const body = kind === "messages" ? structuredClone(targets[0]) : { id, historyId: next, messages: targets.map((m) => structuredClone(m)) };
6312
+ return { status: 200, body, collection: kind === "messages" ? MESSAGES2 : GMAIL_THREADS, operation: "write", record: { id, action } };
5662
6313
  }
5663
6314
  const threadMatch = /^\/gmail\/v1\/users\/me\/threads\/([^/]+)$/.exec(path);
5664
6315
  if (threadMatch) {
@@ -5668,23 +6319,55 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5668
6319
  return ok(GMAIL_THREADS, { id: decodeURIComponent(threadMatch[1]), historyId: gmailHistoryId(messages), messages: structuredClone(messages) });
5669
6320
  }
5670
6321
  if (path === "/gmail/v1/users/me/history") {
5671
- if (method !== "GET" || Object.keys(params).some((k) => !["startHistoryId", "historyTypes", "maxResults"].includes(k))) return void 0;
6322
+ if (method !== "GET" || Object.keys(params).some((k) => !["startHistoryId", "historyTypes", "maxResults", "pageToken"].includes(k))) return void 0;
5672
6323
  if (params.historyTypes !== void 0 && !["messageAdded", "labelAdded", "labelRemoved"].includes(String(params.historyTypes))) return void 0;
5673
- if (typeof params.startHistoryId !== "string" || !/^\d{1,20}$/.test(params.startHistoryId)) return googleError(MESSAGES, 400, "startHistoryId is required.");
6324
+ if (typeof params.startHistoryId !== "string" || !/^\d{1,20}$/.test(params.startHistoryId)) return googleError(MESSAGES2, 400, "startHistoryId is required.");
5674
6325
  const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
5675
- if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(MESSAGES, 400, "maxResults must be an integer from 1 to 500.");
6326
+ if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(MESSAGES2, 400, "maxResults must be an integer from 1 to 500.");
5676
6327
  const start = BigInt(params.startHistoryId);
5677
- const all = rowsIn(data, MESSAGES);
6328
+ const all = rowsIn(data, MESSAGES2);
5678
6329
  const added = all.filter((m) => BigInt(String(m.historyId ?? 0)) > start).sort((a, b) => BigInt(String(a.historyId)) < BigInt(String(b.historyId)) ? -1 : 1);
5679
- if (added.length > max) return void 0;
5680
- 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 ?? []) } }] }));
6330
+ const offset = params.pageToken === void 0 ? 0 : typeof params.pageToken === "string" && /^\d{1,9}$/.test(params.pageToken) ? Number(params.pageToken) : NaN;
6331
+ if (!Number.isInteger(offset) || offset < 0 || offset > added.length) return void 0;
6332
+ const page = added.slice(offset, offset + max);
6333
+ 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 ?? []) } }] }));
5681
6334
  const latest = gmailHistoryId(all);
5682
- return ok(MESSAGES, { ...history.length ? { history } : {}, historyId: BigInt(latest) > start ? latest : params.startHistoryId });
6335
+ const nextPageToken = offset + max < added.length ? String(offset + max) : void 0;
6336
+ return ok(MESSAGES2, { ...history.length ? { history } : {}, historyId: BigInt(latest) > start ? latest : params.startHistoryId, ...nextPageToken ? { nextPageToken } : {} });
5683
6337
  }
5684
6338
  if (path === GMAIL_SEND_AS) {
5685
6339
  if (method !== "GET" || Object.keys(params).length) return void 0;
5686
6340
  return ok(GMAIL_SEND_AS, { sendAs: rowsIn(data, GMAIL_SEND_AS).map((row) => structuredClone(row)) });
5687
6341
  }
6342
+ if (path === "/gmail/v1/users/me/settings/forwardingAddresses") {
6343
+ if (method !== "GET" || Object.keys(params).length) return void 0;
6344
+ return ok("/gmail/v1/users/me/settings/forwardingAddresses", { forwardingAddresses: rowsIn(data, "/gmail/v1/users/me/settings/forwardingAddresses").map((row) => structuredClone(row)) });
6345
+ }
6346
+ if (path === "/gmail/v1/users/me/settings/filters") {
6347
+ if (method === "GET") {
6348
+ if (Object.keys(params).length) return void 0;
6349
+ return ok("/gmail/v1/users/me/settings/filters", { filter: rowsIn(data, "/gmail/v1/users/me/settings/filters").map((row) => structuredClone(row)) });
6350
+ }
6351
+ if (method !== "POST") return void 0;
6352
+ if (Object.keys(params).some((k) => !["criteria", "action"].includes(k))) return void 0;
6353
+ const criteria = params.criteria, action = params.action;
6354
+ if (!isObject4(criteria) || !isObject4(action)) return googleError("/gmail/v1/users/me/settings/filters", 400, "criteria and action must be objects.");
6355
+ if (Object.keys(criteria).some((k) => !["from", "to", "subject", "query", "negatedQuery", "hasAttachment", "excludeChats", "size", "sizeComparison"].includes(k))) return void 0;
6356
+ if (Object.keys(action).some((k) => !["addLabelIds", "removeLabelIds", "forward"].includes(k))) return void 0;
6357
+ const filters = rowsIn(data, "/gmail/v1/users/me/settings/filters");
6358
+ const filter = { id: `Filter_${filters.length + 1}`, criteria: structuredClone(criteria), action: structuredClone(action) };
6359
+ filters.push(filter);
6360
+ return { status: 200, body: structuredClone(filter), collection: "/gmail/v1/users/me/settings/filters", operation: "write", record: filter };
6361
+ }
6362
+ const filterMatch = /^\/gmail\/v1\/users\/me\/settings\/filters\/([^/]+)$/.exec(path);
6363
+ if (filterMatch) {
6364
+ if (method !== "DELETE" || Object.keys(params).length) return void 0;
6365
+ const filters = rowsIn(data, "/gmail/v1/users/me/settings/filters");
6366
+ const index = filters.findIndex((f) => f.id === decodeURIComponent(filterMatch[1]));
6367
+ if (index < 0) return googleError("/gmail/v1/users/me/settings/filters", 404, "Requested entity was not found.");
6368
+ const [removed] = filters.splice(index, 1);
6369
+ return { status: 204, body: null, collection: "/gmail/v1/users/me/settings/filters", operation: "write", record: { id: removed.id, deleted: true } };
6370
+ }
5688
6371
  if (path === GMAIL_WATCH) {
5689
6372
  if (method !== "POST" || Object.keys(params).some((k) => !["topicName", "labelIds", "labelFilterBehavior", "labelFilterAction"].includes(k))) return void 0;
5690
6373
  if (typeof params.topicName !== "string" || !/^projects\/[^/]+\/topics\/[^/]+$/.test(params.topicName)) return googleError(GMAIL_WATCH, 400, "Invalid topicName: expected projects/<project>/topics/<topic>.");
@@ -5711,7 +6394,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5711
6394
  if (typeof params.id !== "string" || !params.id) return sendFail(400, "Draft id is required.");
5712
6395
  const drafts = rowsIn(data, GMAIL_DRAFTS), index = drafts.findIndex((d) => d.id === params.id);
5713
6396
  if (index < 0) return sendFail(404, "Requested entity was not found.");
5714
- const messages = rowsIn(data, MESSAGES), draft = drafts[index];
6397
+ const messages = rowsIn(data, MESSAGES2), draft = drafts[index];
5715
6398
  const message = messages.find((m) => m.id === draft.message.id);
5716
6399
  if (!message) return sendFail(404, "Requested entity was not found.");
5717
6400
  let update;
@@ -5731,7 +6414,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5731
6414
  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.");
5732
6415
  drafts.splice(index, 1);
5733
6416
  Object.assign(message, update ? { payload: update.payload, snippet: update.snippet, sizeEstimate: update.bytes } : {}, { labelIds: ["SENT"], internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) });
5734
- return withPush(write2(200, MESSAGES, { id: message.id, threadId: message.threadId, labelIds: ["SENT"] }, { ...structuredClone(message), sentFromDraft: draft.id }), gmailPublish(data, ["SENT"], sequence));
6417
+ return withPush(write2(200, MESSAGES2, { id: message.id, threadId: message.threadId, labelIds: ["SENT"] }, { ...structuredClone(message), sentFromDraft: draft.id }), gmailPublish(data, ["SENT"], sequence));
5735
6418
  }
5736
6419
  const draftMatch = /^\/gmail\/v1\/users\/me\/drafts\/([^/]+)$/.exec(path);
5737
6420
  if (draftMatch) {
@@ -5740,7 +6423,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5740
6423
  if (method === "GET") {
5741
6424
  if (Object.keys(params).some((k) => k !== "format") || params.format !== void 0 && params.format !== "full") return void 0;
5742
6425
  if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
5743
- const draft = drafts[index], message = rowsIn(data, MESSAGES).find((m) => m.id === draft.message.id);
6426
+ const draft = drafts[index], message = rowsIn(data, MESSAGES2).find((m) => m.id === draft.message.id);
5744
6427
  return ok(GMAIL_DRAFTS, { id, message: structuredClone(message ?? draft.message) });
5745
6428
  }
5746
6429
  if (method === "PUT") {
@@ -5757,7 +6440,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5757
6440
  if (Object.keys(params).length) return void 0;
5758
6441
  if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
5759
6442
  const [removed] = drafts.splice(index, 1);
5760
- const messages = rowsIn(data, MESSAGES), messageIndex = messages.findIndex((m) => m.id === removed.message.id);
6443
+ const messages = rowsIn(data, MESSAGES2), messageIndex = messages.findIndex((m) => m.id === removed.message.id);
5761
6444
  if (messageIndex >= 0) messages.splice(messageIndex, 1);
5762
6445
  return { status: 204, body: null, collection: GMAIL_DRAFTS, record: { id, deleted: true, threadId: removed.threadId ?? null }, operation: "write" };
5763
6446
  }
@@ -5781,7 +6464,7 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5781
6464
  if (Object.keys(fields).some((k) => !["raw", "threadId"].includes(k))) return void 0;
5782
6465
  return gmailDraftWrite(data, fields.raw, fields.threadId, sequence);
5783
6466
  }
5784
- if (path === `${MESSAGES}/send`) {
6467
+ if (path === `${MESSAGES2}/send`) {
5785
6468
  if (method !== "POST") return void 0;
5786
6469
  if (Object.keys(params).some((k) => !["raw", "to", "subject", "text", "threadId"].includes(k))) return void 0;
5787
6470
  const text2 = str(params.text), raw2 = str(params.raw);
@@ -5797,17 +6480,17 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5797
6480
  const legacy = plain2 && !("error" in plain2) ? plain2 : void 0;
5798
6481
  const mime = raw2 && !legacy ? parseGmailDraftRaw(raw2) : void 0;
5799
6482
  if (mime && "error" in mime) {
5800
- return mime.unsupported ? { status: 501, body: restUnsupportedBody("gmail"), collection: MESSAGES, unsupportedReason: mime.error } : fail(400, mime.error);
6483
+ return mime.unsupported ? { status: 501, body: restUnsupportedBody("gmail"), collection: MESSAGES2, unsupportedReason: mime.error } : fail(400, mime.error);
5801
6484
  }
5802
- if (mime && !headerAddresses(mime.headers.find((header3) => header3.name.toLowerCase() === "to")?.value).length) {
6485
+ if (mime && !headerAddresses(mime.headers.find((header4) => header4.name.toLowerCase() === "to")?.value).length) {
5803
6486
  return fail(400, "Invalid To header: a sent message needs at least one recipient.");
5804
6487
  }
5805
6488
  const body = legacy?.text ?? mime?.snippet ?? text2 ?? "";
5806
6489
  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) };
5807
- rowsIn(data, MESSAGES).push(message);
5808
- return withPush(write2(200, MESSAGES, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
6490
+ rowsIn(data, MESSAGES2).push(message);
6491
+ return withPush(write2(200, MESSAGES2, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
5809
6492
  }
5810
- if (path === MESSAGES && method === "POST") {
6493
+ if (path === MESSAGES2 && method === "POST") {
5811
6494
  if (Object.keys(params).some((k) => !["raw", "labelIds", "threadId", "internalDateSource"].includes(k))) return void 0;
5812
6495
  if (typeof params.raw !== "string" || !params.raw) return fail(400, "raw must be a base64url MIME string.");
5813
6496
  if (params.threadId !== void 0 && (typeof params.threadId !== "string" || !gmailThreadMessages(data, params.threadId).length)) return fail(404, "Requested entity was not found.");
@@ -5826,25 +6509,47 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5826
6509
  }
5827
6510
  const id = `gmail_insert_at_${sequence}`;
5828
6511
  const message = { id, threadId: params.threadId ?? id, labelIds, snippet: mime.snippet, payload: mime.payload, sizeEstimate: mime.bytes, internalDate: String(internalDate), historyId: String(17e8 + sequence) };
5829
- rowsIn(data, MESSAGES).push(message);
5830
- return withPush(write2(200, MESSAGES, { id, threadId: message.threadId, labelIds }, message), gmailPublish(data, labelIds, sequence));
6512
+ rowsIn(data, MESSAGES2).push(message);
6513
+ return withPush(write2(200, MESSAGES2, { id, threadId: message.threadId, labelIds }, message), gmailPublish(data, labelIds, sequence));
5831
6514
  }
5832
- if (path === MESSAGES) {
6515
+ if (path === MESSAGES2) {
5833
6516
  if (method !== "GET") return void 0;
5834
- if (Object.keys(params).some((k) => k !== "q")) return void 0;
5835
- let filtered = rowsIn(data, MESSAGES);
5836
- if (params.q !== void 0) {
5837
- if (typeof params.q !== "string") return fail(400, "q must be a string.");
5838
- filtered = filtered.filter((m) => typeof m.snippet === "string" && m.snippet.includes(params.q));
5839
- }
5840
- return ok(MESSAGES, { messages: filtered.map((m) => ({ id: m.id, threadId: m.threadId })), resultSizeEstimate: filtered.length });
6517
+ if (Object.keys(params).some((k) => !["q", "maxResults", "pageToken", "labelIds", "includeSpamTrash"].includes(k))) return void 0;
6518
+ if (params.q !== void 0 && typeof params.q !== "string") return fail(400, "q must be a string.");
6519
+ if (params.includeSpamTrash !== void 0 && !["true", "false", true, false].includes(params.includeSpamTrash)) return fail(400, "includeSpamTrash must be true or false.");
6520
+ const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
6521
+ if (!Number.isInteger(max) || max < 1 || max > 500) return fail(400, "maxResults must be an integer from 1 to 500.");
6522
+ const matcher = params.q === void 0 || params.q === "" ? () => true : gmailQueryMatcher(params.q);
6523
+ if (!matcher) return void 0;
6524
+ const labels = gmailLabelFilter(params), spamTrash = params.includeSpamTrash === true || params.includeSpamTrash === "true";
6525
+ const filtered = rowsIn(data, MESSAGES2).filter((message) => {
6526
+ const ids = Array.isArray(message.labelIds) ? message.labelIds : [];
6527
+ if (!spamTrash && (ids.includes("SPAM") || ids.includes("TRASH"))) return false;
6528
+ return labels.every((label2) => ids.includes(label2)) && matcher(message);
6529
+ });
6530
+ const offset = gmailPageOffset(params.pageToken, filtered.length);
6531
+ if (offset === void 0) return void 0;
6532
+ const page = filtered.slice(offset, offset + max);
6533
+ const nextPageToken = offset + max < filtered.length ? String(offset + max) : void 0;
6534
+ return ok(MESSAGES2, { messages: page.map((m) => ({ id: m.id, threadId: m.threadId })), resultSizeEstimate: filtered.length, ...nextPageToken ? { nextPageToken } : {} });
6535
+ }
6536
+ const attachmentMatch = /^\/gmail\/v1\/users\/me\/messages\/([^/]+)\/attachments\/([^/]+)$/.exec(path);
6537
+ if (attachmentMatch) {
6538
+ if (method !== "GET" || Object.keys(params).length) return void 0;
6539
+ const message = rowsIn(data, MESSAGES2).find((m) => m.id === decodeURIComponent(attachmentMatch[1]));
6540
+ const attachmentId = decodeURIComponent(attachmentMatch[2]);
6541
+ if (!message) return fail(404, "Requested entity was not found.");
6542
+ const collect = (part) => part.body?.attachmentId === attachmentId ? part : (part.parts ?? []).map((child) => collect(child)).find(Boolean);
6543
+ const found = collect(message.payload ?? {});
6544
+ if (!found?.body) return fail(404, `Attachment not found: ${attachmentId}`);
6545
+ return ok(MESSAGES2, { attachmentId, size: found.body.size ?? 0, data: found.body.data ?? "" });
5841
6546
  }
5842
6547
  const messageMatch = /^\/gmail\/v1\/users\/me\/messages\/([^/]+)$/.exec(path);
5843
6548
  if (messageMatch) {
5844
6549
  if (method !== "GET") return void 0;
5845
- const message = rowsIn(data, MESSAGES).find((m) => m.id === messageMatch[1]);
6550
+ const message = rowsIn(data, MESSAGES2).find((m) => m.id === messageMatch[1]);
5846
6551
  if (!message) return fail(404, `Message not found: ${messageMatch[1]}`);
5847
- return ok(MESSAGES, structuredClone(message));
6552
+ return ok(MESSAGES2, structuredClone(message));
5848
6553
  }
5849
6554
  const modifyMatch = /^\/gmail\/v1\/users\/me\/(messages|threads)\/([^/]+)\/modify$/.exec(path);
5850
6555
  if (modifyMatch) {
@@ -5855,9 +6560,9 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5855
6560
  const known2 = gmailLabelKnown(data), unknown = [...add, ...remove2].find((id2) => !known2(id2));
5856
6561
  if (unknown) return fail(400, `Invalid label: ${unknown}`);
5857
6562
  const id = decodeURIComponent(modifyMatch[2]);
5858
- const targets = modifyMatch[1] === "messages" ? rowsIn(data, MESSAGES).filter((m) => m.id === id) : rowsIn(data, MESSAGES).filter((m) => m.threadId === id);
6563
+ const targets = modifyMatch[1] === "messages" ? rowsIn(data, MESSAGES2).filter((m) => m.id === id) : rowsIn(data, MESSAGES2).filter((m) => m.threadId === id);
5859
6564
  if (!targets.length) return fail(404, `Requested entity was not found.`);
5860
- const next = String(BigInt(gmailHistoryId(rowsIn(data, MESSAGES))) + 1n);
6565
+ const next = String(BigInt(gmailHistoryId(rowsIn(data, MESSAGES2))) + 1n);
5861
6566
  for (const message of targets) {
5862
6567
  const labels = new Set(message.labelIds ?? []);
5863
6568
  for (const l of add) labels.add(l);
@@ -5866,7 +6571,46 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5866
6571
  message.historyId = next;
5867
6572
  }
5868
6573
  const body = modifyMatch[1] === "messages" ? structuredClone(targets[0]) : { id, historyId: next, messages: targets.map((m) => structuredClone(m)) };
5869
- return { status: 200, body, collection: MESSAGES, operation: "write", record: { id, addLabelIds: add, removeLabelIds: remove2 } };
6574
+ return { status: 200, body, collection: MESSAGES2, operation: "write", record: { id, addLabelIds: add, removeLabelIds: remove2 } };
6575
+ }
6576
+ const labelMatch = /^\/gmail\/v1\/users\/me\/labels\/([^/]+)$/.exec(path);
6577
+ if (labelMatch) {
6578
+ const id = decodeURIComponent(labelMatch[1]), labels = rowsIn(data, LABELS);
6579
+ const index = labels.findIndex((l) => l.id === id);
6580
+ const system = GMAIL_SYSTEM_LABEL_NAMES.has(String(id).toUpperCase()) || id.startsWith("CATEGORY_");
6581
+ if (method === "GET") {
6582
+ if (Object.keys(params).length) return void 0;
6583
+ if (index < 0) return googleError(LABELS, 404, "Requested entity was not found.");
6584
+ return ok(LABELS, structuredClone(labels[index]));
6585
+ }
6586
+ if (method === "PATCH" || method === "PUT") {
6587
+ if (Object.keys(params).some((k) => !["name", "labelListVisibility", "messageListVisibility", "color"].includes(k))) return void 0;
6588
+ if (index < 0) {
6589
+ if (system) return googleError(LABELS, 400, "Invalid label: system labels cannot be modified.");
6590
+ return googleError(LABELS, 404, "Requested entity was not found.");
6591
+ }
6592
+ if (system) return googleError(LABELS, 400, "Invalid label: system labels cannot be modified.");
6593
+ if (params.name !== void 0) {
6594
+ if (typeof params.name !== "string" || !params.name.trim()) return googleError(LABELS, 400, "Invalid label name");
6595
+ if (labels.some((l, i) => i !== index && String(l.name).toLowerCase() === String(params.name).toLowerCase())) return googleError(LABELS, 409, "Label name exists or conflicts");
6596
+ }
6597
+ if (params.color !== void 0 && (!isObject4(params.color) || Object.keys(params.color).some((k) => !["backgroundColor", "textColor"].includes(k)))) return googleError(LABELS, 400, "Invalid color.");
6598
+ 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)) };
6599
+ labels.splice(index, 1, updated);
6600
+ return { status: 200, body: structuredClone(updated), collection: LABELS, operation: "write", record: updated };
6601
+ }
6602
+ if (method === "DELETE") {
6603
+ if (Object.keys(params).length) return void 0;
6604
+ if (system) return googleError(LABELS, 400, "Invalid label: system labels cannot be deleted.");
6605
+ if (index < 0) return googleError(LABELS, 404, "Requested entity was not found.");
6606
+ const [removed] = labels.splice(index, 1);
6607
+ for (const message of rowsIn(data, MESSAGES2)) {
6608
+ const ids = message.labelIds;
6609
+ if (Array.isArray(ids) && ids.includes(id)) message.labelIds = ids.filter((l) => l !== id);
6610
+ }
6611
+ return { status: 204, body: null, collection: LABELS, operation: "write", record: { id, deleted: true, name: removed.name } };
6612
+ }
6613
+ return void 0;
5870
6614
  }
5871
6615
  if (path === LABELS) {
5872
6616
  if (method === "POST") {
@@ -5885,8 +6629,8 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
5885
6629
  return void 0;
5886
6630
  }
5887
6631
  function googleCalendarOperation(method, path, params, _headers, data, sequence) {
5888
- const CALENDAR_LIST = "/calendar/v3/users/me/calendarList", EVENTS = "/calendar/v3/calendars/primary/events";
5889
- const fail = (status, message) => googleError(EVENTS, status, message);
6632
+ const CALENDAR_LIST = "/calendar/v3/users/me/calendarList", EVENTS3 = "/calendar/v3/calendars/primary/events";
6633
+ const fail = (status, message) => googleError(EVENTS3, status, message);
5890
6634
  if (path === CALENDAR_LIST) {
5891
6635
  if (method !== "GET") return void 0;
5892
6636
  if (Object.keys(params).length) return void 0;
@@ -5895,9 +6639,9 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5895
6639
  const match = /^\/calendar\/v3\/calendars\/([^/]+)\/events(?:\/([^/]+))?$/.exec(path);
5896
6640
  if (!match) return void 0;
5897
6641
  const [, calendar, eventId] = match;
5898
- if (calendar !== "primary") return googleError(EVENTS, 404, `Not Found: no twin state for calendar ${calendar}`);
6642
+ if (calendar !== "primary") return googleError(EVENTS3, 404, `Not Found: no twin state for calendar ${calendar}`);
5899
6643
  const scalar2 = (value) => ["summary", "description", "location"].filter((k) => params[k] !== void 0 && str(params[k]) === void 0);
5900
- const meetingField = (value) => value !== void 0 && !Array.isArray(value) && !isObject2(value);
6644
+ const meetingField = (value) => value !== void 0 && !Array.isArray(value) && !isObject4(value);
5901
6645
  if (!eventId) {
5902
6646
  if (method === "GET") {
5903
6647
  const allowed = ["timeMin", "timeMax", "maxResults", "pageToken", "singleEvents", "orderBy", "conferenceDataVersion"];
@@ -5915,10 +6659,10 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5915
6659
  if (Number.isNaN(lower) || Number.isNaN(upper) || lower >= upper) return fail(400, "Invalid time range.");
5916
6660
  const limit = params.maxResults === void 0 ? 250 : boundedInt(params.maxResults, 1, 2500);
5917
6661
  if (limit === null) return fail(400, "Invalid maxResults.");
5918
- let events = rowsIn(data, EVENTS).filter((row) => row.status !== "cancelled");
6662
+ let events = rowsIn(data, EVENTS3).filter((row) => row.status !== "cancelled");
5919
6663
  if (events.some((row) => row.recurrence || row.recurringEventId || row.conferenceData)) return void 0;
5920
6664
  const timed = params.timeMin !== void 0 || params.timeMax !== void 0 || params.orderBy !== void 0;
5921
- 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;
6665
+ 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;
5922
6666
  if (timed) events = events.filter((row) => timestamp(row.end.dateTime) > lower && timestamp(row.start.dateTime) < upper);
5923
6667
  if (params.orderBy === "startTime") events = [...events].sort((a, b) => timestamp(a.start.dateTime) - timestamp(b.start.dateTime));
5924
6668
  const query = Object.fromEntries(Object.entries(params).filter(([key2]) => key2 !== "pageToken").sort(([a], [b]) => a.localeCompare(b)));
@@ -5931,7 +6675,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5931
6675
  offset = Number(token[2]);
5932
6676
  }
5933
6677
  const next = offset + (limit ?? 250);
5934
- return ok(EVENTS, { items: structuredClone(events.slice(offset, next)), ...next < events.length ? { nextPageToken: `at_${fingerprint}_${next}` } : {} });
6678
+ return ok(EVENTS3, { items: structuredClone(events.slice(offset, next)), ...next < events.length ? { nextPageToken: `at_${fingerprint}_${next}` } : {} });
5935
6679
  }
5936
6680
  if (method !== "POST") return void 0;
5937
6681
  if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
@@ -5939,13 +6683,13 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5939
6683
  if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
5940
6684
  const scalarBad = scalar2(params);
5941
6685
  if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
5942
- 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() };
5943
- rowsIn(data, EVENTS).push(event2);
5944
- return write2(200, EVENTS, structuredClone(event2), event2);
6686
+ 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() };
6687
+ rowsIn(data, EVENTS3).push(event2);
6688
+ return write2(200, EVENTS3, structuredClone(event2), event2);
5945
6689
  }
5946
- const event = rowsIn(data, EVENTS).find((e) => e.id === eventId);
6690
+ const event = rowsIn(data, EVENTS3).find((e) => e.id === eventId);
5947
6691
  if (!event) return fail(404, `Not Found: event ${eventId}`);
5948
- if (method === "GET") return ok(EVENTS, structuredClone(event));
6692
+ if (method === "GET") return ok(EVENTS3, structuredClone(event));
5949
6693
  if (method === "PATCH") {
5950
6694
  if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
5951
6695
  if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
@@ -5953,23 +6697,23 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
5953
6697
  if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
5954
6698
  for (const [k, v] of Object.entries(params)) if (["summary", "description", "location", "start", "end", "attendees", "status"].includes(k)) event[k] = structuredClone(v);
5955
6699
  event.updated = iso2();
5956
- return write2(200, EVENTS, structuredClone(event), event);
6700
+ return write2(200, EVENTS3, structuredClone(event), event);
5957
6701
  }
5958
6702
  if (method === "DELETE") {
5959
- rowsIn(data, EVENTS).splice(rowsIn(data, EVENTS).findIndex((e) => e.id === eventId), 1);
5960
- return write2(200, EVENTS, {}, structuredClone(event));
6703
+ rowsIn(data, EVENTS3).splice(rowsIn(data, EVENTS3).findIndex((e) => e.id === eventId), 1);
6704
+ return write2(200, EVENTS3, {}, structuredClone(event));
5961
6705
  }
5962
6706
  return void 0;
5963
6707
  }
5964
6708
  function gitlabOperation(method, path, params, _headers, data, sequence) {
5965
6709
  const match = /^\/api\/v4\/(projects|issues|merge_requests)(?:\/(\d+))?(?:\/(notes)(?:\/(\d+))?)?$/.exec(path);
5966
6710
  if (!match) return void 0;
5967
- const [, resource, id, sub] = match;
5968
- const collection = sub === "notes" ? "/api/v4/merge_requests/notes" : `/api/v4/${resource}`;
6711
+ const [, resource2, id, sub] = match;
6712
+ const collection = sub === "notes" ? "/api/v4/merge_requests/notes" : `/api/v4/${resource2}`;
5969
6713
  const records = rowsIn(data, collection);
5970
6714
  const author = { id: 42, username: "agenttwin-test", name: "AgentTwin Test" };
5971
6715
  if (sub === "notes") {
5972
- if (!id || !resource) return void 0;
6716
+ if (!id || !resource2) return void 0;
5973
6717
  const mr = rowsIn(data, "/api/v4/merge_requests").find((r) => String(r.iid) === id || String(r.id) === id);
5974
6718
  if (!mr) return notFound(collection, { message: "404 Merge Request Not Found" });
5975
6719
  if (method === "GET") return ok(collection, records.filter((n) => n.noteable_iid === mr.iid).map((row) => structuredClone(row)));
@@ -5985,7 +6729,7 @@ function gitlabOperation(method, path, params, _headers, data, sequence) {
5985
6729
  return ok(collection, records.map((row) => structuredClone(row)));
5986
6730
  }
5987
6731
  if (method === "POST" && !id) {
5988
- if (resource === "projects") {
6732
+ if (resource2 === "projects") {
5989
6733
  if (Object.keys(params).some((k) => !["name", "description", "visibility"].includes(k))) return void 0;
5990
6734
  if (typeof params.name !== "string" || !params.name) return badRequest(collection, { message: "name is missing" });
5991
6735
  if (params.description !== void 0 && str(params.description) === void 0) return void 0;
@@ -5993,7 +6737,7 @@ function gitlabOperation(method, path, params, _headers, data, sequence) {
5993
6737
  records.push(project);
5994
6738
  return created(collection, structuredClone(project), project);
5995
6739
  }
5996
- if (resource === "issues") {
6740
+ if (resource2 === "issues") {
5997
6741
  if (Object.keys(params).some((k) => !["title", "description", "project_id", "labels", "assignee_ids"].includes(k))) return void 0;
5998
6742
  const projectId2 = Number(params.project_id);
5999
6743
  if (typeof params.title !== "string" || !params.title || !Number.isInteger(projectId2)) return badRequest(collection, { message: "title and project_id are required" });
@@ -6013,8 +6757,8 @@ function gitlabOperation(method, path, params, _headers, data, sequence) {
6013
6757
  records.push(mergeRequest);
6014
6758
  return created(collection, structuredClone(mergeRequest), mergeRequest);
6015
6759
  }
6016
- const primary = id ? rowsIn(data, `/api/v4/${resource}`).find((r) => String(r.id) === id || String(r.iid) === id) : void 0;
6017
- if (!primary) return id ? notFound(collection, { message: `404 ${resource === "merge_requests" ? "Merge Request" : resource.slice(0, -1)} Not Found` }) : void 0;
6760
+ const primary = id ? rowsIn(data, `/api/v4/${resource2}`).find((r) => String(r.id) === id || String(r.iid) === id) : void 0;
6761
+ if (!primary) return id ? notFound(collection, { message: `404 ${resource2 === "merge_requests" ? "Merge Request" : resource2.slice(0, -1)} Not Found` }) : void 0;
6018
6762
  if (method === "GET") return ok(collection, structuredClone(primary));
6019
6763
  return void 0;
6020
6764
  }
@@ -6037,11 +6781,11 @@ function jiraOperation(method, path, params, _headers, data, sequence) {
6037
6781
  }
6038
6782
  if (path === ISSUE) {
6039
6783
  if (method !== "POST") return void 0;
6040
- if (Object.keys(params).some((k) => k !== "fields") || !isObject2(params.fields)) return jiraFail(ISSUE, [], { fields: "fields is required" });
6784
+ if (Object.keys(params).some((k) => k !== "fields") || !isObject4(params.fields)) return jiraFail(ISSUE, [], { fields: "fields is required" });
6041
6785
  const fields = params.fields;
6042
6786
  if (Object.keys(fields).some((k) => !["project", "issuetype", "summary", "description", "priority", "labels", "assignee"].includes(k))) return void 0;
6043
- const projectKey = isObject2(fields.project) ? str(fields.project.key) : void 0;
6044
- const issuetype = isObject2(fields.issuetype) ? str(fields.issuetype.name) : void 0;
6787
+ const projectKey = isObject4(fields.project) ? str(fields.project.key) : void 0;
6788
+ const issuetype = isObject4(fields.issuetype) ? str(fields.issuetype.name) : void 0;
6045
6789
  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.` });
6046
6790
  if (!rowsIn(data, PROJECT).some((p) => p.key === projectKey)) return jiraFail(ISSUE, [`Project '${projectKey}' does not exist.`], {});
6047
6791
  const issueRows = rowsIn(data, ISSUE);
@@ -6057,15 +6801,15 @@ function jiraOperation(method, path, params, _headers, data, sequence) {
6057
6801
  if (method === "GET" && !issueMatch[2]) return ok(ISSUE, structuredClone(issue));
6058
6802
  if (method === "POST" && issueMatch[2] === "comment") {
6059
6803
  if (Object.keys(params).some((k) => k !== "body")) return void 0;
6060
- if (typeof params.body !== "string" && !isObject2(params.body)) return jiraFail(ISSUE, [], { body: "body is required" });
6061
- 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." });
6804
+ if (typeof params.body !== "string" && !isObject4(params.body)) return jiraFail(ISSUE, [], { body: "body is required" });
6805
+ 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." });
6062
6806
  const commentRows = rowsIn(data, "/rest/api/3/issue/comments");
6063
6807
  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) };
6064
6808
  commentRows.push(comment);
6065
6809
  return created("/rest/api/3/issue/comments", structuredClone(comment), comment);
6066
6810
  }
6067
6811
  if (method === "POST" && issueMatch[2] === "transitions") {
6068
- if (Object.keys(params).some((k) => !["transition", "fields"].includes(k)) || !isObject2(params.transition) || Object.keys(params.transition).some((k) => k !== "id")) return void 0;
6812
+ if (Object.keys(params).some((k) => !["transition", "fields"].includes(k)) || !isObject4(params.transition) || Object.keys(params.transition).some((k) => k !== "id")) return void 0;
6069
6813
  const transitionId = str(params.transition.id);
6070
6814
  if (!transitionId) return void 0;
6071
6815
  if (!JIRA_TRANSITIONS[transitionId]) return jiraFail(ISSUE, [], { transition: "Transition id must be one of 11, 21, 31" });
@@ -6089,12 +6833,12 @@ function jiraOperation(method, path, params, _headers, data, sequence) {
6089
6833
  return void 0;
6090
6834
  }
6091
6835
  function discordOperation(method, path, params, _headers, data, sequence) {
6092
- const CHANNELS = "/api/channels", MESSAGES = "/api/channels/messages", GUILDS = "/api/guilds", MEMBERS = "/api/guilds/members";
6836
+ const CHANNELS = "/api/channels", MESSAGES2 = "/api/channels/messages", GUILDS = "/api/guilds", MEMBERS = "/api/guilds/members";
6093
6837
  const channelMatch = /^\/api\/channels\/([^/]+)(?:\/(messages)(?:\/([^/]+))?)?$/.exec(path);
6094
6838
  if (channelMatch) {
6095
6839
  const [, channelId, messages, messageId] = channelMatch;
6096
6840
  const channel = rowsIn(data, CHANNELS).find((c) => c.id === channelId);
6097
- if (!channel) return discordError(MESSAGES, 10003, "Unknown Channel");
6841
+ if (!channel) return discordError(MESSAGES2, 10003, "Unknown Channel");
6098
6842
  if (!messages) {
6099
6843
  if (method !== "GET") return void 0;
6100
6844
  return ok(CHANNELS, structuredClone(channel));
@@ -6102,15 +6846,15 @@ function discordOperation(method, path, params, _headers, data, sequence) {
6102
6846
  if (messageId || method !== "GET" && method !== "POST") return void 0;
6103
6847
  if (method === "GET") {
6104
6848
  if (Object.keys(params).length) return void 0;
6105
- return ok(MESSAGES, rowsIn(data, MESSAGES).filter((m) => m.channel_id === channelId).map((row) => structuredClone(row)).reverse());
6849
+ return ok(MESSAGES2, rowsIn(data, MESSAGES2).filter((m) => m.channel_id === channelId).map((row) => structuredClone(row)).reverse());
6106
6850
  }
6107
6851
  if (Object.keys(params).some((k) => !["content", "tts"].includes(k))) return void 0;
6108
- if (typeof params.content !== "string" || !params.content) return discordError(MESSAGES, 50035, "Invalid Form Body: content cannot be empty.");
6852
+ if (typeof params.content !== "string" || !params.content) return discordError(MESSAGES2, 50035, "Invalid Form Body: content cannot be empty.");
6109
6853
  if (params.tts !== void 0 && typeof params.tts !== "boolean") return void 0;
6110
- const records = rowsIn(data, MESSAGES);
6854
+ const records = rowsIn(data, MESSAGES2);
6111
6855
  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 };
6112
6856
  records.push(message);
6113
- return created(MESSAGES, structuredClone(message), message);
6857
+ return created(MESSAGES2, structuredClone(message), message);
6114
6858
  }
6115
6859
  const guildMatch = /^\/api\/guilds\/([^/]+)(?:\/(members))?$/.exec(path);
6116
6860
  if (guildMatch) {
@@ -6132,8 +6876,8 @@ function discordOperation(method, path, params, _headers, data, sequence) {
6132
6876
  function twilioOperation(method, path, params, _headers, data, sequence) {
6133
6877
  const match = /^\/2010-04-01\/Accounts\/([^/]+)\/(Messages|Calls)(?:\.json)?$/.exec(path);
6134
6878
  if (!match) return void 0;
6135
- const [, accountSid, resource] = match;
6136
- const collection = `/2010-04-01/${resource}`;
6879
+ const [, accountSid, resource2] = match;
6880
+ const collection = `/2010-04-01/${resource2}`;
6137
6881
  const records = rowsIn(data, collection);
6138
6882
  const fail = (status, code, message) => ({ status, body: { status, code, message, more_info: "" }, collection });
6139
6883
  const stamp2 = () => {
@@ -6141,13 +6885,13 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
6141
6885
  return `${date} ${time.slice(0, 8)}`;
6142
6886
  };
6143
6887
  if (method === "POST") {
6144
- const allowed = resource === "Messages" ? ["To", "From", "Body"] : ["To", "From", "Url"];
6888
+ const allowed = resource2 === "Messages" ? ["To", "From", "Body"] : ["To", "From", "Url"];
6145
6889
  if (!accountSid || Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
6146
6890
  const missing = allowed.filter((k) => typeof params[k] !== "string" || !params[k]);
6147
6891
  if (missing.length) return fail(400, missing.length === allowed.length ? "21211" : "21606", `No parameter provided for ${allowed.filter((k) => missing.includes(k)).join(", ")}`);
6148
- const prefix = resource === "Messages" ? "SM" : "CA";
6892
+ const prefix = resource2 === "Messages" ? "SM" : "CA";
6149
6893
  const sid = `${prefix}${sha(`${prefix.toLowerCase()}:${sequence}:${accountSid}`).slice(0, 32)}`;
6150
- 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` };
6894
+ 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` };
6151
6895
  records.push(record3);
6152
6896
  return created(collection, structuredClone(record3), record3);
6153
6897
  }
@@ -6162,26 +6906,26 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
6162
6906
  if (typeof params.From !== "string") return fail(400, "20001", "From must be a string");
6163
6907
  filtered = filtered.filter((r) => r.from === params.From);
6164
6908
  }
6165
- 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)) });
6909
+ 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)) });
6166
6910
  }
6167
6911
  return void 0;
6168
6912
  }
6169
6913
  function zendeskOperation(method, path, params, _headers, data, sequence) {
6170
6914
  const match = /^\/api\/v2\/(tickets|users|organizations)(?:\/(\d+))?\.json$/.exec(path);
6171
6915
  if (!match) return void 0;
6172
- const [, resource, id] = match;
6173
- const collection = `/api/v2/${resource}`;
6916
+ const [, resource2, id] = match;
6917
+ const collection = `/api/v2/${resource2}`;
6174
6918
  const records = rowsIn(data, collection);
6175
- const envelope = (items) => ({ [resource]: items, next_page: null, previous_page: null, count: items.length });
6919
+ const envelope = (items) => ({ [resource2]: items, next_page: null, previous_page: null, count: items.length });
6176
6920
  if (method === "POST" && !id) {
6177
- if (resource !== "tickets") return void 0;
6178
- if (Object.keys(params).some((k) => k !== "ticket") || !isObject2(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
6921
+ if (resource2 !== "tickets") return void 0;
6922
+ if (Object.keys(params).some((k) => k !== "ticket") || !isObject4(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
6179
6923
  const ticketParams = params.ticket;
6180
6924
  if (Object.keys(ticketParams).some((k) => !["subject", "comment", "requester", "status", "priority", "tags", "description", "type"].includes(k))) return void 0;
6181
6925
  if (typeof ticketParams.subject !== "string" || !ticketParams.subject) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: Subject can't be blank" });
6182
- 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" });
6926
+ 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" });
6183
6927
  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" });
6184
- 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() };
6928
+ 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() };
6185
6929
  records.push(ticket);
6186
6930
  return created(collection, { ticket: structuredClone(ticket), audit: null }, ticket);
6187
6931
  }
@@ -6189,15 +6933,15 @@ function zendeskOperation(method, path, params, _headers, data, sequence) {
6189
6933
  if (Object.keys(params).length) return void 0;
6190
6934
  return ok(collection, envelope(records));
6191
6935
  }
6192
- if (method === "GET" && id && resource === "tickets") {
6936
+ if (method === "GET" && id && resource2 === "tickets") {
6193
6937
  const ticket = records.find((r) => String(r.id) === id);
6194
6938
  if (!ticket) return notFound(collection, { error: "RecordNotFound", description: `Not found: ${id}` });
6195
6939
  return ok(collection, { ticket: structuredClone(ticket) });
6196
6940
  }
6197
- if (method === "PUT" && id && resource === "tickets") {
6941
+ if (method === "PUT" && id && resource2 === "tickets") {
6198
6942
  const ticket = typeof id === "string" ? records.find((r) => String(r.id) === id) : void 0;
6199
6943
  if (!ticket) return notFound(collection, { error: "RecordNotFound", description: `Not found: ${id}` });
6200
- if (Object.keys(params).some((k) => k !== "ticket") || !isObject2(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
6944
+ if (Object.keys(params).some((k) => k !== "ticket") || !isObject4(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
6201
6945
  const ticketParams = params.ticket;
6202
6946
  if (Object.keys(ticketParams).some((k) => !["subject", "status", "priority", "tags"].includes(k))) return void 0;
6203
6947
  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" });
@@ -6211,7 +6955,7 @@ function zendeskOperation(method, path, params, _headers, data, sequence) {
6211
6955
  function restUnsupportedBody(adapter) {
6212
6956
  return UNSUPPORTED_BODIES[adapter];
6213
6957
  }
6214
- var EPOCH2, iso2, sha, detUuid, rows, notFound, badRequest, ok, created, write2, isObject2, str, pagination, uniqueId, boundedInt, notionPropValue, notionPage, notionError, hubspotEnvelope, SHOPIFY_VERSION, shopifySlug, googleError, rowsIn, GMAIL_MESSAGES, GMAIL_THREADS, GMAIL_DRAFTS, GMAIL_SEND_AS, GMAIL_WATCH, PUBSUB_SUBSCRIPTIONS, PUBSUB_MESSAGES, gmailHeader, gmailDate, gmailThreadMessages, GMAIL_SYSTEM_LABELS, gmailLabelKnown, gmailHistoryId, withPush, GMAIL_SYSTEM_LABEL_NAMES, JIRA_TRANSITIONS, discordError, ZENDESK_STATUSES, UNSUPPORTED_BODIES, REST_ADAPTERS, REST_ADAPTER_NAMES;
6958
+ var EPOCH2, iso2, sha, detUuid, rows5, notFound, badRequest, ok, created, write2, isObject4, str, pagination, uniqueId, boundedInt, notionPropValue, notionPage, notionError, hubspotEnvelope, SHOPIFY_VERSION, shopifySlug, googleError, rowsIn, GMAIL_MESSAGES, GMAIL_THREADS, GMAIL_DRAFTS, GMAIL_SEND_AS, GMAIL_WATCH, PUBSUB_SUBSCRIPTIONS, PUBSUB_MESSAGES, gmailHeader, gmailDate, gmailThreadMessages, GMAIL_SYSTEM_LABELS, gmailLabelKnown, gmailHistoryId, gmailNextHistoryId, gmailPageOffset, gmailLabelFilter, withPush, GMAIL_SYSTEM_LABEL_NAMES, JIRA_TRANSITIONS, discordError, ZENDESK_STATUSES, UNSUPPORTED_BODIES, REST_ADAPTERS, REST_ADAPTER_NAMES;
6215
6959
  var init_rest_adapters = __esm({
6216
6960
  "src/runtime/rest-adapters.ts"() {
6217
6961
  "use strict";
@@ -6220,6 +6964,10 @@ var init_rest_adapters = __esm({
6220
6964
  init_composio_twin();
6221
6965
  init_google_oauth_twin();
6222
6966
  init_upstash_redis_twin();
6967
+ init_posthog_twin();
6968
+ init_tinybird_twin();
6969
+ init_lemonsqueezy_twin();
6970
+ init_qstash_twin();
6223
6971
  init_gmail_mime();
6224
6972
  EPOCH2 = 17e8;
6225
6973
  iso2 = (epoch = EPOCH2) => new Date(twinNowMs(epoch * 1e3)).toISOString();
@@ -6231,13 +6979,13 @@ var init_rest_adapters = __esm({
6231
6979
  const s = hex.join("");
6232
6980
  return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
6233
6981
  };
6234
- rows = (data, collection) => data[collection];
6982
+ rows5 = (data, collection) => data[collection];
6235
6983
  notFound = (collection, body) => ({ status: 404, body, collection });
6236
6984
  badRequest = (collection, body) => ({ status: 400, body, collection });
6237
6985
  ok = (collection, body, operation = "read") => ({ status: 200, body, collection, operation });
6238
6986
  created = (collection, body, record3) => ({ status: 201, body, collection, record: structuredClone(record3), operation: "write" });
6239
6987
  write2 = (status, collection, body, record3) => ({ status, body, collection, record: structuredClone(record3), operation: "write" });
6240
- isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
6988
+ isObject4 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
6241
6989
  str = (v) => typeof v === "string" ? v : void 0;
6242
6990
  pagination = (params, limitDefault, limitMax) => {
6243
6991
  if (params.limit !== void 0 && (!Number.isInteger(Number(params.limit)) || Number(params.limit) < 1 || Number(params.limit) > limitMax)) return void 0;
@@ -6255,11 +7003,11 @@ var init_rest_adapters = __esm({
6255
7003
  return Number.isInteger(n) && n >= min && n <= max ? n : null;
6256
7004
  };
6257
7005
  notionPropValue = (property) => {
6258
- if (!isObject2(property)) return property;
7006
+ if (!isObject4(property)) return property;
6259
7007
  if (property.title !== void 0) return Array.isArray(property.title) ? property.title.map((t) => t?.plain_text ?? t?.text?.content ?? "").join("") : property.title;
6260
7008
  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;
6261
- if (property.select !== void 0) return isObject2(property.select) ? property.select.name : property.select;
6262
- if (property.status !== void 0) return isObject2(property.status) ? property.status.name : property.status;
7009
+ if (property.select !== void 0) return isObject4(property.select) ? property.select.name : property.select;
7010
+ if (property.status !== void 0) return isObject4(property.status) ? property.status.name : property.status;
6263
7011
  return property.number ?? property.checkbox ?? property.url ?? property.email ?? property.phone_number ?? null;
6264
7012
  };
6265
7013
  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 });
@@ -6285,6 +7033,9 @@ var init_rest_adapters = __esm({
6285
7033
  return (id) => GMAIL_SYSTEM_LABELS.has(id) || seeded.has(id);
6286
7034
  };
6287
7035
  gmailHistoryId = (messages) => messages.reduce((max, m) => BigInt(String(m.historyId ?? 0)) > BigInt(max) ? String(m.historyId) : max, "0");
7036
+ gmailNextHistoryId = (data) => String(BigInt(gmailHistoryId(rowsIn(data, GMAIL_MESSAGES))) + 1n);
7037
+ gmailPageOffset = (value, total) => value === void 0 ? 0 : typeof value === "string" && /^\d{1,9}$/.test(value) && Number(value) <= total ? Number(value) : void 0;
7038
+ gmailLabelFilter = (params) => params.labelIds === void 0 ? [] : Array.isArray(params.labelIds) ? params.labelIds.map(String) : [String(params.labelIds)];
6288
7039
  withPush = (result, deliveries) => deliveries.length ? { ...result, deliveries } : result;
6289
7040
  GMAIL_SYSTEM_LABEL_NAMES = /* @__PURE__ */ new Set(["INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT", "CHAT"]);
6290
7041
  JIRA_TRANSITIONS = { "11": "To Do", "21": "In Progress", "31": "Done" };
@@ -6308,7 +7059,11 @@ var init_rest_adapters = __esm({
6308
7059
  openai: { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the AgentTwin scripted OpenAI subset, or no scripted response is left" }, forwardedToProduction: false },
6309
7060
  anthropic: { type: "error", error: { type: "invalid_request_error", message: "Outside the AgentTwin scripted Anthropic subset, or no scripted response is left" }, forwardedToProduction: false },
6310
7061
  zendesk: { error: "UnsupportedOperation", description: "Outside the verified AgentTwin Zendesk twin subset", forwardedToProduction: false },
6311
- "upstash-redis": { error: "ERR outside the verified AgentTwin Upstash Redis twin subset", forwardedToProduction: false }
7062
+ "upstash-redis": { error: "ERR outside the verified AgentTwin Upstash Redis twin subset", forwardedToProduction: false },
7063
+ posthog: { status: 0, error: "Outside the verified AgentTwin PostHog twin subset", forwardedToProduction: false },
7064
+ tinybird: { error: "Outside the verified AgentTwin Tinybird twin subset", documentation: "https://www.tinybird.co/docs/api-reference", forwardedToProduction: false },
7065
+ lemonsqueezy: { errors: [{ status: "501", title: "Unsupported Operation", detail: "Outside the verified AgentTwin Lemon Squeezy twin subset" }], forwardedToProduction: false },
7066
+ qstash: { error: "Outside the verified AgentTwin QStash twin subset", forwardedToProduction: false }
6312
7067
  };
6313
7068
  REST_ADAPTERS = {
6314
7069
  openai: openaiOperation,
@@ -6328,7 +7083,11 @@ var init_rest_adapters = __esm({
6328
7083
  zendesk: zendeskOperation,
6329
7084
  "google-oauth": googleOAuthOperation,
6330
7085
  composio: composioOperation,
6331
- "upstash-redis": upstashRedisOperation
7086
+ "upstash-redis": upstashRedisOperation,
7087
+ posthog: posthogOperation,
7088
+ tinybird: tinybirdOperation,
7089
+ lemonsqueezy: lemonsqueezyOperation,
7090
+ qstash: qstashOperation
6332
7091
  };
6333
7092
  REST_ADAPTER_NAMES = Object.keys(REST_ADAPTERS);
6334
7093
  }
@@ -6432,11 +7191,11 @@ var init_postgrest = __esm({
6432
7191
  return clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
6433
7192
  }
6434
7193
  async handle(request) {
6435
- const header3 = (name) => {
7194
+ const header4 = (name) => {
6436
7195
  const v = request.headers[name];
6437
7196
  return Array.isArray(v) ? v.join(",") : v ?? "";
6438
7197
  };
6439
- const prefer = header3("prefer"), single = /vnd\.pgrst\.object/.test(header3("accept"));
7198
+ const prefer = header4("prefer"), single = /vnd\.pgrst\.object/.test(header4("accept"));
6440
7199
  const reply = (status, body, extra = {}) => ({ status, headers: { "content-type": "application/json; charset=utf-8", ...extra }, body: body === void 0 ? "" : JSON.stringify(body) });
6441
7200
  const segments = request.url.pathname.replace(/^\/rest\/v1\/?/, "").split("/").filter(Boolean).map(decodeURIComponent);
6442
7201
  if (!segments.length) return reply(404, { code: "PGRST125", message: "Invalid path specified in request URL" });
@@ -6455,8 +7214,8 @@ var init_postgrest = __esm({
6455
7214
  return `${ident2(k)} => $${i + 1}`;
6456
7215
  });
6457
7216
  const r = await this.pool.query(`SELECT to_json(f) AS v FROM ${ident2(segments[1])}(${list2.join(", ")}) f`, values);
6458
- const rows3 = r.rows.map((x) => x.v);
6459
- 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);
7217
+ const rows7 = r.rows.map((x) => x.v);
7218
+ 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);
6460
7219
  }
6461
7220
  const table2 = segments[0], t = ident2(table2);
6462
7221
  const returning = async (sql2) => {
@@ -6475,9 +7234,9 @@ var init_postgrest = __esm({
6475
7234
  perRow = true;
6476
7235
  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`;
6477
7236
  } else if (method === "POST") {
6478
- const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
6479
- const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
6480
- values.push(JSON.stringify(rows3));
7237
+ const rows7 = Array.isArray(payload) ? payload : [payload ?? {}];
7238
+ const keys = [...new Set(rows7.flatMap((r) => Object.keys(r)))];
7239
+ values.push(JSON.stringify(rows7));
6481
7240
  const target = params.get("on_conflict")?.split(",").map(ident2).join(", ");
6482
7241
  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;
6483
7242
  const merge = /resolution=merge-duplicates/.test(prefer), ignore = /resolution=ignore-duplicates/.test(prefer);
@@ -6495,12 +7254,12 @@ var init_postgrest = __esm({
6495
7254
  sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
6496
7255
  } else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
6497
7256
  const result = await this.pool.query(sql, values);
6498
- const rows2 = perRow ? result.rows.map((r) => r.row) : result.rows[0]?.rows ?? [];
6499
- const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
7257
+ const rows6 = perRow ? result.rows.map((r) => r.row) : result.rows[0]?.rows ?? [];
7258
+ const range = { "content-range": `0-${Math.max(rows6.length - 1, 0)}/${/count=exact/.test(prefer) ? rows6.length : "*"}` };
6500
7259
  if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6501
7260
  if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6502
- 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 });
6503
- return reply(status, rows2, range);
7261
+ 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 });
7262
+ return reply(status, rows6, range);
6504
7263
  } catch (error) {
6505
7264
  const e = error;
6506
7265
  const status = e.code === "23505" ? 409 : e.code === "42P01" ? 404 : e.code === "42501" ? 403 : 400;
@@ -6512,7 +7271,7 @@ var init_postgrest = __esm({
6512
7271
  });
6513
7272
 
6514
7273
  // src/runtime/gotrue.ts
6515
- import { createHash as createHash6, createHmac, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
7274
+ import { createHash as createHash6, createHmac as createHmac3, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
6516
7275
  var b64url, userIdFor, GoTrueLayer;
6517
7276
  var init_gotrue = __esm({
6518
7277
  "src/runtime/gotrue.ts"() {
@@ -6523,9 +7282,9 @@ var init_gotrue = __esm({
6523
7282
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
6524
7283
  };
6525
7284
  GoTrueLayer = class {
6526
- constructor(secret = randomBytes2(32).toString("hex"), now = () => /* @__PURE__ */ new Date()) {
7285
+ constructor(secret = randomBytes2(32).toString("hex"), now5 = () => /* @__PURE__ */ new Date()) {
6527
7286
  this.secret = secret;
6528
- this.now = now;
7287
+ this.now = now5;
6529
7288
  }
6530
7289
  secret;
6531
7290
  now;
@@ -6539,12 +7298,12 @@ var init_gotrue = __esm({
6539
7298
  }
6540
7299
  sign(claims) {
6541
7300
  const head = b64url(JSON.stringify({ alg: "HS256", typ: "JWT" })), body = b64url(JSON.stringify(claims));
6542
- return `${head}.${body}.${b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest())}`;
7301
+ return `${head}.${body}.${b64url(createHmac3("sha256", this.secret).update(`${head}.${body}`).digest())}`;
6543
7302
  }
6544
7303
  verify(token) {
6545
7304
  const [head, body, sig] = token.split(".");
6546
7305
  if (!head || !body || !sig) return void 0;
6547
- if (b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest()) !== sig) return void 0;
7306
+ if (b64url(createHmac3("sha256", this.secret).update(`${head}.${body}`).digest()) !== sig) return void 0;
6548
7307
  try {
6549
7308
  const c = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
6550
7309
  return typeof c.exp === "number" && c.exp * 1e3 < this.now().getTime() ? void 0 : c;
@@ -6709,8 +7468,8 @@ var init_supabase_storage = __esm({
6709
7468
  "src/runtime/supabase-storage.ts"() {
6710
7469
  "use strict";
6711
7470
  StorageLayer = class {
6712
- constructor(now = () => /* @__PURE__ */ new Date()) {
6713
- this.now = now;
7471
+ constructor(now5 = () => /* @__PURE__ */ new Date()) {
7472
+ this.now = now5;
6714
7473
  }
6715
7474
  now;
6716
7475
  buckets = /* @__PURE__ */ new Map();
@@ -6738,7 +7497,7 @@ var init_supabase_storage = __esm({
6738
7497
  return {};
6739
7498
  }
6740
7499
  };
6741
- const header3 = (name) => {
7500
+ const header4 = (name) => {
6742
7501
  const v = request.headers[name];
6743
7502
  return Array.isArray(v) ? v[0] : v;
6744
7503
  };
@@ -6779,9 +7538,9 @@ var init_supabase_storage = __esm({
6779
7538
  const [, bucket, name] = obj;
6780
7539
  const k = this.key(bucket, name);
6781
7540
  if (method === "POST" || method === "PUT") {
6782
- if (method === "POST" && this.objects.has(k) && header3("x-upsert") !== "true") return fail(400, "Duplicate", "The resource already exists");
7541
+ if (method === "POST" && this.objects.has(k) && header4("x-upsert") !== "true") return fail(400, "Duplicate", "The resource already exists");
6783
7542
  this.bucket(bucket);
6784
- 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() });
7543
+ 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() });
6785
7544
  return reply(200, { Key: k, Id: k }, `uploaded ${k} (${request.body?.length ?? 0} bytes)`);
6786
7545
  }
6787
7546
  if (method === "GET" || method === "HEAD") {
@@ -6992,12 +7751,12 @@ var init_http_world = __esm({
6992
7751
  sampleResources() {
6993
7752
  const resources = this.spec.resources;
6994
7753
  if (!resources?.length || this.resourceSampleCount >= 5e3) return;
6995
- for (const resource of resources) {
7754
+ for (const resource2 of resources) {
6996
7755
  if (this.resourceSampleCount >= 5e3) return;
6997
- const rows2 = this.state[resource.service]?.[resource.path] ?? [];
6998
- const count = resource.where ? rows2.filter((row) => Object.entries(resource.where).every(([key2, value]) => isDeepStrictEqual(row[key2], value))).length : rows2.length;
7756
+ const rows6 = this.state[resource2.service]?.[resource2.path] ?? [];
7757
+ const count = resource2.where ? rows6.filter((row) => Object.entries(resource2.where).every(([key2, value]) => isDeepStrictEqual(row[key2], value))).length : rows6.length;
6999
7758
  this.resourceSampleCount++;
7000
- this.record(resource.service, "resource", resource.path, `resource ${resource.id} = ${count}`, { resource: resource.id, count });
7759
+ this.record(resource2.service, "resource", resource2.path, `resource ${resource2.id} = ${count}`, { resource: resource2.id, count });
7001
7760
  }
7002
7761
  }
7003
7762
  /**
@@ -7352,6 +8111,13 @@ var init_http_world = __esm({
7352
8111
  const all = form.getAll(key3);
7353
8112
  parsed[key3] = all.length > 1 ? all : all[0];
7354
8113
  }
8114
+ } else if (enterprise && String(req.headers["content-type"] ?? "").startsWith("application/x-www-form-urlencoded")) {
8115
+ const form = new URLSearchParams(text2);
8116
+ parsed = {};
8117
+ for (const key3 of new Set(form.keys())) {
8118
+ const all = form.getAll(key3);
8119
+ parsed[key3] = all.length > 1 ? all : all[0];
8120
+ }
7355
8121
  } else if (mode === "raw") {
7356
8122
  rawBody = text2;
7357
8123
  parsed = {};
@@ -7364,6 +8130,9 @@ var init_http_world = __esm({
7364
8130
  } else if (service.adapter === "upstash-redis") {
7365
8131
  rawBody = text2;
7366
8132
  parsed = {};
8133
+ } else if (service.adapter === "tinybird" || service.adapter === "qstash") {
8134
+ rawBody = text2;
8135
+ parsed = Object.fromEntries(url.searchParams);
7367
8136
  } else if (service.adapter === "gmail" && !text2.trim()) parsed = {};
7368
8137
  else if (service.adapter === "google-oauth") {
7369
8138
  if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
@@ -7724,14 +8493,14 @@ var init_http_world = __esm({
7724
8493
  }
7725
8494
  if (type.startsWith("_")) continue;
7726
8495
  const collection = packCollection(type, path);
7727
- const rows2 = data[collection] ??= [];
7728
- const at = rows2.findIndex((r) => r.id === id);
8496
+ const rows6 = data[collection] ??= [];
8497
+ const at = rows6.findIndex((r) => r.id === id);
7729
8498
  const removed = /^(del|delete|remove)$/i.test(a.op ?? "") || /\.(delete|del)$/.test(a.operation ?? "");
7730
8499
  const row = { id, ...a.fields ?? {} };
7731
8500
  if (removed) {
7732
- if (at >= 0) rows2.splice(at, 1);
7733
- } else if (at >= 0) rows2[at] = { ...rows2[at], ...row };
7734
- else rows2.push(row);
8501
+ if (at >= 0) rows6.splice(at, 1);
8502
+ } else if (at >= 0) rows6[at] = { ...rows6[at], ...row };
8503
+ else rows6.push(row);
7735
8504
  if (!evidence) continue;
7736
8505
  const byApp = a.actor?.kind === "agent" && !byWorld;
7737
8506
  this.record(service.name, byApp ? "write" : "twin", collection, `${method} ${path} \u2192 ${a.operation ?? type} ${id}${byApp ? "" : " (by the twin)"}`, row);
@@ -8123,8 +8892,8 @@ var init_http_world = __esm({
8123
8892
  }
8124
8893
  assertions() {
8125
8894
  return this.spec.assertions.map((a) => {
8126
- const rows2 = this.state[a.service][a.path].filter((row) => !a.where || Object.entries(a.where).every(([k, v]) => isDeepStrictEqual(row[k], v)));
8127
- return { ...a, actual: rows2.length, passed: rows2.length === a.count };
8895
+ const rows6 = this.state[a.service][a.path].filter((row) => !a.where || Object.entries(a.where).every(([k, v]) => isDeepStrictEqual(row[k], v)));
8896
+ return { ...a, actual: rows6.length, passed: rows6.length === a.count };
8128
8897
  });
8129
8898
  }
8130
8899
  get faultTriggered() {
@@ -8259,9 +9028,9 @@ async function processes() {
8259
9028
  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";
8260
9029
  const { stdout: stdout2 } = await exec2(shell, ["-NoProfile", "-NonInteractive", "-Command", script], { timeout: 1e3, windowsHide: true, maxBuffer: 4 * 1024 * 1024 });
8261
9030
  const data = JSON.parse(stdout2.trim() || "[]");
8262
- const rows2 = Array.isArray(data) ? data : [data];
8263
- if (!rows2.every((r) => Number.isSafeInteger(r.pid) && Number.isSafeInteger(r.parent) && typeof r.born === "string")) throw Error("Invalid process evidence");
8264
- return rows2;
9031
+ const rows6 = Array.isArray(data) ? data : [data];
9032
+ if (!rows6.every((r) => Number.isSafeInteger(r.pid) && Number.isSafeInteger(r.parent) && typeof r.born === "string")) throw Error("Invalid process evidence");
9033
+ return rows6;
8265
9034
  }
8266
9035
  const { stdout } = await exec2("ps", ["-axo", "pid=,ppid=,stat=,lstart="], { timeout: 1e3, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } });
8267
9036
  return stdout.trim().split("\n").filter(Boolean).map((line) => {
@@ -8285,21 +9054,21 @@ function manageApplication(child) {
8285
9054
  child.once("error", () => resolve9());
8286
9055
  });
8287
9056
  async function capture() {
8288
- const rows2 = await processes();
8289
- for (const [pid, born] of known2) if (!rows2.some((r) => r.pid === pid && r.born === born)) known2.delete(pid);
8290
- const root = rows2.find((r) => r.pid === child.pid);
9057
+ const rows6 = await processes();
9058
+ for (const [pid, born] of known2) if (!rows6.some((r) => r.pid === pid && r.born === born)) known2.delete(pid);
9059
+ const root = rows6.find((r) => r.pid === child.pid);
8291
9060
  if (root && child.exitCode === null && child.signalCode === null) known2.set(root.pid, root.born);
8292
9061
  let changed = true;
8293
9062
  while (changed) {
8294
9063
  changed = false;
8295
- for (const row of rows2) {
9064
+ for (const row of rows6) {
8296
9065
  if (row.pid > 1 && known2.has(row.parent) && !known2.has(row.pid)) {
8297
9066
  known2.set(row.pid, row.born);
8298
9067
  changed = true;
8299
9068
  }
8300
9069
  }
8301
9070
  }
8302
- return rows2.filter((r) => known2.get(r.pid) === r.born && !r.state.startsWith("Z"));
9071
+ return rows6.filter((r) => known2.get(r.pid) === r.born && !r.state.startsWith("Z"));
8303
9072
  }
8304
9073
  let scanning = false;
8305
9074
  const tick = () => {
@@ -8408,18 +9177,18 @@ function windowsBrowserProcess(executable, commands = run) {
8408
9177
  async function snapshot() {
8409
9178
  const { stdout } = await commands(powershell, ["-NoProfile", "-NonInteractive", "-Command", script]);
8410
9179
  const parsed = JSON.parse(stdout.trim() || "[]");
8411
- const rows2 = Array.isArray(parsed) ? parsed : [parsed];
8412
- 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");
8413
- return rows2;
9180
+ const rows6 = Array.isArray(parsed) ? parsed : [parsed];
9181
+ 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");
9182
+ return rows6;
8414
9183
  }
8415
9184
  async function owned() {
8416
- const rows2 = await snapshot();
8417
- for (const [pid, created2] of known2) if (!rows2.some((r) => r.pid === pid && r.created === created2)) known2.delete(pid);
8418
- for (const row of rows2) if (row.parent === process.pid && row.command.split(/[\s"]+/).includes(marker)) known2.set(row.pid, row.created);
9185
+ const rows6 = await snapshot();
9186
+ for (const [pid, created2] of known2) if (!rows6.some((r) => r.pid === pid && r.created === created2)) known2.delete(pid);
9187
+ for (const row of rows6) if (row.parent === process.pid && row.command.split(/[\s"]+/).includes(marker)) known2.set(row.pid, row.created);
8419
9188
  let changed = true;
8420
9189
  while (changed) {
8421
9190
  changed = false;
8422
- for (const row of rows2) {
9191
+ for (const row of rows6) {
8423
9192
  const parent = known2.get(row.parent);
8424
9193
  if (row.pid > 1 && parent && row.created >= parent && !known2.has(row.pid)) {
8425
9194
  known2.set(row.pid, row.created);
@@ -8427,7 +9196,7 @@ function windowsBrowserProcess(executable, commands = run) {
8427
9196
  }
8428
9197
  }
8429
9198
  }
8430
- return rows2.filter((r) => known2.get(r.pid) === r.created);
9199
+ return rows6.filter((r) => known2.get(r.pid) === r.created);
8431
9200
  }
8432
9201
  return {
8433
9202
  launcher: executable,
@@ -8491,7 +9260,7 @@ exec ${quote(executable)} "$@"
8491
9260
  throw e;
8492
9261
  }
8493
9262
  if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error("Invalid browser process identity");
8494
- const rows2 = await processes2(), leader = rows2.find((p) => p.pid === pid);
9263
+ const rows6 = await processes2(), leader = rows6.find((p) => p.pid === pid);
8495
9264
  if (leader && leader.pgid !== pid) throw new Error("Browser launcher does not own its process group");
8496
9265
  group = pid;
8497
9266
  return group;
@@ -9241,14 +10010,14 @@ function evaluateState(spec, initial, final, events) {
9241
10010
  function evaluateProperty(policy, final, events) {
9242
10011
  const timing = policy.timing ?? "eventually";
9243
10012
  const base = { id: policy.id, kind: "property", propertyKind: policy.kind, timing, service: policy.service, path: policy.path, passed: false };
9244
- const rows2 = final[policy.service]?.[policy.path];
9245
- if (!rows2) return { ...base, expected: "intact", actual: "missing collection", evidence: { timing, evidenceGap: `final state has no collection "${policy.path}" in "${policy.service}"` } };
9246
- if (timing === "always") return evaluateAlwaysProperty(policy, rows2, events, base);
10013
+ const rows6 = final[policy.service]?.[policy.path];
10014
+ if (!rows6) return { ...base, expected: "intact", actual: "missing collection", evidence: { timing, evidenceGap: `final state has no collection "${policy.path}" in "${policy.service}"` } };
10015
+ if (timing === "always") return evaluateAlwaysProperty(policy, rows6, events, base);
9247
10016
  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)));
9248
10017
  if (policy.kind === "unique-per-act") {
9249
10018
  const field = String(policy.params?.field);
9250
10019
  const keyed = /* @__PURE__ */ new Map();
9251
- for (const row of rows2) {
10020
+ for (const row of rows6) {
9252
10021
  if (row[field] === void 0) continue;
9253
10022
  const key2 = JSON.stringify(canonical(row[field]));
9254
10023
  keyed.set(key2, [...keyed.get(key2) ?? [], row.id ?? row]);
@@ -9264,7 +10033,7 @@ function evaluateProperty(policy, final, events) {
9264
10033
  }
9265
10034
  if (policy.kind === "no-loss") {
9266
10035
  const writes = eventsFor("write", policy.params?.where);
9267
- const lost = writes.filter((e) => e.record !== void 0 && !recordPresent(rows2, e.record));
10036
+ const lost = writes.filter((e) => e.record !== void 0 && !recordPresent(rows6, e.record));
9268
10037
  const unknown2 = writes.some((e) => !e.record);
9269
10038
  return {
9270
10039
  ...base,
@@ -9287,7 +10056,7 @@ function evaluateProperty(policy, final, events) {
9287
10056
  evidence: { timing, operation, eventSequences: hits.map((e) => e.sequence), evidenceGap: unknown }
9288
10057
  };
9289
10058
  }
9290
- function evaluateAlwaysProperty(policy, rows2, events, base) {
10059
+ function evaluateAlwaysProperty(policy, rows6, events, base) {
9291
10060
  const relevant = events.filter((e) => e.service === policy.service && e.path === policy.path);
9292
10061
  if (policy.kind === "unique-per-act") {
9293
10062
  const field = String(policy.params?.field);
@@ -9324,7 +10093,7 @@ function evaluateAlwaysProperty(policy, rows2, events, base) {
9324
10093
  if (policy.kind === "no-loss") {
9325
10094
  const where2 = policy.params?.where;
9326
10095
  const writes = relevant.filter((e) => e.operation === "write" && (!where2 || e.record !== void 0 && matches(e.record, where2)));
9327
- const lost = writes.filter((e) => e.record !== void 0 && !recordPresent(rows2, e.record));
10096
+ const lost = writes.filter((e) => e.record !== void 0 && !recordPresent(rows6, e.record));
9328
10097
  const evidenceGap2 = writes.some((e) => !e.record);
9329
10098
  return {
9330
10099
  ...base,
@@ -9382,7 +10151,7 @@ var init_evaluation = __esm({
9382
10151
  matches = (row, where) => !where || Object.entries(where).every(([k, v]) => isDeepStrictEqual3(row[k], v));
9383
10152
  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;
9384
10153
  short = (value, limit = 120) => value.length <= limit ? value : `${value.slice(0, limit)}\u2026`;
9385
- recordPresent = (rows2, record3) => typeof record3.id === "string" && record3.id ? rows2.some((row) => row.id === record3.id) : rows2.some((row) => isDeepStrictEqual3(row, record3));
10154
+ recordPresent = (rows6, record3) => typeof record3.id === "string" && record3.id ? rows6.some((row) => row.id === record3.id) : rows6.some((row) => isDeepStrictEqual3(row, record3));
9386
10155
  escape = (value) => value.replace(/~/g, "~0").replace(/\//g, "~1");
9387
10156
  }
9388
10157
  });
@@ -9408,7 +10177,7 @@ var init_run_summary = __esm({
9408
10177
 
9409
10178
  // src/runtime/application-activity.ts
9410
10179
  function isApplicationWrite(event) {
9411
- return event.operation === "write" && !event.path?.startsWith("/_twin/") && !/^[A-Z]+ \/_twin\//.test(event.detail ?? "");
10180
+ return event.operation === "write" && event.activity !== "bookkeeping" && !event.path?.startsWith("/_twin/") && !/^[A-Z]+ \/_twin\//.test(event.detail ?? "");
9412
10181
  }
9413
10182
  var init_application_activity = __esm({
9414
10183
  "src/runtime/application-activity.ts"() {
@@ -9775,11 +10544,11 @@ var init_generic_calls = __esm({
9775
10544
 
9776
10545
  // src/runtime/default-checks.ts
9777
10546
  function addedRows(initial, final) {
9778
- const rows2 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
9779
- const ids = new Set(rows2(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
10547
+ const rows6 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
10548
+ const ids = new Set(rows6(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
9780
10549
  const seen = /* @__PURE__ */ new Map();
9781
- for (const r of rows2(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
9782
- return rows2(final).filter((r) => {
10550
+ for (const r of rows6(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
10551
+ return rows6(final).filter((r) => {
9783
10552
  if (r.id !== void 0 && r.id !== null) return !ids.has(r.id);
9784
10553
  const key2 = canonical3(r), left = seen.get(key2) ?? 0;
9785
10554
  if (left > 0) {
@@ -10029,8 +10798,8 @@ var init_default_checks = __esm({
10029
10798
  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;
10030
10799
  gmailText = (r) => {
10031
10800
  const headers = r.payload?.headers ?? [];
10032
- const header3 = (name) => headers.find((h) => h.name?.toLowerCase() === name)?.value ?? "";
10033
- return { to: header3("to"), subject: header3("subject"), body: String(r.payload?.body?.data ?? r.snippet ?? "") };
10801
+ const header4 = (name) => headers.find((h) => h.name?.toLowerCase() === name)?.value ?? "";
10802
+ return { to: header4("to"), subject: header4("subject"), body: String(r.payload?.body?.data ?? r.snippet ?? "") };
10034
10803
  };
10035
10804
  TARGETED = /\bwhere\b[\s\S]*=\s*\$\d/i;
10036
10805
  postgresUpdateApplied = {
@@ -10578,6 +11347,8 @@ var init_twin_routing = __esm({
10578
11347
  stripe: [{ hosts: ["api.stripe.com", "files.stripe.com"], auth: "bearer" }],
10579
11348
  slack: [{ hosts: ["slack.com", "www.slack.com"], auth: "bearer" }],
10580
11349
  gmail: [{ hosts: ["gmail.googleapis.com"], auth: "bearer" }, { hosts: ["www.googleapis.com"], pathPrefix: "/gmail", auth: "bearer" }],
11350
+ // Microsoft Graph mail: the Graph API and the identity token endpoints it authenticates with share one twin.
11351
+ outlook: [{ hosts: ["graph.microsoft.com"], auth: "bearer" }, { hosts: ["login.microsoftonline.com", "login.microsoft.com"], auth: "bearer" }],
10581
11352
  "google-calendar": [{ hosts: ["www.googleapis.com"], pathPrefix: "/calendar", auth: "bearer" }],
10582
11353
  "google-oauth": [{ hosts: ["oauth2.googleapis.com"], auth: "bearer" }],
10583
11354
  github: [{ hosts: ["api.github.com"], auth: "bearer" }],
@@ -10590,7 +11361,11 @@ var init_twin_routing = __esm({
10590
11361
  jira: [{ hosts: ["atlassian.net"], suffix: true, auth: "bearer" }],
10591
11362
  shopify: [{ hosts: ["myshopify.com"], suffix: true, auth: "bearer" }],
10592
11363
  gitlab: [{ hosts: ["gitlab.com"], auth: "bearer" }],
10593
- datadog: [{ hosts: ["api.datadoghq.com", "api.datadoghq.eu", "api.us5.datadoghq.com"], auth: "bearer" }]
11364
+ datadog: [{ hosts: ["api.datadoghq.com", "api.datadoghq.eu", "api.us5.datadoghq.com"], auth: "bearer" }],
11365
+ posthog: [{ hosts: ["us.i.posthog.com", "eu.i.posthog.com", "app.posthog.com", "us.posthog.com", "eu.posthog.com"], auth: "bearer" }],
11366
+ tinybird: [{ hosts: ["api.tinybird.co", "cloud.tinybird.co"], auth: "bearer" }, { hosts: ["tinybird.co"], suffix: true, auth: "bearer" }],
11367
+ lemonsqueezy: [{ hosts: ["api.lemonsqueezy.com"], auth: "bearer" }],
11368
+ qstash: [{ hosts: ["qstash.upstash.io", "qstash-us-east-1.upstash.io", "qstash-eu-central-1.upstash.io", "qstash-us-west-1.upstash.io"], auth: "bearer" }]
10594
11369
  };
10595
11370
  TWIN_PRELOAD = String.raw`'use strict';
10596
11371
  if(process.env.AGENTTWIN==='1'&&!globalThis.__agenttwinRouting){(()=>{
@@ -11232,8 +12007,8 @@ async function startPostgresEngine(options = {}) {
11232
12007
  const out = [];
11233
12008
  for (const name of names) {
11234
12009
  const primaryKey = keys.filter((k) => k.table_name === name).map((k) => k.column_name);
11235
- const rows2 = (await db.query(`select * from ${quote2(name)}${primaryKey.length ? ` order by ${primaryKey.map(quote2).join(",")}` : ""} limit 10000`)).rows.map((r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, plain(v)])));
11236
- out.push({ name, columns: cols.filter((c) => c.table_name === name).map((c) => ({ name: c.column_name, type: c.data_type })), primaryKey, rows: rows2 });
12010
+ const rows6 = (await db.query(`select * from ${quote2(name)}${primaryKey.length ? ` order by ${primaryKey.map(quote2).join(",")}` : ""} limit 10000`)).rows.map((r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, plain(v)])));
12011
+ out.push({ name, columns: cols.filter((c) => c.table_name === name).map((c) => ({ name: c.column_name, type: c.data_type })), primaryKey, rows: rows6 });
11237
12012
  }
11238
12013
  return out;
11239
12014
  };
@@ -11244,9 +12019,9 @@ async function startPostgresEngine(options = {}) {
11244
12019
  const result = { tables: [] };
11245
12020
  for (const { name } of tables) {
11246
12021
  const columns = (await db.query("select column_name as name,udt_name as type from information_schema.columns where table_schema='public' and table_name=$1 order by ordinal_position", [name])).rows.map((c) => ({ name: c.name, type: c.type }));
11247
- const rows2 = (await db.query(`select row_to_json(t)::text as row from public.${quote2(name)} t limit ${L.rows + 1}`)).rows.map((r) => JSON.parse(r.row));
11248
- if (columns.length > L.columns || rows2.length > L.rows) throw new Error(`PostgreSQL snapshot exceeds ${L.columns} columns or ${L.rows} rows in table ${name}`);
11249
- result.tables.push({ name, columns, rows: rows2.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) });
12022
+ const rows6 = (await db.query(`select row_to_json(t)::text as row from public.${quote2(name)} t limit ${L.rows + 1}`)).rows.map((r) => JSON.parse(r.row));
12023
+ if (columns.length > L.columns || rows6.length > L.rows) throw new Error(`PostgreSQL snapshot exceeds ${L.columns} columns or ${L.rows} rows in table ${name}`);
12024
+ result.tables.push({ name, columns, rows: rows6.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) });
11250
12025
  }
11251
12026
  if (Buffer.byteLength(JSON.stringify(result)) > L.bytes) throw new Error(`PostgreSQL snapshot exceeds ${L.bytes / 1024} KiB`);
11252
12027
  return result;
@@ -11268,8 +12043,8 @@ async function startPostgresEngine(options = {}) {
11268
12043
  if (data.sql) {
11269
12044
  for (const part of data.sql.split(/^(?=-- Schema source: )/m)) if (part.trim()) await db.exec(part);
11270
12045
  }
11271
- for (const [table2, rows2] of Object.entries(data.tables ?? {})) {
11272
- for (const row of rows2) {
12046
+ for (const [table2, rows6] of Object.entries(data.tables ?? {})) {
12047
+ for (const row of rows6) {
11273
12048
  const fields = Object.keys(row);
11274
12049
  if (!fields.length) {
11275
12050
  await db.exec(`insert into ${quoteTable(table2)} default values`);
@@ -11337,8 +12112,8 @@ async function startPostgresEngine(options = {}) {
11337
12112
  await db.exec("BEGIN READ ONLY");
11338
12113
  try {
11339
12114
  const result = await db.query(`SELECT COALESCE(json_agg(t), '[]'::json) AS rows FROM (${sql}) t`);
11340
- const rows2 = result.rows[0]?.rows;
11341
- return typeof rows2 === "string" ? JSON.parse(rows2) : rows2 ?? [];
12115
+ const rows6 = result.rows[0]?.rows;
12116
+ return typeof rows6 === "string" ? JSON.parse(rows6) : rows6 ?? [];
11342
12117
  } finally {
11343
12118
  await db.exec("ROLLBACK");
11344
12119
  }
@@ -11433,10 +12208,7 @@ async function startLocalEngines(app, spec) {
11433
12208
  initialTables = await snapshotPublicTables(postgres2).catch(() => void 0);
11434
12209
  }
11435
12210
  if (spec.redis) {
11436
- redis = await startRedisEngine({ prefer: "binary" }).catch((error) => {
11437
- if (error instanceof EngineUnavailable) return startRedisEngine({ prefer: "in-process" });
11438
- throw error;
11439
- });
12211
+ redis = await startRedisEngine();
11440
12212
  started.push(redis);
11441
12213
  }
11442
12214
  } catch (error) {
@@ -11473,7 +12245,6 @@ var init_local_engines = __esm({
11473
12245
  "use strict";
11474
12246
  init_postgres();
11475
12247
  init_redis();
11476
- init_types();
11477
12248
  }
11478
12249
  });
11479
12250
 
@@ -11574,7 +12345,7 @@ async function sourceRoot(app, spec) {
11574
12345
  if (dirname3(candidate) === candidate) return real;
11575
12346
  }
11576
12347
  }
11577
- async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {}, filesDir = app) {
12348
+ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {}, filesDir = app, readRoutingFaults) {
11578
12349
  if (spec.applicationClock && !/(^|\/)node(\.exe)?$/.test(spec.command[0])) throw new Error("applicationClock requires a Node application");
11579
12350
  if (spec.applicationRandom && !/(^|\/)node(\.exe)?$/.test(spec.command[0])) throw new Error("applicationRandom requires a Node application");
11580
12351
  signal?.throwIfAborted();
@@ -11705,6 +12476,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
11705
12476
  try {
11706
12477
  blockedFetches = await hook.readViolations();
11707
12478
  injectedFaults = await hook.readFaults();
12479
+ if (readRoutingFaults) injectedFaults.push(...await readRoutingFaults());
11708
12480
  if (nativeFaultsPath) {
11709
12481
  try {
11710
12482
  injectedFaults.push(...(await readFile7(nativeFaultsPath, "utf8")).split("\n").filter(Boolean).map((line) => JSON.parse(line)));
@@ -11800,8 +12572,8 @@ function parseScenario(value) {
11800
12572
  const services = /* @__PURE__ */ new Set();
11801
12573
  for (const ref of entity.refs) {
11802
12574
  if (!object3(ref) || typeof ref.service !== "string" || typeof ref.path !== "string" || !object3(ref.where) || !Object.keys(ref.where).length || Object.keys(ref).some((k) => !["service", "path", "where"].includes(k))) fail("entity reference needs service, path and a nonempty where selector");
11803
- const rows2 = scenario.services.find((s) => s.name === ref.service)?.collections.find((c) => c.path === ref.path)?.seed;
11804
- if (!rows2 || rows2.filter((row) => Object.entries(ref.where).every(([k, v]) => isDeepStrictEqual4(row[k], v))).length !== 1) fail(`entity ${entity.id} reference must resolve to exactly one seeded record`);
12575
+ const rows6 = scenario.services.find((s) => s.name === ref.service)?.collections.find((c) => c.path === ref.path)?.seed;
12576
+ if (!rows6 || rows6.filter((row) => Object.entries(ref.where).every(([k, v]) => isDeepStrictEqual4(row[k], v))).length !== 1) fail(`entity ${entity.id} reference must resolve to exactly one seeded record`);
11805
12577
  services.add(ref.service);
11806
12578
  }
11807
12579
  if (services.size < 2) fail(`entity ${entity.id} must link at least two services`);