agenttwin 0.3.19 → 0.3.21

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 (75) hide show
  1. package/README.md +7 -9
  2. package/dist/api.js +9240 -1135
  3. package/dist/cli.js +26 -21
  4. package/dist/dashboard/assets/next/static/chunks/1250-7571b1a697f6bb4a.js +1 -0
  5. package/dist/dashboard/assets/next/static/chunks/2868-424d32cfc8ae81c9.js +1 -0
  6. package/dist/dashboard/assets/next/static/chunks/9675.d833ca9b2d89cf8a.js +1 -0
  7. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-9390b6ace45cc1ff.js +1 -0
  8. package/dist/dashboard/assets/next/static/chunks/app/about/page-f7d9ffd4f6138e0e.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-aa11ba1b9100c0ca.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/app/auth/page-aa11ba1b9100c0ca.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-1e8a656895b65474.js +1 -0
  12. package/dist/dashboard/assets/next/static/chunks/app/compare/page-aa11ba1b9100c0ca.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/contact/page-aa11ba1b9100c0ca.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-2d0408d8f22d7921.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-9c11295678539a5f.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/app/developers/page-aa11ba1b9100c0ca.js +1 -0
  17. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-f9fca2c08f779fa0.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-220e50b34fd67668.js +1 -0
  19. package/dist/dashboard/assets/next/static/chunks/app/guides/page-aa11ba1b9100c0ca.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/layout-cd911546738f01ed.js +1 -0
  21. package/dist/dashboard/assets/next/static/chunks/app/not-found-aa11ba1b9100c0ca.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/page-6d01bfbee0186f28.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-1200305185e4183f.js +1 -0
  24. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-aa11ba1b9100c0ca.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-aa11ba1b9100c0ca.js +1 -0
  26. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/{layout-a5cf565e017886d3.js → layout-a1c12faf8094e40e.js} +1 -1
  27. package/dist/dashboard/assets/next/static/chunks/app/v2/page-07c8054d57c9089b.js +1 -0
  28. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-aa11ba1b9100c0ca.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/webpack-40324749d289e4a5.js +1 -0
  30. package/dist/dashboard/assets/next/static/css/1d1b20bd9fb076d4.css +1 -0
  31. package/dist/dashboard/assets/next/static/css/2c38dfe54afd9bb6.css +1 -0
  32. package/dist/dashboard/assets/next/static/css/39133c9a03c8edb8.css +1 -0
  33. package/dist/dashboard/assets/next/static/css/{18afa3e32331c41d.css → 42045de5f39b50ca.css} +1 -1
  34. package/dist/dashboard/assets/next/static/css/{77c0c440ebb56bc4.css → 423c6df577acd447.css} +1 -1
  35. package/dist/dashboard/assets/next/static/css/{d131a6499fe6cf19.css → 4bbe78c2fe206b92.css} +1 -1
  36. package/dist/dashboard/assets/next/static/css/7109685b391c1c46.css +1 -0
  37. package/dist/dashboard/assets/next/static/css/96134c7d160c4fc3.css +1 -0
  38. package/dist/dashboard/assets/next/static/css/b068ffd8e6f22102.css +1 -0
  39. package/dist/dashboard/assets/next/static/css/bbce83b7ab716064.css +1 -0
  40. package/dist/dashboard/index.html +6 -2
  41. package/dist/engine.js +21898 -10960
  42. package/dist/gateway.js +9254 -1142
  43. package/dist/worker.js +1641 -62
  44. package/dist/world-host.js +2380 -80
  45. package/package.json +18 -3
  46. package/dist/dashboard/assets/next/static/chunks/1482.c28f7cd0f92885c1.js +0 -1
  47. package/dist/dashboard/assets/next/static/chunks/2868-b80a3af454408935.js +0 -1
  48. package/dist/dashboard/assets/next/static/chunks/3056.ffa9a4d44a274b29.js +0 -1
  49. package/dist/dashboard/assets/next/static/chunks/5531-fde254dbd21c3153.js +0 -1
  50. package/dist/dashboard/assets/next/static/chunks/9675.14739028910476e4.js +0 -1
  51. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-43db8aef3fa81958.js +0 -1
  52. package/dist/dashboard/assets/next/static/chunks/app/about/page-3f5dbcdbf95bb2fc.js +0 -1
  53. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-3f5dbcdbf95bb2fc.js +0 -1
  54. package/dist/dashboard/assets/next/static/chunks/app/auth/page-3f5dbcdbf95bb2fc.js +0 -1
  55. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-563d8763d65d66b5.js +0 -1
  56. package/dist/dashboard/assets/next/static/chunks/app/compare/page-3f5dbcdbf95bb2fc.js +0 -1
  57. package/dist/dashboard/assets/next/static/chunks/app/contact/page-3f5dbcdbf95bb2fc.js +0 -1
  58. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-1afe915ed22ac5ed.js +0 -1
  59. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-0eb9937f1e5e9c1e.js +0 -1
  60. package/dist/dashboard/assets/next/static/chunks/app/developers/page-3f5dbcdbf95bb2fc.js +0 -1
  61. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-1800a8f06aeb4acb.js +0 -1
  62. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-1fd02494889ae794.js +0 -1
  63. package/dist/dashboard/assets/next/static/chunks/app/guides/page-3f5dbcdbf95bb2fc.js +0 -1
  64. package/dist/dashboard/assets/next/static/chunks/app/layout-993a96283a3ceb07.js +0 -1
  65. package/dist/dashboard/assets/next/static/chunks/app/page-2e622bb9a3459541.js +0 -1
  66. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-40f352fe5093a0ff.js +0 -1
  67. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-3f5dbcdbf95bb2fc.js +0 -1
  68. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-3f5dbcdbf95bb2fc.js +0 -1
  69. package/dist/dashboard/assets/next/static/chunks/app/v2/page-3905446ec0206fb5.js +0 -1
  70. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-3f5dbcdbf95bb2fc.js +0 -1
  71. package/dist/dashboard/assets/next/static/chunks/webpack-d20e6727e78cdbc8.js +0 -1
  72. package/dist/dashboard/assets/next/static/css/7263c178012081d9.css +0 -1
  73. package/dist/dashboard/assets/next/static/css/d5d08788c3435fdf.css +0 -1
  74. /package/dist/dashboard/assets/next/static/{JSI_XeT8MHbUAs8aF59pe → 5ub3D2yzS8DE7w2qZd1nv}/_buildManifest.js +0 -0
  75. /package/dist/dashboard/assets/next/static/{JSI_XeT8MHbUAs8aF59pe → 5ub3D2yzS8DE7w2qZd1nv}/_ssgManifest.js +0 -0
package/dist/worker.js CHANGED
@@ -9,6 +9,7 @@ import { spawn } from "child_process";
9
9
  // src/runtime/http-world.ts
10
10
  import { createServer } from "http";
11
11
  import { isDeepStrictEqual } from "util";
12
+ import { createHash as createHash5 } from "crypto";
12
13
  import { AsyncLocalStorage } from "async_hooks";
13
14
 
14
15
  // src/runtime/request-source.ts
@@ -119,9 +120,9 @@ function stripeOperation(method, path, params, data, sequence) {
119
120
  const match = /^\/v1\/(customers|payment_intents)(?:\/([^/]+))?(?:\/(confirm))?$/.exec(path);
120
121
  if (!match || !["GET", "POST"].includes(method)) return void 0;
121
122
  const [, resource, id, action] = match, collection = `/v1/${resource}`, rows2 = data[collection];
122
- const allowed = method === "GET" ? id ? [] : ["limit", "starting_after"] : resource === "customers" && !id ? ["email", "name", "description"] : resource === "payment_intents" && !id ? ["amount", "currency", "customer", "payment_method", "confirm"] : action === "confirm" ? ["payment_method"] : void 0;
123
+ 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;
123
124
  if (!allowed || resource === "customers" && action || resource === "payment_intents" && method === "GET" && !id) return void 0;
124
- if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
125
+ if (Object.keys(params).some((k) => !allowed.includes(k.replace(/\[.*$/, "")))) return void 0;
125
126
  if (method === "GET" && !id) {
126
127
  const limit = params.limit === void 0 ? 10 : Number(params.limit);
127
128
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...error(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
@@ -144,13 +145,28 @@ function stripeOperation(method, path, params, data, sequence) {
144
145
  row.last_payment_error = payment === "pm_card_chargeDeclined" ? { code: "card_declined", decline_code: "generic_decline", message: "Your card was declined." } : null;
145
146
  return { status: payment === "pm_card_chargeDeclined" ? 402 : 200, body: payment === "pm_card_chargeDeclined" ? { error: { type: "card_error", code: "card_declined", decline_code: "generic_decline", message: "Your card was declined.", payment_intent: structuredClone(row) } } : row, collection, record: structuredClone(row), operation: "write" };
146
147
  }
148
+ const form = Object.fromEntries(Object.entries(params).map(([k, v]) => [k, v])), nested = {};
149
+ for (const [key, value] of Object.entries(form)) {
150
+ const m = /^([^[]+)((?:\[[^\]]*\])+)$/.exec(key);
151
+ if (!m) {
152
+ nested[key] = value;
153
+ continue;
154
+ }
155
+ const path2 = [m[1], ...[...m[2].matchAll(/\[([^\]]*)\]/g)].map((x) => x[1])];
156
+ let cursor = nested;
157
+ for (const part of path2.slice(0, -1)) {
158
+ if (typeof cursor[part] !== "object" || cursor[part] === null) cursor[part] = {};
159
+ cursor = cursor[part];
160
+ }
161
+ cursor[path2.at(-1)] = value;
162
+ }
147
163
  const prefix = resource === "customers" ? "cus" : "pi";
148
164
  let suffix = sequence;
149
165
  while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
150
166
  const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: 17e8, livemode: false };
151
167
  if (resource === "customers") {
152
168
  if (params.email !== void 0 && typeof params.email !== "string") return { ...error(400, "parameter_invalid", "email must be a string", "email"), collection };
153
- Object.assign(created2, { email: null, name: null, description: null, ...params });
169
+ Object.assign(created2, { email: null, name: null, description: null, metadata: {}, ...nested });
154
170
  } else {
155
171
  const amount = Number(params.amount);
156
172
  if (!Number.isSafeInteger(amount) || amount < 1) return { ...error(400, "parameter_invalid_integer", "amount must be a positive integer", "amount"), collection };
@@ -163,6 +179,10 @@ function stripeOperation(method, path, params, data, sequence) {
163
179
  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 });
164
180
  }
165
181
  if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
182
+ if (resource === "payment_intents") {
183
+ for (const key of ["description", "receipt_email", "statement_descriptor", "capture_method"]) if (nested[key] !== void 0) created2[key] = nested[key];
184
+ }
185
+ if (resource === "payment_intents") created2.metadata = typeof nested.metadata === "object" && nested.metadata ? nested.metadata : {};
166
186
  rows2.push(created2);
167
187
  if (created2.status === "succeeded") chargeFor(created2, data, sequence);
168
188
  const declined = resource === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
@@ -170,7 +190,11 @@ function stripeOperation(method, path, params, data, sequence) {
170
190
  }
171
191
 
172
192
  // src/runtime/llm-adapter.ts
193
+ function hasToolResult(messages) {
194
+ return Array.isArray(messages) && messages.some((m) => !!m && typeof m === "object" && (m.role === "tool" || Array.isArray(m.content) && m.content.some((part) => !!part && typeof part === "object" && part.type === "tool_result")));
195
+ }
173
196
  function lastUserText(messages) {
197
+ if (typeof messages === "string") return messages;
174
198
  if (!Array.isArray(messages)) return "";
175
199
  const user = [...messages].reverse().find((m) => m && typeof m === "object" && m.role === "user");
176
200
  const content = user?.content;
@@ -178,10 +202,10 @@ function lastUserText(messages) {
178
202
  if (Array.isArray(content)) return content.map((part) => part && typeof part === "object" && typeof part.text === "string" ? part.text : "").join("\n");
179
203
  return "";
180
204
  }
181
- function nextScripted(data, prompt) {
205
+ function nextScripted(data, prompt, toolResult = false) {
182
206
  const scripts = data["/responses"];
183
207
  if (!scripts) return void 0;
184
- const usable = (row) => !row.used || row.repeat === true;
208
+ const usable = (row) => (!row.used || row.repeat === true) && (typeof row.afterToolResult !== "boolean" || row.afterToolResult === toolResult);
185
209
  const matched = scripts.find((row) => usable(row) && typeof row.match === "string" && prompt.includes(row.match));
186
210
  const script = matched ?? scripts.find((row) => usable(row) && row.match === void 0);
187
211
  if (!script) return void 0;
@@ -208,10 +232,11 @@ var arg = (value) => typeof value === "string" ? value : JSON.stringify(value ??
208
232
  function openaiOperation(method, path, params, _headers, data, sequence) {
209
233
  const collection = "/requests";
210
234
  if (path === "/v1/requests" || path === "/requests") return method === "GET" ? { status: 200, body: { object: "list", data: data[collection] }, collection, operation: "read" } : void 0;
235
+ if (method === "POST" && ["/v1/responses", "/responses"].includes(path)) return openaiResponsesOperation(params, data, sequence);
211
236
  if (method !== "POST" || !["/v1/chat/completions", "/chat/completions"].includes(path)) return void 0;
212
237
  if (params.stream === true || !Array.isArray(params.messages)) return void 0;
213
238
  const prompt = lastUserText(params.messages);
214
- const script = nextScripted(data, prompt);
239
+ const script = nextScripted(data, prompt, hasToolResult(params.messages));
215
240
  if (!script) return void 0;
216
241
  const id = `chatcmpl_at_${sequence}`;
217
242
  const toolCalls = script.calls.map((call, index) => ({ id: `call_at_${sequence}_${index}`, type: "function", function: { name: String(call.name), arguments: arg(call.arguments) } }));
@@ -227,13 +252,40 @@ function openaiOperation(method, path, params, _headers, data, sequence) {
227
252
  };
228
253
  return { status: 200, body, collection, record: entry, operation: "write" };
229
254
  }
255
+ function openaiResponsesOperation(params, data, sequence) {
256
+ const collection = "/requests";
257
+ if (params.stream === true || typeof params.input !== "string" && !Array.isArray(params.input)) return void 0;
258
+ const prompt = lastUserText(params.input);
259
+ const script = nextScripted(data, prompt);
260
+ if (!script) return void 0;
261
+ const id = `resp_at_${sequence}`;
262
+ const calls = script.calls.map((call, index) => ({ type: "function_call", id: `fc_at_${sequence}_${index}`, call_id: `call_at_${sequence}_${index}`, name: String(call.name), arguments: arg(call.arguments), status: "completed" }));
263
+ const entry = record(data, "openai", params.model, prompt, id, calls.map((call) => call.name));
264
+ if (!entry) return { status: 429, body: { error: { type: "world_capacity", message: "World record capacity reached" } }, collection };
265
+ const message = script.content !== null ? [{ type: "message", id: `msg_at_${sequence}`, role: "assistant", status: "completed", content: [{ type: "output_text", text: script.content, annotations: [] }] }] : [];
266
+ const body = {
267
+ id,
268
+ object: "response",
269
+ created_at: 17e8,
270
+ status: "completed",
271
+ model: params.model ?? "agenttwin-scripted",
272
+ error: null,
273
+ incomplete_details: null,
274
+ output: [...message, ...calls],
275
+ parallel_tool_calls: true,
276
+ tool_choice: params.tool_choice ?? "auto",
277
+ tools: Array.isArray(params.tools) ? params.tools : [],
278
+ usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } }
279
+ };
280
+ return { status: 200, body, collection, record: entry, operation: "write" };
281
+ }
230
282
  function anthropicOperation(method, path, params, _headers, data, sequence) {
231
283
  const collection = "/requests";
232
284
  if (path === "/v1/requests" || path === "/requests") return method === "GET" ? { status: 200, body: { data: data[collection] }, collection, operation: "read" } : void 0;
233
285
  if (method !== "POST" || !["/v1/messages", "/messages"].includes(path)) return void 0;
234
286
  if (params.stream === true || !Array.isArray(params.messages)) return void 0;
235
287
  const prompt = lastUserText(params.messages);
236
- const script = nextScripted(data, prompt);
288
+ const script = nextScripted(data, prompt, hasToolResult(params.messages));
237
289
  if (!script) return void 0;
238
290
  const id = `msg_at_${sequence}`;
239
291
  const toolUses = script.calls.map((call, index) => ({ type: "tool_use", id: `toolu_at_${sequence}_${index}`, name: String(call.name), input: parsedInput(call.arguments) }));
@@ -346,10 +398,10 @@ function parseGmailRaw(raw) {
346
398
  if (headers.some((h) => h.name.toLowerCase() === match[1].toLowerCase())) return { error: "Duplicate MIME headers are outside the verified subset", unsupported: true };
347
399
  headers.push({ name: match[1], value: match[2] });
348
400
  }
349
- const header = (name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
350
- if (!header("to")) return { error: "MIME To header is required", unsupported: false };
351
- if (header("content-type") && !/^text\/plain(?:\s*;\s*charset=(?:"?utf-8"?|"?us-ascii"?))?$/i.test(header("content-type"))) return { error: "Only text/plain UTF-8 MIME is supported", unsupported: true };
352
- if (header("content-transfer-encoding") && !/^(7bit|8bit)$/i.test(header("content-transfer-encoding"))) return { error: "Encoded MIME bodies are outside the verified subset", unsupported: true };
401
+ const header3 = (name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
402
+ if (!header3("to")) return { error: "MIME To header is required", unsupported: false };
403
+ 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 };
404
+ 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 };
353
405
  const text = mime.slice(boundary + 4);
354
406
  return { headers, text, encodedBody: Buffer.from(text).toString("base64url"), bytes: bytes.length };
355
407
  }
@@ -526,11 +578,11 @@ function linearOperation(method, path, params, _headers, data, sequence) {
526
578
  }
527
579
  if (root[1] === "issueCreate") {
528
580
  if (!isObject(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
529
- if (Object.keys(input).some((k) => !["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k))) return void 0;
581
+ 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;
530
582
  if (typeof input.title !== "string" || !input.title) return { status: 200, body: { data: null, errors: [{ message: "Issue title required" }] }, collection: "/issues" };
531
- 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, createdAt: iso(), updatedAt: iso() };
583
+ 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: iso(), updatedAt: iso() };
532
584
  rows(data, "/issues").push(issue);
533
- return write(200, "/issues", { data: { issueCreate: { success: true, issue: structuredClone(issue) } } }, issue);
585
+ return write(200, "/issues", { data: { issueCreate: { success: true, lastSyncId: sequence, issue: structuredClone(issue) } } }, issue);
534
586
  }
535
587
  if (root[1] === "issueUpdate") {
536
588
  if (!isObject(input) || arg2("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
@@ -696,7 +748,7 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
696
748
  return ok(collection, { total: rows(data, collection).length, results: page.map((r) => hubspotEnvelope(r)) });
697
749
  }
698
750
  if (method !== "POST") return void 0;
699
- if (Object.keys(params).some((k) => k !== "properties") || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: `Invalid input JSON on line 1: Unable to process JSON: properties required for ${object3}`, category: "VALIDATION_ERROR" });
751
+ if (Object.keys(params).some((k) => k !== "properties" && k !== "associations") || params.associations !== void 0 && !Array.isArray(params.associations) || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: `Invalid input JSON on line 1: Unable to process JSON: properties required for ${object3}`, category: "VALIDATION_ERROR" });
700
752
  const record3 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso(), updatedAt: iso() };
701
753
  rows(data, collection).push(record3);
702
754
  return created(collection, hubspotEnvelope(record3), record3);
@@ -894,7 +946,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
894
946
  if (!match) return void 0;
895
947
  const [, calendar, eventId] = match;
896
948
  if (calendar !== "primary") return googleError(EVENTS, 404, `Not Found: no twin state for calendar ${calendar}`);
897
- const scalar = (value) => ["summary", "description", "location"].filter((k) => params[k] !== void 0 && str(params[k]) === void 0);
949
+ const scalar2 = (value) => ["summary", "description", "location"].filter((k) => params[k] !== void 0 && str(params[k]) === void 0);
898
950
  const meetingField = (value) => value !== void 0 && !Array.isArray(value) && !isObject(value);
899
951
  if (!eventId) {
900
952
  if (method === "GET") {
@@ -935,7 +987,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
935
987
  if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
936
988
  if (typeof params.summary !== "string" || !params.summary) return fail(400, "Event summary is required.");
937
989
  if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
938
- const scalarBad = scalar(params);
990
+ const scalarBad = scalar2(params);
939
991
  if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
940
992
  const event2 = { id: detUuid(`gcal:${sequence}`), summary: params.summary, description: str(params.description) ?? null, location: str(params.location) ?? null, start: isObject(params.start) ? structuredClone(params.start) : { dateTime: iso() }, end: isObject(params.end) ? structuredClone(params.end) : { dateTime: iso() }, attendees: Array.isArray(params.attendees) ? structuredClone(params.attendees) : [], status: str(params.status) ?? "confirmed", htmlLink: null, creator: { email: "agenttwin@example.test", self: true }, created: iso(), updated: iso() };
941
993
  rowsIn(data, EVENTS).push(event2);
@@ -947,7 +999,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
947
999
  if (method === "PATCH") {
948
1000
  if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
949
1001
  if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
950
- const scalarBad = scalar(params);
1002
+ const scalarBad = scalar2(params);
951
1003
  if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
952
1004
  for (const [k, v] of Object.entries(params)) if (["summary", "description", "location", "start", "end", "attendees", "status"].includes(k)) event[k] = structuredClone(v);
953
1005
  event.updated = iso();
@@ -1136,7 +1188,7 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
1136
1188
  const collection = `/2010-04-01/${resource}`;
1137
1189
  const records = rowsIn(data, collection);
1138
1190
  const fail = (status, code, message) => ({ status, body: { status, code, message, more_info: "" }, collection });
1139
- const stamp = () => {
1191
+ const stamp2 = () => {
1140
1192
  const [date, time] = iso().split("T");
1141
1193
  return `${date} ${time.slice(0, 8)}`;
1142
1194
  };
@@ -1147,7 +1199,7 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
1147
1199
  if (missing.length) return fail(400, missing.length === allowed.length ? "21211" : "21606", `No parameter provided for ${allowed.filter((k) => missing.includes(k)).join(", ")}`);
1148
1200
  const prefix = resource === "Messages" ? "SM" : "CA";
1149
1201
  const sid = `${prefix}${sha(`${prefix.toLowerCase()}:${sequence}:${accountSid}`).slice(0, 32)}`;
1150
- const record2 = 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: stamp(), date_updated: stamp(), 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: stamp(), date_updated: stamp(), start_time: null, duration: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Calls/${sid}.json` };
1202
+ const record2 = 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` };
1151
1203
  records.push(record2);
1152
1204
  return created(collection, structuredClone(record2), record2);
1153
1205
  }
@@ -1300,6 +1352,7 @@ var SeedStream = class {
1300
1352
  var FAULT_SCHEDULE_WINDOW = 32;
1301
1353
  function faultOrdinals(selection, seed) {
1302
1354
  const count = selection.type === "timeout-after-write" ? 1 : selection.count ?? 1;
1355
+ if (selection.schedule === "first") return Array.from({ length: Math.min(count, FAULT_SCHEDULE_WINDOW) }, (_, i) => i);
1303
1356
  const stream = new SeedStream(seed, `fault:${selection.type}:${selection.service}:${selection.path}`);
1304
1357
  const all = Array.from({ length: FAULT_SCHEDULE_WINDOW }, (_, i) => i);
1305
1358
  for (let i = all.length - 1; i > 0; i--) {
@@ -1316,9 +1369,1474 @@ function validPostgresClock(value) {
1316
1369
  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;
1317
1370
  }
1318
1371
 
1372
+ // src/runtime/compiler/model.ts
1373
+ var tierLabel = (twin) => `${twin.tier} (${twin.fidelity}: ${twin.source.kind}${twin.source.license ? `, ${twin.source.license}` : ""})`;
1374
+ function fromPattern(pattern, stream) {
1375
+ let p = pattern.replace(/^\^/, "").replace(/\$$/, "");
1376
+ let out = "";
1377
+ const pick = (chars) => chars[stream.nextInt(chars.length)];
1378
+ const expand = (cls) => {
1379
+ let chars = "";
1380
+ for (let i = 0; i < cls.length; i++) {
1381
+ if (cls[i] === "\\" && cls[i + 1]) {
1382
+ const c = cls[++i];
1383
+ chars += c === "d" ? "0123456789" : c === "w" ? "abcdefghijklmnopqrstuvwxyz0123456789" : c;
1384
+ continue;
1385
+ }
1386
+ if (cls[i + 1] === "-" && cls[i + 2]) {
1387
+ for (let c = cls.charCodeAt(i); c <= cls.charCodeAt(i + 2); c++) chars += String.fromCharCode(c);
1388
+ i += 2;
1389
+ continue;
1390
+ }
1391
+ chars += cls[i];
1392
+ }
1393
+ return chars;
1394
+ };
1395
+ for (let guard = 0; p && guard < 200; guard++) {
1396
+ let chars;
1397
+ if (p[0] === "[") {
1398
+ const end = p.indexOf("]");
1399
+ if (end < 0) return;
1400
+ chars = expand(p.slice(1, end));
1401
+ p = p.slice(end + 1);
1402
+ } else if (p[0] === "\\") {
1403
+ const c = p[1];
1404
+ chars = c === "d" ? "0123456789" : c === "w" ? "abcdefghijklmnopqrstuvwxyz0123456789" : c === "-" || c === "." || c === "_" ? c : "";
1405
+ if (!chars) return;
1406
+ p = p.slice(2);
1407
+ } else if (p[0] === "(") {
1408
+ const end = p.indexOf(")");
1409
+ const options = p.slice(1, end).replace(/^\?:/, "").split("|");
1410
+ if (end < 0 || options.some((o) => !/^[A-Za-z0-9_-]*$/.test(o))) return;
1411
+ chars = "";
1412
+ p = p.slice(end + 1);
1413
+ if (p[0] === "?") {
1414
+ p = p.slice(1);
1415
+ continue;
1416
+ }
1417
+ out += options[stream.nextInt(options.length)];
1418
+ continue;
1419
+ } else if ("|?.".includes(p[0])) return;
1420
+ else {
1421
+ chars = p[0];
1422
+ p = p.slice(1);
1423
+ }
1424
+ let count = 1;
1425
+ const q = p.match(/^\{(\d+)(?:,(\d*))?\}|^[+*]/);
1426
+ if (q) {
1427
+ p = p.slice(q[0].length);
1428
+ count = q[0] === "+" ? 8 : q[0] === "*" ? 4 : q[2] !== void 0 ? Math.min(Number(q[2] || Number(q[1]) + 8), Number(q[1]) + 8) : Number(q[1]);
1429
+ if (q[1] && q[2] && Number(q[2]) > Number(q[1])) count = Number(q[1]) + stream.nextInt(Math.min(Number(q[2]), Number(q[1]) + 12) - Number(q[1]) + 1);
1430
+ }
1431
+ if (!chars.length) return;
1432
+ for (let i = 0; i < count; i++) out += pick(chars);
1433
+ }
1434
+ return p ? void 0 : out;
1435
+ }
1436
+ var FIRST = ["Avery", "Jordan", "Riley", "Morgan", "Casey", "Quinn", "Harper", "Rowan", "Emerson", "Sage"];
1437
+ var LAST = ["Chen", "Patel", "Okafor", "Silva", "Novak", "Haddad", "Larsen", "Moreau", "Kim", "Rossi"];
1438
+ var COMPANY = ["Northwind", "Globex", "Initech", "Umbrella Labs", "Acme Freight", "Vandelay", "Hooli", "Soylent", "Stark Supply", "Wayne Analytics"];
1439
+ var WORDS = ["renewal", "onboarding", "enterprise plan", "pilot", "expansion", "support", "quarterly review", "migration", "integration", "upgrade"];
1440
+ var twinClock = (sequence) => new Date(Date.UTC(2026, 0, 5, 9, 0, 0) + sequence * 6e4);
1441
+ function fakeValue(schema, name, stream, depth = 0, sequence = 0) {
1442
+ if (!schema) return void 0;
1443
+ if (schema.example !== void 0 && depth > 0 && typeof schema.example !== "object") return schema.example;
1444
+ if (schema.enum?.length) return schema.enum[stream.nextInt(schema.enum.length)];
1445
+ const n = name.toLowerCase().replace(/[^a-z0-9]/g, "");
1446
+ const type = schema.type ?? (schema.properties ? "object" : schema.items ? "array" : "string");
1447
+ if (type === "object") {
1448
+ if (depth > 3 || schema["x-recursive"]) return {};
1449
+ const out = {};
1450
+ for (const [key, child] of Object.entries(schema.properties ?? {})) {
1451
+ const v = fakeValue(child, key, stream, depth + 1, sequence);
1452
+ if (v !== void 0) out[key] = v;
1453
+ }
1454
+ return out;
1455
+ }
1456
+ if (type === "array") return depth > 2 || !schema.items ? [] : schema.items.type === "object" || schema.items.properties ? [] : [fakeValue(schema.items, name.replace(/s$/, ""), stream, depth + 1, sequence)];
1457
+ if (type === "boolean") return /^(is)?(deleted|archived|disabled|test)$/.test(n) ? false : stream.nextInt(2) === 1;
1458
+ if (type === "integer" || type === "number") {
1459
+ const min = schema.minimum ?? 0, max = schema.maximum ?? (/amount|price|total|cents/.test(n) ? 5e4 : /count|quantity|size|num/.test(n) ? 20 : /year/.test(n) ? 2026 : 1e3);
1460
+ if (/created|updated|timestamp|date|time/.test(n) && max > 1e6) return Math.floor(twinClock(sequence).getTime() / 1e3);
1461
+ const v = min + stream.nextInt(Math.max(1, Math.floor(max - min) + 1));
1462
+ return type === "number" && /rate|ratio|percent|score/.test(n) ? Math.round(stream.next() * 1e3) / 1e3 : v;
1463
+ }
1464
+ if (schema.pattern) {
1465
+ const v = fromPattern(schema.pattern, stream);
1466
+ if (v !== void 0) return v;
1467
+ }
1468
+ const f = schema.format ?? "";
1469
+ if (f === "date-time-rfc-2822") return twinClock(sequence).toUTCString();
1470
+ if (f === "date-time" || /_at$|At$|^date|date$|time$|timestamp/.test(name)) return f === "date" ? twinClock(sequence).toISOString().slice(0, 10) : twinClock(sequence).toISOString();
1471
+ if (/^num|count$|segments|quantity/.test(n)) return String(1 + stream.nextInt(3));
1472
+ if (/price|amount|cost|fee/.test(n)) return (stream.nextInt(1e4) / 100).toFixed(2);
1473
+ if (/^uri$|path$/.test(n)) return `/${n}/${stream.nextHex(6)}`;
1474
+ if (f === "date") return twinClock(sequence).toISOString().slice(0, 10);
1475
+ if (f === "email" || n.includes("email")) return `${FIRST[stream.nextInt(10)].toLowerCase()}.${LAST[stream.nextInt(10)].toLowerCase()}@example.com`;
1476
+ if (f === "uri" || f === "url" || /url$|uri$|link$|website|href/.test(n)) return `https://example.com/${n || "resource"}/${stream.nextHex(4)}`;
1477
+ if (f === "uuid") return `${stream.nextHex(4)}-${stream.nextHex(2)}-4${stream.nextHex(2).slice(1)}-a${stream.nextHex(2).slice(1)}-${stream.nextHex(6)}`;
1478
+ if (/phone|^to$|^from$|number/.test(n)) return `+1555${String(1e6 + stream.nextInt(8999999))}`;
1479
+ if (/firstname|givenname/.test(n)) return FIRST[stream.nextInt(10)];
1480
+ if (/lastname|surname|familyname/.test(n)) return LAST[stream.nextInt(10)];
1481
+ if (/company|organization|org|account(name)?$/.test(n)) return COMPANY[stream.nextInt(10)];
1482
+ if (/^name$|fullname|displayname|username/.test(n)) return `${FIRST[stream.nextInt(10)]} ${LAST[stream.nextInt(10)]}`;
1483
+ if (/currency/.test(n)) return "usd";
1484
+ if (/country/.test(n)) return "US";
1485
+ if (/status|state|stage/.test(n)) return "active";
1486
+ if (/^id$|id$|sid$|key$|token$/.test(n)) return `${n.replace(/id$|sid$|key$|token$/, "").slice(0, 4) || "id"}_${stream.nextHex(6)}`;
1487
+ if (/title|subject|summary|dealname|^name/.test(n)) return `${COMPANY[stream.nextInt(10)]} ${WORDS[stream.nextInt(10)]}`;
1488
+ if (/description|body|text|message|content|note|comment/.test(n)) return `Synthetic ${WORDS[stream.nextInt(10)]} note ${stream.nextHex(2)}`;
1489
+ const s = `${n || "value"}_${stream.nextHex(3)}`;
1490
+ return schema.maxLength && s.length > schema.maxLength ? s.slice(0, schema.maxLength) : s;
1491
+ }
1492
+ var streamFor = (seed, purpose) => new SeedStream(normalizeSeed(seed ?? "42"), purpose);
1493
+ var normName = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
1494
+ var singular = (s) => s.replace(/ies$/, "y").replace(/(sses|xes|ches|shes)$/, (m) => m.slice(0, -2)).replace(/([^s])s$/, "$1");
1495
+
1496
+ // src/runtime/compiler/engine.ts
1497
+ var HIDDEN = "__at_";
1498
+ var visible = (row) => {
1499
+ if (Array.isArray(row)) return row.map(visible);
1500
+ if (!row || typeof row !== "object") return row;
1501
+ const out = {};
1502
+ for (const [k, v] of Object.entries(row)) if (!k.startsWith(HIDDEN)) out[k] = visible(v);
1503
+ return out;
1504
+ };
1505
+ var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1506
+ var CREATED = /* @__PURE__ */ new Set(["createdat", "created", "datecreated", "createdtime", "createtime", "createdate", "insertedat", "creationdate", "createdon"]);
1507
+ var UPDATED = /* @__PURE__ */ new Set(["updatedat", "updated", "dateupdated", "lastmodified", "lastmodifieddate", "hslastmodifieddate", "modifiedat", "updatetime", "updatedtime", "lastupdated", "modifiedon", "updatedon"]);
1508
+ var stamp = (schema, sequence) => {
1509
+ const d = twinClock(sequence);
1510
+ return schema?.type === "integer" || schema?.type === "number" ? Math.floor(d.getTime() / 1e3) : schema?.format === "date-time-rfc-2822" ? d.toUTCString() : schema?.format === "date" ? d.toISOString().slice(0, 10) : d.toISOString();
1511
+ };
1512
+ function materialize(schema, mode, stream, sequence, name = "", depth = 0) {
1513
+ if (!schema) return mode === "seed" ? {} : void 0;
1514
+ if (mode === "seed") return fakeValue(schema, name, stream, depth, sequence);
1515
+ if (schema.default !== void 0) return structuredClone(schema.default);
1516
+ if (schema.enum?.length) return schema.enum[0];
1517
+ const type = schema.type ?? (schema.properties ? "object" : void 0);
1518
+ if (type === "object") {
1519
+ if (depth > 4 || schema["x-recursive"]) return {};
1520
+ const out = {};
1521
+ const all = !schema.required, required = new Set(schema.required ?? []);
1522
+ for (const [k, child] of Object.entries(schema.properties ?? {})) {
1523
+ const n = normName(k);
1524
+ if (CREATED.has(n) || UPDATED.has(n)) {
1525
+ out[k] = stamp(child, sequence);
1526
+ continue;
1527
+ }
1528
+ if (!all && !required.has(k) && child.default === void 0 && !(child.enum?.length === 1)) continue;
1529
+ if (child.nullable && !child.enum && child.type !== "object" && child.type !== "array" && !/^(id|sid|object|status|type)$/.test(n)) {
1530
+ out[k] = null;
1531
+ continue;
1532
+ }
1533
+ const v = materialize(child, mode, stream, sequence, k, depth + 1);
1534
+ if (v !== void 0) out[k] = v;
1535
+ }
1536
+ return out;
1537
+ }
1538
+ if (type === "array") return [];
1539
+ return fakeValue(schema, name, stream, depth, sequence);
1540
+ }
1541
+ var coerce = (value, schema) => {
1542
+ if (typeof value !== "string" || !schema) return value;
1543
+ if (schema.type === "integer" || schema.type === "number") {
1544
+ const n = Number(value);
1545
+ return Number.isFinite(n) ? n : value;
1546
+ }
1547
+ if (schema.type === "boolean") return value === "true" ? true : value === "false" ? false : value;
1548
+ return value;
1549
+ };
1550
+ function overlay(target, input, schema, merge) {
1551
+ const props = schema?.properties ?? {};
1552
+ for (const [k, v] of Object.entries(input)) {
1553
+ const key = Object.hasOwn(props, k) ? k : Object.keys(props).find((p) => normName(p) === normName(k)) ?? k;
1554
+ const child = props[key];
1555
+ if (isObj(v) && isObj(target[key]) && merge) {
1556
+ const next = structuredClone(target[key]);
1557
+ overlay(next, v, child, true);
1558
+ target[key] = next;
1559
+ } else target[key] = isObj(v) || Array.isArray(v) ? structuredClone(v) : coerce(v, child);
1560
+ }
1561
+ }
1562
+ function newId(resource, rows2, stream) {
1563
+ const s = resource.idSchema, taken = new Set(rows2.map((r) => String(r[resource.idField])));
1564
+ for (let i = 0; i < 50; i++) {
1565
+ let id;
1566
+ if (s?.type === "integer" || s?.type === "number") id = rows2.reduce((m, r) => Math.max(m, Number(r[resource.idField]) || 0), 1e3) + 1 + i;
1567
+ else if (s?.pattern) id = fromPattern(s.pattern, stream);
1568
+ if (id === void 0 && typeof s?.example === "string" && /^[A-Za-z]{1,8}_/.test(s.example)) id = s.example.split("_")[0] + "_" + stream.nextHex(12);
1569
+ if (id === void 0 && s?.format === "uuid") id = fakeValue(s, "id", stream);
1570
+ if (id === void 0 && typeof s?.example === "string" && /^\d+$/.test(s.example)) id = String(1e7 + stream.nextInt(89999999));
1571
+ id ??= `${singular(resource.name).replace(/[^a-z0-9]/gi, "").slice(0, 4).toLowerCase() || "obj"}_${stream.nextHex(10)}`;
1572
+ if (!taken.has(String(id))) return id;
1573
+ }
1574
+ return `${resource.name}_${stream.nextHex(16)}`;
1575
+ }
1576
+ var cache = /* @__PURE__ */ new WeakMap();
1577
+ function routes(twin) {
1578
+ let list2 = cache.get(twin);
1579
+ if (list2) return list2;
1580
+ list2 = twin.operations.map((op2) => {
1581
+ const names = [];
1582
+ let literal = 0;
1583
+ const source = op2.path.split("/").map((seg) => {
1584
+ if (!seg.includes("{")) {
1585
+ literal++;
1586
+ return seg.replace(/[.*+?^$()|[\]\\]/g, "\\$&");
1587
+ }
1588
+ return seg.split(/(\{[^}]+\})/).map((part) => {
1589
+ const m = part.match(/^\{([^}]+?)(\+)?\}$/);
1590
+ if (!m) return part.replace(/[.*+?^$()|[\]\\]/g, "\\$&");
1591
+ names.push(m[1]);
1592
+ return m[2] ? "(.+)" : "([^/]+?)";
1593
+ }).join("");
1594
+ }).join("/");
1595
+ return { op: op2, re: new RegExp(`^${source}/?$`), names, score: literal * 10 - names.length };
1596
+ }).sort((a, b) => b.score - a.score);
1597
+ cache.set(twin, list2);
1598
+ return list2;
1599
+ }
1600
+ function matchOperation(twin, method, path) {
1601
+ const candidates = [path];
1602
+ if (twin.basePath && path.startsWith(twin.basePath + "/")) candidates.push(path.slice(twin.basePath.length));
1603
+ for (const p of candidates) for (const r of routes(twin)) {
1604
+ if (r.op.method !== method) continue;
1605
+ const m = p.match(r.re);
1606
+ if (m) return { op: r.op, params: Object.fromEntries(r.names.map((n, i) => [n, decodeURIComponent(m[i + 1])])) };
1607
+ }
1608
+ return;
1609
+ }
1610
+ var pathKnown = (twin, path) => ["GET", "POST", "PUT", "PATCH", "DELETE"].some((m) => matchOperation(twin, m, path));
1611
+ var MESSAGE = /* @__PURE__ */ new Set(["message", "detail", "errordescription", "title", "description", "errormessage"]);
1612
+ var CODE = /* @__PURE__ */ new Set(["code", "errorcode", "errortype", "category"]);
1613
+ var STATUS = /* @__PURE__ */ new Set(["status", "statuscode", "httpstatus", "httpstatuscode"]);
1614
+ function errorBody(twin, op2, status, code, message, seed) {
1615
+ const documented = op2?.errors ?? [];
1616
+ const choice = documented.find((e) => e.status === status) ?? (status === 400 ? documented.find((e) => e.status === 422) : void 0) ?? documented.find((e) => e.schema && Math.floor(e.status / 100) === 4 && status < 500);
1617
+ const finalStatus = choice?.status && Math.floor(choice.status / 100) === Math.floor(status / 100) ? choice.status : status;
1618
+ if (!choice?.schema || choice.schema.type !== "object") return { status: finalStatus, body: { error: { code, message, status: finalStatus }, forwardedToProduction: false } };
1619
+ const body = materialize(choice.schema, "create", streamFor(seed, `error:${twin.id}`), 0);
1620
+ const fill = (node, schema, depth) => {
1621
+ for (const [k, s] of Object.entries(schema?.properties ?? {})) {
1622
+ const n = normName(k);
1623
+ if (MESSAGE.has(n) && (s.type ?? "string") === "string") node[k] = message;
1624
+ else if (CODE.has(n) && (s.type ?? "string") === "string" && !s.enum) node[k] = code;
1625
+ else if (CODE.has(n) && (s.type === "integer" || s.type === "number")) node[k] = finalStatus;
1626
+ else if (STATUS.has(n) && (s.type === "integer" || s.type === "number")) node[k] = finalStatus;
1627
+ else if (n === "error" && (s.type ?? "string") === "string") node[k] = code;
1628
+ else if (s.type === "object" && depth < 2 && /error/.test(n)) {
1629
+ node[k] = isObj(node[k]) ? node[k] : {};
1630
+ fill(node[k], s, depth + 1);
1631
+ } else if (s.type === "array" && s.items?.type === "object" && depth < 2 && /error/.test(n)) {
1632
+ const item = {};
1633
+ fill(item, s.items, depth + 1);
1634
+ node[k] = [item];
1635
+ }
1636
+ }
1637
+ };
1638
+ fill(body, choice.schema, 0);
1639
+ return { status: finalStatus, body };
1640
+ }
1641
+ var PAGE_SIZE = /^(limit|perpage|pagesize|maxresults|maxitems|top|size|first|count|maxkeys)$/;
1642
+ var CURSOR = /^(after|startingafter|cursor|pagetoken|nextpagetoken|offset|start|skip|page|marker|continuationtoken|nexttoken|startafter|startindex)$/;
1643
+ var resourceOf = (twin, op2) => twin.resources.find((r) => r.collection === op2.resource);
1644
+ var findRow = (rows2, resource, id) => rows2.findIndex((r) => String(r[resource.idField]) === id);
1645
+ var parentKey = (name) => HIDDEN + name;
1646
+ function inScope(row, resource, params, op2) {
1647
+ for (const p of op2.parentParams ?? []) {
1648
+ const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
1649
+ const value = row[parentKey(p)] ?? (field ? row[field] : void 0);
1650
+ if (value !== void 0 && String(value) !== params[p]) return false;
1651
+ }
1652
+ return true;
1653
+ }
1654
+ function withParents(row, resource, op2, params) {
1655
+ const out = visible(row);
1656
+ for (const p of op2.parentParams ?? []) {
1657
+ const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
1658
+ if (field && (out[field] === void 0 || out[field] === null)) out[field] = params[p];
1659
+ }
1660
+ return out;
1661
+ }
1662
+ function shape(op2, resource, record2, stream, sequence, params = {}) {
1663
+ const r = op2.response;
1664
+ const out = withParents(record2, resource, op2, params);
1665
+ 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;
1666
+ 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)));
1667
+ if (!holder) return out;
1668
+ const env = materialize(r, "create", stream, sequence);
1669
+ for (const [k, s] of Object.entries(r.properties)) if (normName(k) === "success" && s.type === "boolean") env[k] = true;
1670
+ env[holder[0]] = out;
1671
+ return env;
1672
+ }
1673
+ function listEnvelope(op2, page, info, stream, sequence) {
1674
+ const r = op2.response;
1675
+ if (!r || op2.listKey === "" || r.type === "array") return page;
1676
+ const env = materialize(r, "create", stream, sequence) ?? {};
1677
+ env[op2.listKey ?? "data"] = page;
1678
+ const walk = (node, schema, depth) => {
1679
+ for (const [k, s] of Object.entries(schema?.properties ?? {})) {
1680
+ const n = normName(k);
1681
+ if (k === op2.listKey && depth === 0) continue;
1682
+ if (["hasmore", "more", "istruncated", "hasnextpage"].includes(n)) node[k] = !!info.next;
1683
+ else if (["total", "totalcount", "totalresults", "totalsize", "resultsize"].includes(n) && (s.type === "integer" || s.type === "number")) node[k] = info.total;
1684
+ else if (["nextcursor", "nextpagetoken", "nexttoken", "endcursor", "after", "cursor", "nextcontinuationtoken", "nextmarker", "offset"].includes(n)) node[k] = info.next ?? (s.nullable ? null : n === "offset" ? 0 : "");
1685
+ else if (["nextpageuri", "nextpageurl", "next", "nextlink", "odatanextlink", "nexturl"].includes(n) && (s.type ?? "string") === "string") node[k] = info.nextUrl ?? null;
1686
+ else if (s.type === "object" && depth < 2 && /paging|pageinfo|meta|metadata|pagination|links|next|responsemetadata/.test(n)) {
1687
+ if (n === "next" && !info.next) {
1688
+ delete node[k];
1689
+ continue;
1690
+ }
1691
+ node[k] = isObj(node[k]) ? node[k] : {};
1692
+ walk(node[k], s, depth + 1);
1693
+ }
1694
+ }
1695
+ };
1696
+ walk(env, r, 0);
1697
+ return env;
1698
+ }
1699
+ function handleRest(twin, req, data, ctx) {
1700
+ const match = matchOperation(twin, req.method, req.path);
1701
+ if (!match || !match.op.supported) return void 0;
1702
+ const { op: op2, params } = match, resource = resourceOf(twin, op2), collection = resource.collection;
1703
+ const rows2 = data[collection] ??= [];
1704
+ const stream = streamFor(ctx.seed, `${twin.id}:${collection}:${ctx.sequence}`);
1705
+ const fail = (status, code, message) => {
1706
+ const e = errorBody(twin, op2, status, code, message, ctx.seed);
1707
+ return { status: e.status, body: e.body, collection };
1708
+ };
1709
+ const authNames = new Set(twin.auth.filter((a) => a.type === "api-key").map((a) => normName(a.name ?? "")));
1710
+ for (const p of op2.params) if (p.in === "query" && p.required && !authNames.has(normName(p.name)) && req.query[p.name] === void 0) return fail(400, "parameter_missing", `Missing required query parameter: ${p.name}`);
1711
+ const body = req.body ?? {};
1712
+ const writes = ["create", "update", "replace", "upsert", "action"].includes(op2.kind) || op2.kind === "singleton" && req.method !== "GET";
1713
+ if (writes && op2.body && op2.bodyEncoding !== "raw") {
1714
+ if (op2.bodyRequired && !Object.keys(body).length && op2.kind !== "action") return fail(400, "body_missing", "Request body is required");
1715
+ const props = op2.body.properties ?? {};
1716
+ for (const name of op2.body.required ?? []) if (body[name] === void 0 && !(op2.kind === "update" && req.method === "PATCH" && !op2.bodyRequired) && !Object.keys(body).some((k) => normName(k) === normName(name))) return fail(400, "parameter_missing", `Missing required field: ${name}`);
1717
+ if (op2.bodyEncoding === "json") for (const [k, v] of Object.entries(body)) {
1718
+ const s = props[k];
1719
+ if (!s || v === null && s.nullable) continue;
1720
+ const t = s.type, ok2 = !t || t === "string" && typeof v === "string" || (t === "integer" || t === "number") && typeof v === "number" || t === "boolean" && typeof v === "boolean" || t === "object" && isObj(v) || t === "array" && Array.isArray(v);
1721
+ if (!ok2) return fail(400, "invalid_type", `Field ${k} must be ${t}`);
1722
+ if (s.enum && typeof v === "string" && !s.enum.includes(v)) return fail(400, "invalid_value", `Field ${k} must be one of ${s.enum.slice(0, 10).join(", ")}`);
1723
+ }
1724
+ }
1725
+ const id = op2.idParam ? params[op2.idParam] : void 0;
1726
+ const scoped = rows2.filter((r) => inScope(r, resource, params, op2));
1727
+ if (op2.kind === "list") {
1728
+ const filters = [];
1729
+ let size = 20, cursor, cursorName = "";
1730
+ for (const p of op2.params.filter((p2) => p2.in === "query")) {
1731
+ const n = normName(p.name), v = req.query[p.name];
1732
+ if (PAGE_SIZE.test(n) && (p.schema?.type === "integer" || p.schema?.type === "number" || n !== "count")) {
1733
+ const d = Number(v ?? p.schema?.default ?? 20);
1734
+ size = Math.max(1, Math.min(Number.isFinite(d) ? d : 20, p.schema?.maximum ?? 1e3));
1735
+ continue;
1736
+ }
1737
+ if (CURSOR.test(n)) {
1738
+ if (v !== void 0) {
1739
+ cursor = v;
1740
+ cursorName = n;
1741
+ } else cursorName ||= n;
1742
+ continue;
1743
+ }
1744
+ if (v !== void 0) filters.push([p.name, v]);
1745
+ }
1746
+ const matches2 = scoped.filter((r) => filters.every(([k, v]) => {
1747
+ const field = Object.keys(r).find((f) => normName(f) === normName(k));
1748
+ const value = field !== void 0 ? r[field] : isObj(r.properties) ? r.properties[k] : void 0;
1749
+ return value === void 0 || String(value) === v;
1750
+ }));
1751
+ let start = 0;
1752
+ if (cursor !== void 0) {
1753
+ const i = matches2.findIndex((r) => String(r[resource.idField]) === cursor);
1754
+ start = i >= 0 ? i + 1 : cursorName === "page" ? Math.max(0, (Number(cursor) - 1) * size) : Number.isFinite(Number(cursor)) ? Number(cursor) : 0;
1755
+ }
1756
+ const page = matches2.slice(start, start + size).map((r) => withParents(r, resource, op2, params));
1757
+ const more = start + size < matches2.length;
1758
+ const next2 = more ? cursorName === "startingafter" ? String(page[page.length - 1][resource.idField]) : String(start + size) : void 0;
1759
+ const nextUrl = next2 ? `${req.path}?${new URLSearchParams({ ...req.query, [op2.params.find((p) => normName(p.name) === cursorName)?.name ?? "after"]: next2 })}` : void 0;
1760
+ return { status: op2.status, body: listEnvelope(op2, page, { total: matches2.length, ...next2 ? { next: next2 } : {}, ...nextUrl ? { nextUrl } : {} }, stream, ctx.sequence), collection, operation: "read" };
1761
+ }
1762
+ if (op2.kind === "singleton") {
1763
+ if (req.method === "GET") {
1764
+ const row3 = scoped[0] ?? materialize(resource.schema ?? op2.response, "seed", streamFor(ctx.seed, `singleton:${twin.id}:${collection}`), 0);
1765
+ if (!scoped.length && isObj(row3)) rows2.push(row3);
1766
+ return { status: op2.status, body: visible(row3), collection, operation: "read" };
1767
+ }
1768
+ if (req.method === "DELETE") {
1769
+ rows2.length = 0;
1770
+ return { status: op2.status === 200 && !op2.response ? 204 : op2.status, body: op2.response ? {} : null, collection, operation: "write", record: {} };
1771
+ }
1772
+ const row2 = scoped[0] ?? {};
1773
+ overlay(row2, body, op2.body, true);
1774
+ if (!scoped.length) rows2.push(row2);
1775
+ return { status: op2.status, body: visible(row2), collection, operation: "write", record: row2 };
1776
+ }
1777
+ if (op2.kind === "create" || op2.kind === "upsert" && findRow(scoped, resource, id) < 0) {
1778
+ if (rows2.length >= 1e4) return fail(429, "capacity", "Twin collection is full");
1779
+ const record2 = materialize(resource.schema ?? op2.response, "create", stream, ctx.sequence) ?? {};
1780
+ overlay(record2, body, resource.schema, true);
1781
+ const supplied = Object.keys(body).find((k) => normName(k) === normName(resource.idField));
1782
+ if (id !== void 0) record2[resource.idField] = id;
1783
+ else if (!supplied) record2[resource.idField] = newId(resource, rows2, stream);
1784
+ else if (findRow(scoped, resource, String(record2[resource.idField])) >= 0) return fail(409, "conflict", `${resource.name} ${record2[resource.idField]} already exists`);
1785
+ for (const p of op2.parentParams ?? []) {
1786
+ const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
1787
+ if (field && record2[field] === void 0) record2[field] = params[p];
1788
+ else if (!field) record2[parentKey(p)] = params[p];
1789
+ }
1790
+ rows2.push(record2);
1791
+ return { status: op2.kind === "upsert" ? op2.status || 200 : op2.status, body: shape(op2, resource, record2, stream, ctx.sequence, params), collection, operation: "write", record: visible(record2) };
1792
+ }
1793
+ const index = rows2.findIndex((r) => String(r[resource.idField]) === id && inScope(r, resource, params, op2));
1794
+ if (index < 0) return { ...fail(404, "not_found", `No such ${singular(resource.name)}: ${id}`), operation: "read" };
1795
+ const row = rows2[index];
1796
+ if (op2.kind === "read") return { status: op2.status, body: shape(op2, resource, row, stream, ctx.sequence, params), collection, operation: "read" };
1797
+ if (op2.kind === "delete") {
1798
+ rows2.splice(index, 1);
1799
+ const props = op2.response?.properties;
1800
+ 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;
1801
+ return { status: reply ? op2.status : op2.status === 200 ? 204 : op2.status, body: reply, collection, operation: "write", record: visible(row) };
1802
+ }
1803
+ if (op2.kind === "action") {
1804
+ const verb = normName(op2.path.split("/").pop() ?? "");
1805
+ const status = Object.entries(resource.schema?.properties ?? {}).find(([k]) => /^(status|state)$/i.test(k));
1806
+ 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"));
1807
+ if (status && target !== void 0) row[status[0]] = target;
1808
+ overlay(row, body, resource.schema, true);
1809
+ for (const [k, s] of Object.entries(resource.schema?.properties ?? {})) if (UPDATED.has(normName(k))) row[k] = stamp(s, ctx.sequence);
1810
+ return { status: op2.status, body: shape(op2, resource, row, stream, ctx.sequence, params), collection, operation: "write", record: visible(row) };
1811
+ }
1812
+ 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);
1813
+ overlay(next, body, resource.schema, op2.kind === "update");
1814
+ next[resource.idField] = row[resource.idField];
1815
+ for (const [k, s] of Object.entries(resource.schema?.properties ?? {})) if (UPDATED.has(normName(k))) next[k] = stamp(s, ctx.sequence);
1816
+ rows2[index] = next;
1817
+ return { status: op2.status === 201 ? 200 : op2.status, body: shape(op2, resource, next, stream, ctx.sequence, params), collection, operation: "write", record: visible(next) };
1818
+ }
1819
+
1820
+ // src/runtime/compiler/adapters.ts
1821
+ var twins = /* @__PURE__ */ new Map();
1822
+ var protocolHandlers = /* @__PURE__ */ new Map([["rest", handleRest]]);
1823
+ var isGeneratedAdapter = (adapter) => typeof adapter === "string" && adapter.startsWith("generated:") && twins.has(adapter);
1824
+ var header = (h, name) => {
1825
+ const v = h[name.toLowerCase()];
1826
+ return Array.isArray(v) ? v[0] : v;
1827
+ };
1828
+ function twinAuth(twin, headers, url, token) {
1829
+ const authorization = header(headers, "authorization") ?? "";
1830
+ for (const scheme of twin.auth) {
1831
+ if ((scheme.type === "bearer" || scheme.type === "oauth2") && authorization === `Bearer ${token}`) return true;
1832
+ if (scheme.type === "basic" && /^Basic /i.test(authorization)) {
1833
+ const [user, ...rest] = Buffer.from(authorization.slice(6), "base64").toString("utf8").split(":");
1834
+ if (user === token || rest.join(":") === token) return true;
1835
+ }
1836
+ if (scheme.type === "api-key" && scheme.name) {
1837
+ if (scheme.in === "query" && new URL(url, "http://localhost").searchParams.get(scheme.name) === token) return true;
1838
+ if (scheme.in !== "query" && (header(headers, scheme.name) === token || header(headers, scheme.name) === `Bearer ${token}`)) return true;
1839
+ }
1840
+ if (scheme.type === "sigv4" && new RegExp(`Credential=${token.replace(/[^a-zA-Z0-9_]/g, "")}/`).test(authorization)) return true;
1841
+ if (scheme.type === "none") return true;
1842
+ }
1843
+ return false;
1844
+ }
1845
+ function generatedAdapter(adapter) {
1846
+ const twin = adapter ? twins.get(adapter) : void 0;
1847
+ if (!twin) return;
1848
+ const handler = protocolHandlers.get(twin.protocol);
1849
+ return {
1850
+ twin,
1851
+ handle: (req, data, sequence, seed) => handler ? handler(twin, req, data, { seed, sequence }) : void 0,
1852
+ auth: (headers, url, token) => twinAuth(twin, headers, url, token),
1853
+ unsupported: (method, path) => ({ error: { code: "unsupported_operation", message: twin.protocol === "rest" && pathKnown(twin, path) ? `${method} ${path} is in the ${twin.title} description but this generated twin does not serve it` : `${method} ${path} is not in the ${twin.title} description this twin was compiled from`, twin: twin.id, tier: tierLabel(twin) }, forwardedToProduction: false }),
1854
+ collectionOf: (method, path) => twin.protocol === "rest" ? (() => {
1855
+ const m = matchOperation(twin, method, path);
1856
+ return m ? m.op.resource : void 0;
1857
+ })() : void 0,
1858
+ bodyMode: (contentType) => {
1859
+ const t = (contentType ?? "").toLowerCase();
1860
+ return /json/.test(t) ? "json" : /x-www-form-urlencoded/.test(t) ? "form" : twin.protocol === "graphql" ? "json" : t || twin.protocol.startsWith("aws-rest") ? "raw" : "json";
1861
+ }
1862
+ };
1863
+ }
1864
+
1865
+ // src/runtime/enterprise-twins.ts
1866
+ import { createHash as createHash4 } from "crypto";
1867
+ var ENTERPRISE_ADAPTERS = ["salesforce", "servicenow", "workday", "sap", "microsoft-teams", "outlook", "entra-id", "okta", "confluence", "sharepoint", "snowflake", "netsuite", "pagerduty"];
1868
+ var isEnterpriseAdapter = (name) => ENTERPRISE_ADAPTERS.includes(name);
1869
+ var EPOCH2 = 17e8;
1870
+ var iso2 = (sequence) => new Date((EPOCH2 + sequence) * 1e3).toISOString();
1871
+ var hash = (seed) => createHash4("sha256").update(seed).digest("hex");
1872
+ var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1873
+ var scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
1874
+ var flat = (v) => Object.values(v).every(scalar);
1875
+ var read = (collection, body, status = 200, headers) => ({ status, body, collection, operation: "read", ...headers ? { headers } : {} });
1876
+ var write2 = (collection, record2, body, status = 200, headers) => ({ status, body, collection, record: structuredClone(record2), operation: "write", ...headers ? { headers } : {} });
1877
+ var table = (data, collection) => data[collection] ??= [];
1878
+ var limitOf = (value, fallback, max) => {
1879
+ if (value === void 0) return fallback;
1880
+ const n = Number(value);
1881
+ return Number.isInteger(n) && n >= 1 && n <= max ? n : null;
1882
+ };
1883
+ var nextNumber = (rows2, key, start) => rows2.reduce((max, r) => Math.max(max, Number(String(r[key] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
1884
+ var header2 = (headers, name) => {
1885
+ const v = headers[name];
1886
+ return Array.isArray(v) ? v[0] : v;
1887
+ };
1888
+ function eqFilter(expression, quote) {
1889
+ const parts = expression.split(/\s+and\s+/i), tests = [];
1890
+ for (const part of parts) {
1891
+ const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote}([^${quote}]*)${quote}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
1892
+ if (!m) return null;
1893
+ const value = m[2] !== void 0 ? m[2] : m[3] === "null" ? null : m[3] === "true" ? true : m[3] === "false" ? false : Number(m[3]);
1894
+ tests.push((r) => {
1895
+ const actual = m[1].split(".").reduce((v, k) => v?.[k], r);
1896
+ return actual === value || typeof value === "number" && String(actual) === String(value);
1897
+ });
1898
+ }
1899
+ return (r) => tests.every((t) => t(r));
1900
+ }
1901
+ var SF_OBJECTS = {
1902
+ Account: { prefix: "001", required: ["Name"] },
1903
+ Contact: { prefix: "003", required: ["LastName"] },
1904
+ Lead: { prefix: "00Q", required: ["LastName", "Company"] },
1905
+ Opportunity: { prefix: "006", required: ["Name", "StageName", "CloseDate"] },
1906
+ Case: { prefix: "500", required: [] }
1907
+ };
1908
+ var sfError = (status, errorCode, message, fields = []) => ({ status, body: [{ message, errorCode, fields }] });
1909
+ var sfView = (object3, version, r, fields) => {
1910
+ const pick = fields ? Object.fromEntries(fields.map((f) => [Object.keys(r).find((k) => k.toLowerCase() === f.toLowerCase()) ?? f, r[Object.keys(r).find((k) => k.toLowerCase() === f.toLowerCase()) ?? f] ?? null])) : r;
1911
+ return { attributes: { type: object3, url: `/services/data/${version}/sobjects/${object3}/${r.Id}` }, ...pick };
1912
+ };
1913
+ function soql(q) {
1914
+ const m = /^\s*SELECT\s+(.+?)\s+FROM\s+(\w+)(?:\s+WHERE\s+(.+?))?(?:\s+LIMIT\s+(\d+))?\s*$/i.exec(q);
1915
+ if (!m || /\(|\bORDER\b|\bGROUP\b|\bOR\b|\bLIKE\b|\bIN\b/i.test(m[1] + " " + (m[3] ?? ""))) return null;
1916
+ const tests = [];
1917
+ for (const cond of m[3] ? m[3].split(/\s+AND\s+/i) : []) {
1918
+ const c = /^\s*(\w+)\s*(=|!=)\s*(?:'((?:[^'\\]|\\.)*)'|(true|false|null|-?\d+(?:\.\d+)?))\s*$/i.exec(cond);
1919
+ if (!c) return null;
1920
+ const value = c[3] !== void 0 ? c[3].replace(/\\(.)/g, "$1") : c[4].toLowerCase() === "null" ? null : /^(true|false)$/i.test(c[4]) ? c[4].toLowerCase() === "true" : Number(c[4]);
1921
+ const field = c[1].toLowerCase();
1922
+ tests.push((r) => {
1923
+ const k = Object.keys(r).find((key) => key.toLowerCase() === field);
1924
+ const equal = (k ? r[k] : null) === value;
1925
+ return c[2] === "=" ? equal : !equal;
1926
+ });
1927
+ }
1928
+ return { fields: m[1].split(",").map((f) => f.trim()).filter(Boolean), object: m[2], where: (r) => tests.every((t) => t(r)), limit: m[4] ? Number(m[4]) : void 0 };
1929
+ }
1930
+ var salesforce = (method, path, body, query, _headers, data, sequence) => {
1931
+ const m = /^\/services\/data\/(v\d+\.\d)\/(.+)$/.exec(path);
1932
+ if (!m) return;
1933
+ const [, version, rest] = m;
1934
+ if (rest === "query" && method === "GET") {
1935
+ const parsed = typeof query.q === "string" ? soql(query.q) : null;
1936
+ if (!parsed) return;
1937
+ const name = Object.keys(SF_OBJECTS).find((o) => o.toLowerCase() === parsed.object.toLowerCase());
1938
+ if (!name) return { ...sfError(400, "INVALID_TYPE", `sObject type '${parsed.object}' is not supported.`), collection: "/sobjects" };
1939
+ const records = table(data, `/sobjects/${name}`).filter(parsed.where).slice(0, parsed.limit ?? 2e3);
1940
+ return read(`/sobjects/${name}`, { totalSize: records.length, done: true, records: records.map((r) => sfView(name, version, r, parsed.fields)) });
1941
+ }
1942
+ const s = /^sobjects\/(\w+)(?:\/(\w{15,18}))?$/.exec(rest);
1943
+ if (!s) return;
1944
+ const object3 = s[1], spec = SF_OBJECTS[object3], collection = `/sobjects/${object3}`;
1945
+ if (!spec) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
1946
+ const rows2 = table(data, collection);
1947
+ if (!s[2] && method === "POST") {
1948
+ if (!flat(body)) return;
1949
+ const missing = spec.required.filter((f) => body[f] === void 0 || body[f] === null || body[f] === "");
1950
+ if (missing.length) return { ...sfError(400, "REQUIRED_FIELD_MISSING", `Required fields are missing: [${missing.join(", ")}]`, missing), collection };
1951
+ const id = (spec.prefix + hash(`salesforce:${object3}:${sequence}:${rows2.length}`).slice(0, 12)).toUpperCase().replace(/^00Q/i, "00Q") + "AAA";
1952
+ const record3 = { Id: id, ...body, CreatedDate: iso2(sequence), LastModifiedDate: iso2(sequence), IsDeleted: false };
1953
+ rows2.push(record3);
1954
+ return write2(collection, record3, { id, success: true, errors: [] }, 201);
1955
+ }
1956
+ if (!s[2]) return;
1957
+ const record2 = rows2.find((r) => r.Id === s[2] || String(r.Id).slice(0, 15) === s[2].slice(0, 15));
1958
+ if (!record2) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
1959
+ if (method === "GET") return read(collection, sfView(object3, version, record2));
1960
+ if (method === "PATCH") {
1961
+ if (!flat(body) || "Id" in body) return;
1962
+ Object.assign(record2, body, { LastModifiedDate: iso2(sequence) });
1963
+ return write2(collection, record2, null, 204);
1964
+ }
1965
+ if (method === "DELETE") {
1966
+ rows2.splice(rows2.indexOf(record2), 1);
1967
+ return write2(collection, { ...record2, IsDeleted: true }, null, 204);
1968
+ }
1969
+ };
1970
+ var SN_TABLES = { incident: "INC", change_request: "CHG", problem: "PRB", sc_request: "REQ", sys_user: null };
1971
+ var snTime = (sequence) => iso2(sequence).replace("T", " ").slice(0, 19);
1972
+ var snError = (status, message, detail) => ({ status, body: { error: { message, detail }, status: "failure" } });
1973
+ var servicenow = (method, path, body, query, _headers, data, sequence) => {
1974
+ const m = /^\/api\/now\/(?:v\d\/)?table\/(\w+)(?:\/([0-9a-f]{32}))?$/.exec(path);
1975
+ if (!m) return;
1976
+ const [, name, sysId] = m, collection = `/${name}`;
1977
+ if (!(name in SN_TABLES)) return { ...snError(400, "Invalid table", `Invalid table ${name}`), collection };
1978
+ const rows2 = table(data, collection);
1979
+ if (!sysId && method === "GET") {
1980
+ const limit = limitOf(query.sysparm_limit, 1e4, 1e4), offset = Number(query.sysparm_offset ?? 0);
1981
+ if (limit === null || !Number.isInteger(offset) || offset < 0) return;
1982
+ const tests = [];
1983
+ for (const clause of query.sysparm_query ? query.sysparm_query.split("^") : []) {
1984
+ const c = /^(\w+)(!=|=)(.*)$/.exec(clause);
1985
+ if (!c || /^(OR|NQ|ORDERBY)/.test(clause)) return;
1986
+ tests.push((r) => String(r[c[1]] ?? "") === c[3] === (c[2] === "="));
1987
+ }
1988
+ const matched = rows2.filter((r) => tests.every((t) => t(r)));
1989
+ const fields = query.sysparm_fields?.split(",").map((f) => f.trim());
1990
+ const page = matched.slice(offset, offset + limit).map((r) => fields ? Object.fromEntries(fields.map((f) => [f, r[f] ?? ""])) : r);
1991
+ return read(collection, { result: page }, 200, { "x-total-count": String(matched.length) });
1992
+ }
1993
+ if (!sysId && method === "POST") {
1994
+ if (!flat(body) || "sys_id" in body) return;
1995
+ const prefix = SN_TABLES[name];
1996
+ const record3 = {
1997
+ sys_id: hash(`servicenow:${name}:${sequence}:${rows2.length}`).slice(0, 32),
1998
+ ...prefix ? { number: `${prefix}${String(nextNumber(rows2, "number", 10001)).padStart(7, "0")}` } : {},
1999
+ ...name === "incident" ? { state: "1", impact: "3", urgency: "3", priority: "5" } : {},
2000
+ ...Object.fromEntries(Object.entries(body).map(([k, v]) => [k, v === null ? "" : String(v)])),
2001
+ sys_created_on: snTime(sequence),
2002
+ sys_updated_on: snTime(sequence),
2003
+ sys_mod_count: "0"
2004
+ };
2005
+ rows2.push(record3);
2006
+ return write2(collection, record3, { result: record3 }, 201);
2007
+ }
2008
+ if (!sysId) return;
2009
+ const record2 = rows2.find((r) => r.sys_id === sysId);
2010
+ if (!record2) return { ...snError(404, "No Record found", "Record doesn't exist or ACL restricts the record retrieval"), collection };
2011
+ if (method === "GET") return read(collection, { result: record2 });
2012
+ if (method === "PATCH" || method === "PUT") {
2013
+ if (!flat(body) || "sys_id" in body || "number" in body) return;
2014
+ Object.assign(record2, Object.fromEntries(Object.entries(body).map(([k, v]) => [k, v === null ? "" : String(v)])), { sys_updated_on: snTime(sequence), sys_mod_count: String(Number(record2.sys_mod_count ?? 0) + 1) });
2015
+ return write2(collection, record2, { result: record2 });
2016
+ }
2017
+ if (method === "DELETE") {
2018
+ rows2.splice(rows2.indexOf(record2), 1);
2019
+ return write2(collection, record2, null, 204);
2020
+ }
2021
+ };
2022
+ var wdError = (status, error, errors = []) => ({ status, body: { error, errors } });
2023
+ var workday = (method, path, body, query, _headers, data, sequence) => {
2024
+ const m = /^\/ccx\/api\/(?:v1|staffing\/v\d+|absenceManagement\/v\d+)\/([\w-]+)\/workers(?:\/([\w-]+))?(?:\/(requestTimeOff|timeOffDetails))?$/.exec(path);
2025
+ if (!m) return;
2026
+ const [, , workerId, action] = m, workers = table(data, "/workers"), requests = table(data, "/timeOffRequests");
2027
+ if (!workerId && method === "GET") {
2028
+ const limit = limitOf(query.limit, 20, 100), offset = Number(query.offset ?? 0);
2029
+ if (limit === null || !Number.isInteger(offset) || offset < 0) return;
2030
+ const search = query.search?.toLowerCase();
2031
+ const matched = workers.filter((w) => !search || String(w.descriptor ?? "").toLowerCase().includes(search) || String(w.primaryWorkEmail ?? "").toLowerCase() === search);
2032
+ return read("/workers", { total: matched.length, data: matched.slice(offset, offset + limit) });
2033
+ }
2034
+ const worker = workers.find((w) => w.id === workerId);
2035
+ if (!worker) return { ...wdError(404, "Resource not found", [{ error: `Invalid ID value. '${workerId}' is not a valid ID value for type = WID`, field: "ID" }]), collection: "/workers" };
2036
+ if (!action && method === "GET") return read("/workers", worker);
2037
+ if (action === "timeOffDetails" && method === "GET") {
2038
+ const own = requests.filter((r) => r.worker?.id === workerId);
2039
+ return read("/timeOffRequests", { total: own.length, data: own });
2040
+ }
2041
+ if (action === "requestTimeOff" && method === "POST") {
2042
+ const days = body.days;
2043
+ if (!Array.isArray(days) || !days.length || !days.every((d) => isObject2(d) && /^\d{4}-\d{2}-\d{2}$/.test(String(d.date)) && isObject2(d.timeOffType) && typeof d.timeOffType.id === "string"))
2044
+ return { ...wdError(400, "Validation error", [{ error: "Each day requires a date (YYYY-MM-DD) and a timeOffType id", field: "days" }]), collection: "/timeOffRequests" };
2045
+ const taken = new Set(requests.filter((r) => r.worker?.id === workerId && r.status !== "Canceled").flatMap((r) => r.days.map((d) => d.date)));
2046
+ const clash = days.find((d) => taken.has(d.date));
2047
+ if (clash) return { ...wdError(400, "Validation error", [{ error: `Time off has already been requested for ${clash.date}.`, field: "days" }]), collection: "/timeOffRequests" };
2048
+ const record2 = {
2049
+ id: hash(`workday:timeoff:${sequence}:${requests.length}`).slice(0, 32),
2050
+ descriptor: `Time Off Request: ${worker.descriptor}`,
2051
+ worker: { id: workerId, descriptor: worker.descriptor },
2052
+ days: days.map((d) => ({ date: d.date, dailyQuantity: Number(d.dailyQuantity ?? 8), timeOffType: { id: d.timeOffType.id } })),
2053
+ status: "Submitted",
2054
+ businessProcessParameters: { overallStatus: "In Progress", comment: isObject2(body.businessProcessParameters) ? body.businessProcessParameters.comment ?? null : null },
2055
+ createdOn: iso2(sequence)
2056
+ };
2057
+ requests.push(record2);
2058
+ return write2("/timeOffRequests", record2, record2, 201);
2059
+ }
2060
+ };
2061
+ var SAP_SETS = { A_BusinessPartner: { service: "API_BUSINESS_PARTNER", key: "BusinessPartner" }, A_SalesOrder: { service: "API_SALES_ORDER_SRV", key: "SalesOrder" } };
2062
+ var sapError = (status, code, value, headers) => ({ status, body: { error: { code, message: { lang: "en", value } } }, ...headers ? { headers } : {} });
2063
+ var sapView = (set, r) => ({ __metadata: { id: `/sap/opu/odata/sap/${SAP_SETS[set].service}/${set}('${r[SAP_SETS[set].key]}')`, uri: `/sap/opu/odata/sap/${SAP_SETS[set].service}/${set}('${r[SAP_SETS[set].key]}')`, type: `${SAP_SETS[set].service}.${set}Type` }, ...r });
2064
+ var sap = (method, path, body, query, headers, data, sequence) => {
2065
+ const m = /^\/sap\/opu\/odata\/sap\/(API_BUSINESS_PARTNER|API_SALES_ORDER_SRV)\/(A_BusinessPartner|A_SalesOrder)(?:\('([^']{1,20})'\))?$/.exec(path);
2066
+ if (!m || SAP_SETS[m[2]].service !== m[1]) return;
2067
+ const [, , set, key] = m, collection = `/${set}`, rows2 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
2068
+ if (method === "GET") {
2069
+ const issued = header2(headers, "x-csrf-token")?.toLowerCase() === "fetch" ? { "x-csrf-token": csrf } : void 0;
2070
+ if (key) {
2071
+ const record3 = rows2.find((r) => r[SAP_SETS[set].key] === key);
2072
+ return record3 ? read(collection, { d: sapView(set, record3) }, 200, issued) : { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection };
2073
+ }
2074
+ const where = query.$filter ? eqFilter(query.$filter, "'") : () => true;
2075
+ const top = limitOf(query.$top, 1e3, 5e3), skip = Number(query.$skip ?? 0);
2076
+ if (!where || top === null || !Number.isInteger(skip) || skip < 0) return;
2077
+ return read(collection, { d: { results: rows2.filter(where).slice(skip, skip + top).map((r) => sapView(set, r)) } }, 200, issued);
2078
+ }
2079
+ if (header2(headers, "x-csrf-token") !== csrf) return { ...sapError(403, "403", "CSRF token validation failed", { "x-csrf-token": "Required" }), collection };
2080
+ if (method === "POST" && !key) {
2081
+ if (set === "A_BusinessPartner") {
2082
+ 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 };
2083
+ const record4 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${(EPOCH2 + sequence) * 1e3})/`, BusinessPartnerIsBlocked: false };
2084
+ rows2.push(record4);
2085
+ return write2(collection, record4, { d: sapView(set, record4) }, 201);
2086
+ }
2087
+ const items = isObject2(body.to_Item) && Array.isArray(body.to_Item.results) ? body.to_Item.results : null;
2088
+ if (!body.SalesOrderType || !body.SoldToParty || !items?.length || !items.every((i) => isObject2(i) && i.Material && i.RequestedQuantity)) return { ...sapError(400, "V1/320", "Sales order requires SalesOrderType, SoldToParty and at least one item with Material and RequestedQuantity"), collection };
2089
+ if (!table(data, "/A_BusinessPartner").some((p) => p.BusinessPartner === String(body.SoldToParty))) return { ...sapError(400, "V1/302", `Sold-to party ${body.SoldToParty} does not exist`), collection };
2090
+ const total = items.reduce((sum, i) => sum + Number(i.NetAmount ?? 0), 0);
2091
+ const { to_Item: _items, ...header_ } = body;
2092
+ const record3 = {
2093
+ SalesOrder: String(nextNumber(rows2, "SalesOrder", 1)).padStart(10, "0"),
2094
+ ...header_,
2095
+ TransactionCurrency: body.TransactionCurrency ?? "USD",
2096
+ TotalNetAmount: total.toFixed(2),
2097
+ OverallSDProcessStatus: "A",
2098
+ CreationDate: `/Date(${(EPOCH2 + sequence) * 1e3})/`,
2099
+ to_Item: { results: items.map((i, n) => ({ SalesOrderItem: String((n + 1) * 10), ...i })) }
2100
+ };
2101
+ rows2.push(record3);
2102
+ return write2(collection, record3, { d: sapView(set, record3) }, 201);
2103
+ }
2104
+ const record2 = key ? rows2.find((r) => r[SAP_SETS[set].key] === key) : void 0;
2105
+ if (!record2) return key ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
2106
+ if (method === "PATCH" || method === "MERGE") {
2107
+ if (!flat(body) || SAP_SETS[set].key in body) return;
2108
+ Object.assign(record2, body);
2109
+ return write2(collection, record2, null, 204);
2110
+ }
2111
+ };
2112
+ var graphError = (status, code, message, sequence) => ({ status, body: { error: { code, message, innerError: { date: iso2(sequence), "request-id": hash(`graph:${sequence}:${code}`).slice(0, 36) } } } });
2113
+ var graphId = (seed) => {
2114
+ const h = hash(seed);
2115
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
2116
+ };
2117
+ var graphPage = (rows2, query) => {
2118
+ const where = query.$filter ? eqFilter(query.$filter, "'") : () => true, top = limitOf(query.$top, 100, 999);
2119
+ if (!where || top === null) return null;
2120
+ const select = query.$select?.split(",").map((s) => s.trim());
2121
+ return rows2.filter(where).slice(0, top).map((r) => select ? Object.fromEntries([["id", r.id], ...select.map((s) => [s, r[s] ?? null])]) : r);
2122
+ };
2123
+ var teams = (method, path, body, query, _headers, data, sequence) => {
2124
+ const m = /^\/v1\.0\/(?:teams\/([\w-]+)\/channels(?:\/([\w:@.%-]+)\/messages(?:\/(\d+)\/replies)?)?|chats\/([\w:@.%-]+)\/messages)$/.exec(path);
2125
+ if (!m) return;
2126
+ const [, teamId, rawChannel, parentId, rawChat] = m, channels = table(data, "/channels"), messages = table(data, "/messages");
2127
+ if (teamId && !rawChannel && method === "GET") return read("/channels", { value: channels.filter((c) => c.teamId === teamId) });
2128
+ const channelId = rawChannel && decodeURIComponent(rawChannel), chatId = rawChat && decodeURIComponent(rawChat);
2129
+ const exists = channelId ? channels.some((c) => c.teamId === teamId && c.id === channelId) : table(data, "/chats").some((c) => c.id === chatId);
2130
+ if (!exists) return { ...graphError(404, "NotFound", "Resource not found", sequence), collection: "/messages" };
2131
+ const scope = (r) => channelId ? r.channelIdentity?.channelId === channelId && r.channelIdentity?.teamId === teamId : r.chatId === chatId;
2132
+ if (method === "GET") {
2133
+ const page = graphPage(messages.filter((r) => scope(r) && (parentId ? r.replyToId === parentId : !r.replyToId)), query);
2134
+ return page ? read("/messages", { "@odata.count": page.length, value: page }) : void 0;
2135
+ }
2136
+ if (method !== "POST") return;
2137
+ if (!isObject2(body.body) || typeof body.body.content !== "string" || !body.body.content.trim()) return { ...graphError(400, "BadRequest", "Missing body content", sequence), collection: "/messages" };
2138
+ if (body.body.contentType !== void 0 && !["text", "html"].includes(body.body.contentType)) return;
2139
+ if (parentId && !messages.some((r) => scope(r) && r.id === parentId)) return { ...graphError(404, "NotFound", "Resource not found", sequence), collection: "/messages" };
2140
+ const record2 = {
2141
+ id: String((EPOCH2 + sequence) * 1e3 + messages.length),
2142
+ replyToId: parentId ?? null,
2143
+ messageType: "message",
2144
+ createdDateTime: iso2(sequence),
2145
+ lastModifiedDateTime: iso2(sequence),
2146
+ importance: body.importance ?? "normal",
2147
+ subject: body.subject ?? null,
2148
+ body: { contentType: body.body.contentType ?? "text", content: body.body.content },
2149
+ from: { application: null, user: { id: "agenttwin-app", displayName: "Agent" } },
2150
+ ...channelId ? { channelIdentity: { teamId, channelId } } : { chatId },
2151
+ attachments: [],
2152
+ mentions: []
2153
+ };
2154
+ messages.push(record2);
2155
+ return write2("/messages", record2, record2, 201);
2156
+ };
2157
+ var address = (r) => isObject2(r) && isObject2(r.emailAddress) && typeof r.emailAddress.address === "string" && /^[^@\s]+@[^@\s]+$/.test(r.emailAddress.address);
2158
+ var outlook = (method, path, body, query, _headers, data, sequence) => {
2159
+ const m = /^\/v1\.0\/(?:me|users\/[^/]+)\/(sendMail|messages|mailFolders\/(inbox|sentitems)\/messages|messages\/([\w=-]+)(?:\/(reply))?)$/.exec(path);
2160
+ if (!m) return;
2161
+ const messages = table(data, "/messages"), [, route, folder, id, reply] = m;
2162
+ const store = (message, parentFolderId) => {
2163
+ const record3 = {
2164
+ id: Buffer.from(hash(`outlook:${sequence}:${messages.length}`).slice(0, 30)).toString("base64url"),
2165
+ createdDateTime: iso2(sequence),
2166
+ sentDateTime: iso2(sequence),
2167
+ receivedDateTime: iso2(sequence),
2168
+ subject: message.subject ?? "",
2169
+ body: message.body ?? { contentType: "text", content: "" },
2170
+ toRecipients: message.toRecipients ?? [],
2171
+ ccRecipients: message.ccRecipients ?? [],
2172
+ from: { emailAddress: { address: "agent@contoso.test", name: "Agent" } },
2173
+ isRead: true,
2174
+ isDraft: false,
2175
+ importance: message.importance ?? "normal",
2176
+ parentFolderId,
2177
+ conversationId: message.conversationId ?? graphId(`conv:${sequence}`)
2178
+ };
2179
+ messages.push(record3);
2180
+ return record3;
2181
+ };
2182
+ if (route === "sendMail" && method === "POST") {
2183
+ const message = body.message;
2184
+ if (!isObject2(message)) return { ...graphError(400, "ErrorInvalidRequest", "The message is missing.", sequence), collection: "/messages" };
2185
+ const recipients = [...message.toRecipients ?? [], ...message.ccRecipients ?? [], ...message.bccRecipients ?? []];
2186
+ if (!recipients.length || !recipients.every(address)) return { ...graphError(400, "ErrorInvalidRecipients", "At least one recipient isn't valid.", sequence), collection: "/messages" };
2187
+ if (message.attachments?.length) return;
2188
+ return write2("/messages", store(message, "sentitems"), null, 202);
2189
+ }
2190
+ if ((route === "messages" || folder) && method === "GET") {
2191
+ const page = graphPage(messages.filter((r) => !folder || r.parentFolderId === folder), query);
2192
+ return page ? read("/messages", { value: page }) : void 0;
2193
+ }
2194
+ const record2 = id ? messages.find((r) => r.id === id) : void 0;
2195
+ if (!record2) return id ? { ...graphError(404, "ErrorItemNotFound", "The specified object was not found in the store.", sequence), collection: "/messages" } : void 0;
2196
+ if (!reply && method === "GET") return read("/messages", record2);
2197
+ if (!reply && method === "PATCH") {
2198
+ if (Object.keys(body).some((k) => !["isRead", "categories", "importance", "flag"].includes(k))) return;
2199
+ Object.assign(record2, body);
2200
+ return write2("/messages", record2, record2);
2201
+ }
2202
+ if (reply && method === "POST") {
2203
+ const to = record2.parentFolderId === "sentitems" ? record2.toRecipients : [record2.from];
2204
+ return write2("/messages", store({ subject: `RE: ${record2.subject}`, body: { contentType: "text", content: String(body.comment ?? "") }, toRecipients: to, conversationId: record2.conversationId }, "sentitems"), null, 202);
2205
+ }
2206
+ };
2207
+ var entra = (method, path, body, query, _headers, data, sequence) => {
2208
+ const m = /^\/v1\.0\/(users|groups)(?:\/([^/]+))?(?:\/members(?:\/([\w-]+))?(\/\$ref)?)?$/.exec(path);
2209
+ if (!m) return;
2210
+ const [, kind, rawKey, memberId, ref] = m, users = table(data, "/users"), groups = table(data, "/groups"), members = table(data, "/groupMembers");
2211
+ const key = rawKey && decodeURIComponent(rawKey), membersRoute = path.includes("/members");
2212
+ if (kind === "users" && !key) {
2213
+ if (method === "GET") {
2214
+ const page = graphPage(users, query);
2215
+ return page ? read("/users", { value: page }) : void 0;
2216
+ }
2217
+ if (method !== "POST") return;
2218
+ const required = ["accountEnabled", "displayName", "mailNickname", "userPrincipalName"];
2219
+ if (required.some((f) => body[f] === void 0) || !isObject2(body.passwordProfile) || typeof body.passwordProfile.password !== "string")
2220
+ return { ...graphError(400, "Request_BadRequest", `Invalid value specified for property '${required.find((f) => body[f] === void 0) ?? "passwordProfile"}' of resource 'User'.`, sequence), collection: "/users" };
2221
+ if (users.some((u) => String(u.userPrincipalName).toLowerCase() === String(body.userPrincipalName).toLowerCase()))
2222
+ return { ...graphError(400, "Request_BadRequest", "Another object with the same value for property userPrincipalName already exists.", sequence), collection: "/users" };
2223
+ const { passwordProfile: _secret, ...profile } = body;
2224
+ const record2 = { id: graphId(`entra:user:${sequence}:${users.length}`), ...profile, mail: profile.mail ?? null, jobTitle: profile.jobTitle ?? null, department: profile.department ?? null, createdDateTime: iso2(sequence) };
2225
+ users.push(record2);
2226
+ return write2("/users", record2, record2, 201);
2227
+ }
2228
+ if (kind === "groups" && !key && method === "GET") {
2229
+ const page = graphPage(groups, query);
2230
+ return page ? read("/groups", { value: page }) : void 0;
2231
+ }
2232
+ if (kind === "users") {
2233
+ const user = users.find((u) => u.id === key || String(u.userPrincipalName).toLowerCase() === String(key).toLowerCase());
2234
+ if (!user) return { ...graphError(404, "Request_ResourceNotFound", `Resource '${key}' does not exist or one of its queried reference-property objects are not present.`, sequence), collection: "/users" };
2235
+ if (membersRoute) return;
2236
+ if (method === "GET") return read("/users", user);
2237
+ if (method === "PATCH") {
2238
+ if (Object.keys(body).some((k) => ["id", "userPrincipalName", "passwordProfile"].includes(k)) || !flat(body)) return;
2239
+ Object.assign(user, body);
2240
+ return write2("/users", user, null, 204);
2241
+ }
2242
+ if (method === "DELETE") {
2243
+ users.splice(users.indexOf(user), 1);
2244
+ for (const link of members.filter((l) => l.userId === user.id)) members.splice(members.indexOf(link), 1);
2245
+ return write2("/users", user, null, 204);
2246
+ }
2247
+ return;
2248
+ }
2249
+ const group = groups.find((g) => g.id === key);
2250
+ if (!group) return { ...graphError(404, "Request_ResourceNotFound", `Resource '${key}' does not exist or one of its queried reference-property objects are not present.`, sequence), collection: "/groups" };
2251
+ if (!membersRoute) return method === "GET" ? read("/groups", group) : void 0;
2252
+ if (method === "GET" && !memberId && !ref) return read("/groupMembers", { value: members.filter((l) => l.groupId === group.id).map((l) => users.find((u) => u.id === l.userId)).filter(Boolean).map((u) => ({ "@odata.type": "#microsoft.graph.user", ...u })) });
2253
+ if (method === "POST" && !memberId && ref) {
2254
+ const target = /\/directoryObjects\/([\w-]+)$/.exec(String(body["@odata.id"] ?? ""))?.[1];
2255
+ if (!target || !users.some((u) => u.id === target)) return { ...graphError(404, "Request_ResourceNotFound", `Resource '${target ?? ""}' does not exist or one of its queried reference-property objects are not present.`, sequence), collection: "/groupMembers" };
2256
+ if (members.some((l) => l.groupId === group.id && l.userId === target)) return { ...graphError(400, "Request_BadRequest", "One or more added object references already exist for the following modified properties: 'members'.", sequence), collection: "/groupMembers" };
2257
+ const link = { id: `${group.id}:${target}`, groupId: group.id, userId: target, addedDateTime: iso2(sequence) };
2258
+ members.push(link);
2259
+ return write2("/groupMembers", link, null, 204);
2260
+ }
2261
+ if (method === "DELETE" && memberId && ref) {
2262
+ const link = members.find((l) => l.groupId === group.id && l.userId === memberId);
2263
+ if (!link) return { ...graphError(404, "Request_ResourceNotFound", `Resource '${memberId}' does not exist or one of its queried reference-property objects are not present.`, sequence), collection: "/groupMembers" };
2264
+ members.splice(members.indexOf(link), 1);
2265
+ return write2("/groupMembers", link, null, 204);
2266
+ }
2267
+ };
2268
+ var oktaError = (status, errorCode, errorSummary, causes = []) => ({ status, body: { errorCode, errorSummary, errorLink: errorCode, errorId: `oae${hash(errorSummary).slice(0, 19)}`, errorCauses: causes.map((errorSummary2) => ({ errorSummary: errorSummary2 })) } });
2269
+ var oktaId = (prefix, seed) => prefix + Buffer.from(hash(seed)).toString("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, 17);
2270
+ var okta = (method, path, body, query, _headers, data, sequence) => {
2271
+ const m = /^\/api\/v1\/(users|groups)(?:\/([^/]+))?(?:\/(users)(?:\/([\w]+))?|\/lifecycle\/(activate|deactivate|suspend|unsuspend))?$/.exec(path);
2272
+ if (!m) return;
2273
+ const [, kind, rawKey, groupUsers, memberId, lifecycle] = m, users = table(data, "/users"), groups = table(data, "/groups"), memberships = table(data, "/groupMemberships");
2274
+ const key = rawKey && decodeURIComponent(rawKey);
2275
+ const notFound2 = (what, type) => ({ ...oktaError(404, "E0000007", `Not found: Resource not found: ${what} (${type})`), collection: `/${kind}` });
2276
+ if (kind === "users" && !key) {
2277
+ if (method === "GET") {
2278
+ const limit = limitOf(query.limit, 200, 200);
2279
+ if (limit === null) return;
2280
+ let rows2 = users;
2281
+ if (query.filter) {
2282
+ const where = eqFilter(query.filter, '"');
2283
+ if (!where) return;
2284
+ rows2 = rows2.filter(where);
2285
+ }
2286
+ if (query.q) {
2287
+ const q = query.q.toLowerCase();
2288
+ rows2 = rows2.filter((u) => ["firstName", "lastName", "email", "login"].some((f) => String(u.profile?.[f] ?? "").toLowerCase().startsWith(q)));
2289
+ }
2290
+ return read("/users", rows2.slice(0, limit));
2291
+ }
2292
+ if (method !== "POST") return;
2293
+ const profile = body.profile;
2294
+ if (!isObject2(profile) || !["firstName", "lastName", "email", "login"].every((f) => typeof profile[f] === "string" && profile[f]))
2295
+ return { ...oktaError(400, "E0000001", "Api validation failed: profile", ["profile: firstName, lastName, email and login are required"]), collection: "/users" };
2296
+ if (users.some((u) => String(u.profile?.login).toLowerCase() === String(profile.login).toLowerCase()))
2297
+ return { ...oktaError(400, "E0000001", "Api validation failed: login", ["login: An object with this field already exists in the current organization"]), collection: "/users" };
2298
+ const active = query.activate !== "false";
2299
+ const record2 = { id: oktaId("00u", `okta:user:${sequence}:${users.length}`), status: active ? "ACTIVE" : "STAGED", created: iso2(sequence), activated: active ? iso2(sequence) : null, statusChanged: active ? iso2(sequence) : null, lastUpdated: iso2(sequence), profile: { ...profile } };
2300
+ users.push(record2);
2301
+ return write2("/users", record2, record2);
2302
+ }
2303
+ if (kind === "groups" && !key && method === "GET") {
2304
+ const q = query.q?.toLowerCase();
2305
+ return read("/groups", groups.filter((g) => !q || String(g.profile?.name ?? "").toLowerCase().startsWith(q)));
2306
+ }
2307
+ if (kind === "users") {
2308
+ const user = users.find((u) => u.id === key || String(u.profile?.login).toLowerCase() === String(key).toLowerCase());
2309
+ if (!user) return notFound2(String(key), "User");
2310
+ if (lifecycle && method === "POST") {
2311
+ const from = user.status;
2312
+ const to = lifecycle === "activate" ? ["STAGED", "PROVISIONED", "DEPROVISIONED"].includes(from) ? "ACTIVE" : null : lifecycle === "deactivate" ? from !== "DEPROVISIONED" ? "DEPROVISIONED" : null : lifecycle === "suspend" ? from === "ACTIVE" ? "SUSPENDED" : null : from === "SUSPENDED" ? "ACTIVE" : null;
2313
+ if (!to) return { ...oktaError(400, "E0000001", `Api validation failed: Cannot ${lifecycle} a user with status ${from}`), collection: "/users" };
2314
+ Object.assign(user, { status: to, statusChanged: iso2(sequence), lastUpdated: iso2(sequence), ...to === "ACTIVE" ? { activated: iso2(sequence) } : {} });
2315
+ return write2("/users", user, {});
2316
+ }
2317
+ if (lifecycle || groupUsers) return;
2318
+ if (method === "GET") return read("/users", user);
2319
+ if (method === "POST") {
2320
+ if (!isObject2(body.profile) || Object.keys(body).some((k) => k !== "profile") || !flat(body.profile)) return;
2321
+ Object.assign(user.profile, body.profile, {});
2322
+ user.lastUpdated = iso2(sequence);
2323
+ return write2("/users", user, user);
2324
+ }
2325
+ if (method === "DELETE") {
2326
+ if (user.status !== "DEPROVISIONED") {
2327
+ Object.assign(user, { status: "DEPROVISIONED", statusChanged: iso2(sequence), lastUpdated: iso2(sequence) });
2328
+ return write2("/users", user, null, 204);
2329
+ }
2330
+ users.splice(users.indexOf(user), 1);
2331
+ for (const link of memberships.filter((l) => l.userId === user.id)) memberships.splice(memberships.indexOf(link), 1);
2332
+ return write2("/users", { ...user, status: "DELETED" }, null, 204);
2333
+ }
2334
+ return;
2335
+ }
2336
+ const group = groups.find((g) => g.id === key);
2337
+ if (!group) return notFound2(String(key), "UserGroup");
2338
+ if (!groupUsers) return method === "GET" && !lifecycle ? read("/groups", group) : void 0;
2339
+ if (!memberId && method === "GET") return read("/groupMemberships", memberships.filter((l) => l.groupId === group.id).map((l) => users.find((u) => u.id === l.userId)).filter(Boolean));
2340
+ if (!memberId) return;
2341
+ if (!users.some((u) => u.id === memberId)) return { ...notFound2(memberId, "User"), collection: "/groupMemberships" };
2342
+ const existing = memberships.find((l) => l.groupId === group.id && l.userId === memberId);
2343
+ if (method === "PUT") {
2344
+ if (existing) return write2("/groupMemberships", existing, null, 204);
2345
+ const link = { id: `${group.id}:${memberId}`, groupId: group.id, userId: memberId, created: iso2(sequence) };
2346
+ memberships.push(link);
2347
+ return write2("/groupMemberships", link, null, 204);
2348
+ }
2349
+ if (method === "DELETE") {
2350
+ if (existing) memberships.splice(memberships.indexOf(existing), 1);
2351
+ return write2("/groupMemberships", existing ?? { groupId: group.id, userId: memberId }, null, 204);
2352
+ }
2353
+ };
2354
+ var cfError = (status, code, title) => ({ status, body: { errors: [{ status, code, title, detail: null }] } });
2355
+ var storage = (b) => isObject2(b) && b.representation === "storage" && typeof b.value === "string";
2356
+ var confluence = (method, path, body, query, _headers, data, sequence) => {
2357
+ const m = /^\/wiki\/api\/v2\/(pages|spaces|footer-comments)(?:\/(\d+))?$/.exec(path);
2358
+ if (!m) return;
2359
+ const [, kind, id] = m, pages = table(data, "/pages"), spaces = table(data, "/spaces"), comments = table(data, "/comments");
2360
+ const view = (p) => {
2361
+ const { body: content, ...rest } = p;
2362
+ return query["body-format"] === "storage" ? { ...rest, body: { storage: content } } : rest;
2363
+ };
2364
+ const nextId2 = () => String(nextNumber([...pages, ...comments], "id", 98305));
2365
+ if (kind === "spaces" && method === "GET" && !id) return read("/spaces", { results: spaces, _links: {} });
2366
+ if (kind === "footer-comments" && method === "POST" && !id) {
2367
+ const page2 = pages.find((p) => p.id === String(body.pageId) && p.status !== "trashed");
2368
+ if (!page2) return { ...cfError(404, "NOT_FOUND", "Page not found"), collection: "/comments" };
2369
+ if (!storage(body.body)) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "Comment body must use the storage representation"), collection: "/comments" };
2370
+ const record2 = { id: nextId2(), pageId: page2.id, status: "current", title: `Re: ${page2.title}`, version: { number: 1, createdAt: iso2(sequence) }, body: body.body };
2371
+ comments.push(record2);
2372
+ return write2("/comments", record2, record2);
2373
+ }
2374
+ if (kind !== "pages") return;
2375
+ if (!id && method === "GET") {
2376
+ const limit = limitOf(query.limit, 25, 250);
2377
+ if (limit === null) return;
2378
+ const status = query.status ?? "current";
2379
+ return read("/pages", { results: pages.filter((p) => p.status === status && (!query["space-id"] || p.spaceId === query["space-id"]) && (!query.title || p.title === query.title)).slice(0, limit).map(view), _links: {} });
2380
+ }
2381
+ if (!id && method === "POST") {
2382
+ if (!spaces.some((s) => s.id === String(body.spaceId))) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "Invalid space id"), collection: "/pages" };
2383
+ if (typeof body.title !== "string" || !body.title.trim() || !storage(body.body)) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "A page requires a title and a storage-format body"), collection: "/pages" };
2384
+ if (pages.some((p) => p.spaceId === String(body.spaceId) && p.title === body.title && p.status !== "trashed"))
2385
+ return { ...cfError(400, "BAD_REQUEST", "A page with this title already exists: A page already exists with the same TITLE in this space"), collection: "/pages" };
2386
+ const record2 = { id: nextId2(), status: body.status === "draft" ? "draft" : "current", title: body.title, spaceId: String(body.spaceId), parentId: body.parentId ?? null, authorId: "agenttwin-agent", createdAt: iso2(sequence), version: { number: 1, createdAt: iso2(sequence), message: "" }, body: body.body };
2387
+ pages.push(record2);
2388
+ return write2("/pages", record2, view(record2));
2389
+ }
2390
+ const page = pages.find((p) => p.id === id && p.status !== "trashed");
2391
+ if (!page) return { ...cfError(404, "NOT_FOUND", "Page not found"), collection: "/pages" };
2392
+ if (method === "GET") return read("/pages", view(page));
2393
+ if (method === "PUT") {
2394
+ const provided = isObject2(body.version) ? Number(body.version.number) : NaN;
2395
+ if (provided !== page.version.number + 1) return { ...cfError(409, "CONFLICT", `Version must be incremented when updating a page. Current Version: [${page.version.number}]. Provided version: [${Number.isNaN(provided) ? "none" : provided}]`), collection: "/pages" };
2396
+ if (typeof body.title !== "string" || !storage(body.body)) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "A page update requires title, body and version"), collection: "/pages" };
2397
+ Object.assign(page, { title: body.title, status: body.status ?? page.status, body: body.body, version: { number: provided, createdAt: iso2(sequence), message: isObject2(body.version) ? body.version.message ?? "" : "" } });
2398
+ return write2("/pages", page, view(page));
2399
+ }
2400
+ if (method === "DELETE") {
2401
+ page.status = "trashed";
2402
+ return write2("/pages", page, null, 204);
2403
+ }
2404
+ };
2405
+ var sharepoint = (method, path, body, query, _headers, data, sequence) => {
2406
+ const m = /^\/v1\.0\/sites\/([^/]+)\/(?:lists(?:\/([^/]+)\/items(?:\/(\d+)(\/fields)?)?)?|drive\/root\/children)$/.exec(path);
2407
+ if (!m) return;
2408
+ const [, siteId, listKey, itemId, fieldsRoute] = m, lists = table(data, "/lists"), items = table(data, "/listItems"), files = table(data, "/driveItems");
2409
+ if (path.endsWith("/drive/root/children")) {
2410
+ if (method === "GET") return read("/driveItems", { value: files.filter((f) => f.siteId === siteId) });
2411
+ if (method !== "POST" || typeof body.name !== "string" || !body.name || /[\\/:*?"<>|]/.test(body.name) || !isObject2(body.folder)) return;
2412
+ let name = body.name;
2413
+ if (files.some((f) => f.siteId === siteId && f.name === name)) {
2414
+ const behaviour = body["@microsoft.graph.conflictBehavior"] ?? "fail";
2415
+ if (behaviour !== "rename") return { ...graphError(409, "nameAlreadyExists", "The specified item name already exists.", sequence), collection: "/driveItems" };
2416
+ let n = 1;
2417
+ while (files.some((f) => f.siteId === siteId && f.name === `${body.name} ${n}`)) n++;
2418
+ name = `${body.name} ${n}`;
2419
+ }
2420
+ const record2 = { id: hash(`sp:drive:${sequence}:${files.length}`).slice(0, 34).toUpperCase(), siteId, name, folder: { childCount: 0 }, createdDateTime: iso2(sequence), lastModifiedDateTime: iso2(sequence), webUrl: `https://contoso.sharepoint.test/sites/${siteId}/Shared%20Documents/${encodeURIComponent(name)}` };
2421
+ files.push(record2);
2422
+ return write2("/driveItems", record2, record2, 201);
2423
+ }
2424
+ if (!listKey) return method === "GET" ? read("/lists", { value: lists.filter((l) => l.siteId === siteId) }) : void 0;
2425
+ const list2 = lists.find((l) => l.siteId === siteId && (l.id === listKey || l.displayName === decodeURIComponent(listKey)));
2426
+ if (!list2) return { ...graphError(404, "itemNotFound", "The requested list was not found.", sequence), collection: "/listItems" };
2427
+ const own = items.filter((i) => i.listId === list2.id);
2428
+ const view = (i, withFields = query.expand === "fields" || query.$expand === "fields") => {
2429
+ const { listId: _l, siteId: _s, fields, ...rest } = i;
2430
+ return withFields ? { ...rest, fields } : rest;
2431
+ };
2432
+ if (!itemId && method === "GET") {
2433
+ const top = limitOf(query.$top, 200, 5e3);
2434
+ return top === null ? void 0 : read("/listItems", { value: own.slice(0, top).map((i) => view(i)) });
2435
+ }
2436
+ if (!itemId && method === "POST") {
2437
+ if (!isObject2(body.fields) || !flat(body.fields)) return { ...graphError(400, "invalidRequest", "Invalid request: fields are required.", sequence), collection: "/listItems" };
2438
+ const id = String(nextNumber(own, "id", 1));
2439
+ const record2 = { id, listId: list2.id, siteId, createdDateTime: iso2(sequence), lastModifiedDateTime: iso2(sequence), webUrl: `https://contoso.sharepoint.test/sites/${siteId}/Lists/${list2.displayName}/DispForm.aspx?ID=${id}`, fields: { id, Title: body.fields.Title ?? null, ...body.fields } };
2440
+ items.push(record2);
2441
+ return write2("/listItems", record2, view(record2, true), 201);
2442
+ }
2443
+ const item = own.find((i) => i.id === itemId);
2444
+ if (!item) return { ...graphError(404, "itemNotFound", "The resource could not be found.", sequence), collection: "/listItems" };
2445
+ if (method === "GET" && !fieldsRoute) return read("/listItems", view(item));
2446
+ if (method === "PATCH" && fieldsRoute) {
2447
+ if (!flat(body) || "id" in body) return;
2448
+ Object.assign(item.fields, body);
2449
+ item.lastModifiedDateTime = iso2(sequence);
2450
+ return write2("/listItems", item, item.fields);
2451
+ }
2452
+ if (method === "DELETE" && !fieldsRoute) {
2453
+ items.splice(items.indexOf(item), 1);
2454
+ return write2("/listItems", item, null, 204);
2455
+ }
2456
+ };
2457
+ var sfSqlValue = (token, bindings, counter) => {
2458
+ if (token === "?") {
2459
+ const b = bindings[String(++counter.n)];
2460
+ return isObject2(b) ? String(b.type).toUpperCase() === "FIXED" || String(b.type).toUpperCase() === "REAL" ? Number(b.value) : b.value : void 0;
2461
+ }
2462
+ if (/^'.*'$/s.test(token)) return token.slice(1, -1).replace(/''/g, "'");
2463
+ if (/^null$/i.test(token)) return null;
2464
+ if (/^(true|false)$/i.test(token)) return token.toLowerCase() === "true";
2465
+ if (/^-?\d+(\.\d+)?$/.test(token)) return Number(token);
2466
+ return void 0;
2467
+ };
2468
+ var VALUE = `('(?:[^']|'')*'|\\?|-?\\d+(?:\\.\\d+)?|null|true|false)`;
2469
+ var ident = (name) => name.startsWith('"') ? name.slice(1, -1) : name.toUpperCase();
2470
+ function sqlWhere(clause, bindings, counter) {
2471
+ if (!clause) return () => true;
2472
+ const tests = [];
2473
+ for (const part of clause.split(/\s+AND\s+/i)) {
2474
+ const c = new RegExp(`^\\s*("?[\\w$]+"?)\\s*(=|!=|<>)\\s*${VALUE}\\s*$`, "i").exec(part);
2475
+ if (!c) return null;
2476
+ const column = ident(c[1]), value = sfSqlValue(c[3], bindings, counter);
2477
+ if (value === void 0) return null;
2478
+ tests.push((r) => String(r[column] ?? null) === String(value) === (c[2] === "="));
2479
+ }
2480
+ return (r) => tests.every((t) => t(r));
2481
+ }
2482
+ var snowflake = (method, path, body, _query, _headers, data, sequence) => {
2483
+ const m = /^\/api\/v2\/statements(?:\/([\w-]+))?$/.exec(path);
2484
+ if (!m) return;
2485
+ const log = table(data, "/statements");
2486
+ if (m[1]) {
2487
+ if (method !== "GET") return;
2488
+ const done = log.find((s2) => s2.statementHandle === m[1]);
2489
+ return done ? read("/statements", done.result) : { status: 404, collection: "/statements", body: { code: "333334", message: `Statement ${m[1]} not found`, statementHandle: m[1] } };
2490
+ }
2491
+ if (method !== "POST" || typeof body.statement !== "string") return;
2492
+ const statement = body.statement.trim().replace(/;\s*$/, ""), bindings = isObject2(body.bindings) ? body.bindings : {}, counter = { n: 0 };
2493
+ const handle = graphId(`snowflake:${sequence}:${log.length}`);
2494
+ const missing = (name) => ({ status: 422, collection: "/statements", body: { code: "002003", message: `SQL compilation error:
2495
+ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCase()}' does not exist or not authorized.`, sqlState: "02000", statementHandle: handle } });
2496
+ const known2 = (name) => Object.hasOwn(data, `/${name}`) && name !== "STATEMENTS";
2497
+ const result = (columns, rows2, dml) => ({
2498
+ resultSetMetaData: { numRows: rows2.length, format: "jsonv2", partitionInfo: [{ rowCount: rows2.length }], rowType: columns.map((name) => ({ name: dml ?? name, type: dml ? "fixed" : "text", nullable: !dml })) },
2499
+ data: rows2.map((r) => r.map((v) => v === null || v === void 0 ? null : String(v))),
2500
+ code: "090001",
2501
+ statementStatusUrl: `/api/v2/statements/${handle}`,
2502
+ requestId: graphId(`sf-req:${sequence}`),
2503
+ sqlState: "00000",
2504
+ statementHandle: handle,
2505
+ message: "Statement executed successfully.",
2506
+ createdOn: (EPOCH2 + sequence) * 1e3
2507
+ });
2508
+ const remember = (collection, res, operation, record2) => {
2509
+ log.push({ statementHandle: handle, statement, result: res, createdOn: iso2(sequence) });
2510
+ return operation === "read" ? read(collection, res) : write2(collection, record2 ?? { statement }, res);
2511
+ };
2512
+ let s;
2513
+ if (s = /^SELECT\s+(.+?)\s+FROM\s+("?[\w$]+"?)(?:\s+WHERE\s+(.+?))?(?:\s+ORDER\s+BY\s+("?[\w$]+"?)(?:\s+(ASC|DESC))?)?(?:\s+LIMIT\s+(\d+))?$/is.exec(statement)) {
2514
+ const name = ident(s[2]);
2515
+ if (!known2(name)) return missing(name);
2516
+ const where = sqlWhere(s[3], bindings, counter);
2517
+ if (!where) return;
2518
+ let rows2 = data[`/${name}`].filter(where);
2519
+ if (s[4]) {
2520
+ const col = ident(s[4]), dir = s[5]?.toUpperCase() === "DESC" ? -1 : 1;
2521
+ rows2 = [...rows2].sort((a, b) => (a[col] > b[col] ? 1 : a[col] < b[col] ? -1 : 0) * dir);
2522
+ }
2523
+ if (s[6]) rows2 = rows2.slice(0, Number(s[6]));
2524
+ const columns = s[1].trim() === "*" ? [...new Set(data[`/${name}`].flatMap((r) => Object.keys(r)))] : s[1].split(",").map((c) => ident(c.trim()));
2525
+ if (columns.some((c) => !/^[\w$]+$/.test(c))) return;
2526
+ return remember(`/${name}`, result(columns, rows2.map((r) => columns.map((c) => r[c] ?? null))), "read");
2527
+ }
2528
+ if (s = /^INSERT\s+INTO\s+("?[\w$]+"?)\s*\(([^)]+)\)\s*VALUES\s*(.+)$/is.exec(statement)) {
2529
+ const name = ident(s[1]);
2530
+ if (!known2(name)) return missing(name);
2531
+ const columns = s[2].split(",").map((c) => ident(c.trim())), inserted = [];
2532
+ const tuples = s[3].match(new RegExp(`\\(\\s*${VALUE}(?:\\s*,\\s*${VALUE})*\\s*\\)`, "gi"));
2533
+ if (!tuples || tuples.join(",").replace(/\s/g, "") !== s[3].replace(/\s/g, "")) return;
2534
+ for (const tuple of tuples) {
2535
+ const values = tuple.slice(1, -1).match(new RegExp(VALUE, "gi")).map((v) => sfSqlValue(v, bindings, counter));
2536
+ if (values.length !== columns.length || values.some((v) => v === void 0)) return;
2537
+ inserted.push(Object.fromEntries(columns.map((c, i) => [c, values[i]])));
2538
+ }
2539
+ data[`/${name}`].push(...inserted);
2540
+ return remember(`/${name}`, result(["number of rows inserted"], [[inserted.length]], "number of rows inserted"), "write", inserted.length === 1 ? inserted[0] : { rows: inserted });
2541
+ }
2542
+ if (s = /^UPDATE\s+("?[\w$]+"?)\s+SET\s+(.+?)(?:\s+WHERE\s+(.+))?$/is.exec(statement)) {
2543
+ const name = ident(s[1]);
2544
+ if (!known2(name)) return missing(name);
2545
+ const sets = [];
2546
+ for (const assignment of s[2].split(/\s*,\s*(?=(?:[^']*'[^']*')*[^']*$)/)) {
2547
+ const a = new RegExp(`^\\s*("?[\\w$]+"?)\\s*=\\s*${VALUE}\\s*$`, "i").exec(assignment);
2548
+ if (!a) return;
2549
+ const value = sfSqlValue(a[2], bindings, counter);
2550
+ if (value === void 0) return;
2551
+ sets.push([ident(a[1]), value]);
2552
+ }
2553
+ const where = sqlWhere(s[3], bindings, counter);
2554
+ if (!where) return;
2555
+ const changed = data[`/${name}`].filter(where);
2556
+ for (const row of changed) for (const [k, v] of sets) row[k] = v;
2557
+ return remember(`/${name}`, { ...result(["number of rows updated"], [[changed.length]], "number of rows updated") }, "write", changed.length === 1 ? changed[0] : { rows: changed });
2558
+ }
2559
+ if (s = /^DELETE\s+FROM\s+("?[\w$]+"?)(?:\s+WHERE\s+(.+))?$/is.exec(statement)) {
2560
+ const name = ident(s[1]);
2561
+ if (!known2(name)) return missing(name);
2562
+ const where = sqlWhere(s[2], bindings, counter);
2563
+ if (!where) return;
2564
+ const removed = data[`/${name}`].filter(where);
2565
+ data[`/${name}`] = data[`/${name}`].filter((r) => !removed.includes(r));
2566
+ return remember(`/${name}`, result(["number of rows deleted"], [[removed.length]], "number of rows deleted"), "write", { deleted: removed });
2567
+ }
2568
+ };
2569
+ var NS_TYPES = ["customer", "vendor", "salesOrder", "invoice", "vendorBill"];
2570
+ var nsError = (status, title, detail, code) => ({ status, body: { type: `https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.${status === 404 ? 5 : 1}`, title, status, "o:errorDetails": [{ detail, "o:errorCode": code }] } });
2571
+ var nsLink = (type, id) => [{ rel: "self", href: `/services/rest/record/v1/${type}/${id}` }];
2572
+ var netsuite = (method, path, body, query, _headers, data, sequence) => {
2573
+ const m = /^\/services\/rest\/record\/v1\/(\w+)(?:\/(\d+))?$/.exec(path);
2574
+ if (!m || !NS_TYPES.includes(m[1])) return;
2575
+ const [, type, id] = m, collection = `/${type}`, rows2 = table(data, collection);
2576
+ if (!id && method === "GET") {
2577
+ const limit = limitOf(query.limit, 1e3, 1e3), offset = Number(query.offset ?? 0);
2578
+ if (limit === null || !Number.isInteger(offset) || offset < 0) return;
2579
+ let matched = rows2;
2580
+ if (query.q) {
2581
+ const tests = query.q.split(/\s+AND\s+/i).map((part) => /^\s*(\w+)\s+(IS|IS_NOT)\s+"([^"]*)"\s*$/i.exec(part));
2582
+ if (tests.some((t) => !t)) return;
2583
+ matched = rows2.filter((r) => tests.every((t) => String(r[t[1]] ?? "") === t[3] === (t[2].toUpperCase() === "IS")));
2584
+ }
2585
+ const page = matched.slice(offset, offset + limit);
2586
+ 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 });
2587
+ }
2588
+ if (!id && method === "POST") {
2589
+ const entity = isObject2(body.entity) ? String(body.entity.id) : void 0;
2590
+ if (type === "customer" && !body.companyName && !(body.isPerson && body.lastName)) return { ...nsError(400, "Bad Request", "Please enter value(s) for: Company Name", "USER_ERROR"), collection };
2591
+ if (type === "vendor" && !body.companyName) return { ...nsError(400, "Bad Request", "Please enter value(s) for: Company Name", "USER_ERROR"), collection };
2592
+ let total;
2593
+ if (["salesOrder", "invoice", "vendorBill"].includes(type)) {
2594
+ const party = type === "vendorBill" ? "/vendor" : "/customer";
2595
+ if (!entity || !table(data, party).some((r) => r.id === entity)) return { ...nsError(400, "Bad Request", `Invalid entity reference key ${entity ?? "(missing)"}.`, "INVALID_KEY_OR_REF"), collection };
2596
+ const lines = isObject2(body.item) && Array.isArray(body.item.items) ? body.item.items : null;
2597
+ if (!lines?.length || !lines.every((l) => isObject2(l) && isObject2(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 };
2598
+ total = lines.reduce((sum, l) => sum + Number(l.quantity) * Number(l.rate ?? 0), 0);
2599
+ }
2600
+ const newId2 = String(nextNumber(rows2, "id", 1001));
2601
+ const record3 = { id: newId2, ...body, ...total !== void 0 ? { total, currency: body.currency ?? { id: "1", refName: "USD" }, tranId: `${type === "salesOrder" ? "SO" : type === "invoice" ? "INV" : "BILL"}${newId2}` } : {}, dateCreated: iso2(sequence), lastModifiedDate: iso2(sequence) };
2602
+ rows2.push(record3);
2603
+ return write2(collection, record3, null, 204, { location: `/services/rest/record/v1/${type}/${newId2}` });
2604
+ }
2605
+ const record2 = id ? rows2.find((r) => r.id === id) : void 0;
2606
+ if (!record2) return { ...nsError(404, "Record Not Found", "The record instance does not exist. Provide a valid record instance ID.", "NONEXISTENT_ID"), collection };
2607
+ if (method === "GET") return read(collection, { links: nsLink(type, record2.id), ...record2 });
2608
+ if (method === "PATCH") {
2609
+ if ("id" in body) return;
2610
+ Object.assign(record2, body, { lastModifiedDate: iso2(sequence) });
2611
+ return write2(collection, record2, null, 204);
2612
+ }
2613
+ if (method === "DELETE") {
2614
+ rows2.splice(rows2.indexOf(record2), 1);
2615
+ return write2(collection, record2, null, 204);
2616
+ }
2617
+ };
2618
+ var pdError = (status, message, code, errors = []) => ({ status, body: { error: { message, code, errors } } });
2619
+ var pdId = (seed) => "P" + hash(seed).replace(/[^A-Z0-9]/gi, "").toUpperCase().slice(0, 6);
2620
+ var pagerduty = (method, path, body, query, headers, data, sequence) => {
2621
+ const services = table(data, "/services"), incidents = table(data, "/incidents"), notes = table(data, "/notes"), events = table(data, "/events");
2622
+ const open = (serviceId, key) => incidents.find((i) => i.service.id === serviceId && i.incident_key === key && i.status !== "resolved");
2623
+ const create = (service, title, urgency, key, details) => {
2624
+ const id2 = pdId(`pd:incident:${sequence}:${incidents.length}`);
2625
+ const record2 = {
2626
+ id: id2,
2627
+ type: "incident",
2628
+ summary: `[#${incidents.length + 1}] ${title}`,
2629
+ incident_number: nextNumber(incidents, "incident_number", 1),
2630
+ title,
2631
+ status: "triggered",
2632
+ urgency,
2633
+ created_at: iso2(sequence),
2634
+ updated_at: iso2(sequence),
2635
+ incident_key: key,
2636
+ service: { id: service.id, type: "service_reference", summary: service.name },
2637
+ html_url: `https://contoso.pagerduty.test/incidents/${id2}`,
2638
+ ...details === void 0 ? {} : { body: { type: "incident_body", details } }
2639
+ };
2640
+ incidents.push(record2);
2641
+ return record2;
2642
+ };
2643
+ if (path === "/v2/enqueue" && method === "POST") {
2644
+ const service = services.find((s) => s.integration_key && s.integration_key === body.routing_key);
2645
+ if (!service) return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["Invalid routing key"] } };
2646
+ const action = body.event_action, payload = body.payload;
2647
+ if (!["trigger", "acknowledge", "resolve"].includes(action)) return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'event_action' is invalid (must be one of the following: 'trigger', 'acknowledge' or 'resolve')"] } };
2648
+ if (action === "trigger" && !(isObject2(payload) && payload.summary && payload.source && ["critical", "error", "warning", "info"].includes(payload.severity)))
2649
+ return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'payload.summary', 'payload.source' and 'payload.severity' are required"] } };
2650
+ if (action !== "trigger" && !body.dedup_key) return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'dedup_key' is required for acknowledge and resolve"] } };
2651
+ const key = String(body.dedup_key ?? hash(`pd:dedup:${sequence}`).slice(0, 32));
2652
+ const existing = open(service.id, key);
2653
+ if (action === "trigger" && !existing) create(service, payload.summary, payload.severity === "critical" || payload.severity === "error" ? "high" : "low", key, payload.custom_details);
2654
+ if (action !== "trigger" && existing) Object.assign(existing, { status: action === "acknowledge" ? "acknowledged" : "resolved", updated_at: iso2(sequence) });
2655
+ const event = { id: hash(`pd:event:${sequence}:${events.length}`).slice(0, 24), service: service.id, event_action: action, dedup_key: key, grouped: action === "trigger" && !!existing, summary: isObject2(payload) ? payload.summary ?? null : null, received_at: iso2(sequence) };
2656
+ events.push(event);
2657
+ return write2("/events", event, { status: "success", message: "Event processed", dedup_key: key }, 202);
2658
+ }
2659
+ const m = /^\/(incidents|services)(?:\/(\w+))?(?:\/(notes))?$/.exec(path);
2660
+ if (!m) return;
2661
+ const [, kind, id, noteRoute] = m;
2662
+ const from = header2(headers, "from");
2663
+ const needsFrom = () => ({ ...pdError(400, `You must specify a user's email address in the "From" header to perform this action`, 2001), collection: "/incidents" });
2664
+ if (kind === "services") return method === "GET" && !id && !noteRoute ? read("/services", { services, limit: 25, offset: 0, total: null, more: false }) : void 0;
2665
+ if (!id && method === "GET") {
2666
+ const limit = limitOf(query.limit, 25, 100), offset = Number(query.offset ?? 0), statuses = query["statuses[]"] ?? query.statuses;
2667
+ if (limit === null || !Number.isInteger(offset) || offset < 0) return;
2668
+ const matched = incidents.filter((i) => (!statuses || i.status === statuses) && (!query["service_ids[]"] || i.service.id === query["service_ids[]"]) && (!query.incident_key || i.incident_key === query.incident_key));
2669
+ return read("/incidents", { incidents: matched.slice(offset, offset + limit), limit, offset, total: null, more: offset + limit < matched.length });
2670
+ }
2671
+ if (!id && method === "POST") {
2672
+ if (!from) return needsFrom();
2673
+ const input = body.incident;
2674
+ if (!isObject2(input) || input.type !== "incident" || typeof input.title !== "string" || !isObject2(input.service)) return { ...pdError(400, "Invalid Input Provided", 2001, ["Incident type, title and service are required."]), collection: "/incidents" };
2675
+ const service = services.find((s) => s.id === input.service.id);
2676
+ if (!service) return { ...pdError(400, "Invalid Input Provided", 2001, ["Service not found"]), collection: "/incidents" };
2677
+ if (input.incident_key && open(service.id, String(input.incident_key))) return { ...pdError(400, "Invalid Input Provided", 2001, ["Open incident with matching dedup key already exists on this service"]), collection: "/incidents" };
2678
+ const record2 = create(service, input.title, input.urgency === "low" ? "low" : "high", String(input.incident_key ?? hash(`pd:key:${sequence}`).slice(0, 32)), isObject2(input.body) ? input.body.details : void 0);
2679
+ return write2("/incidents", record2, { incident: record2 }, 201);
2680
+ }
2681
+ const incident = incidents.find((i) => i.id === id);
2682
+ if (!incident) return { ...pdError(404, "Not Found", 2100), collection: "/incidents" };
2683
+ if (noteRoute) {
2684
+ if (method === "GET") return read("/notes", { notes: notes.filter((n) => n.incident_id === incident.id) });
2685
+ if (method !== "POST") return;
2686
+ if (!from) return needsFrom();
2687
+ if (!isObject2(body.note) || typeof body.note.content !== "string" || !body.note.content) return { ...pdError(400, "Invalid Input Provided", 2001, ["Note content is required."]), collection: "/notes" };
2688
+ const note = { id: pdId(`pd:note:${sequence}:${notes.length}`), incident_id: incident.id, content: body.note.content, created_at: iso2(sequence), user: { type: "user_reference", summary: from } };
2689
+ notes.push(note);
2690
+ return write2("/notes", note, { note }, 201);
2691
+ }
2692
+ if (method === "GET") return read("/incidents", { incident });
2693
+ if (method === "PUT") {
2694
+ if (!from) return needsFrom();
2695
+ const input = body.incident;
2696
+ if (!isObject2(input) || !["acknowledged", "resolved"].includes(input.status ?? "") && input.urgency === void 0 && input.title === void 0) return;
2697
+ if (incident.status === "resolved" && input.status === "acknowledged") return { ...pdError(400, "Invalid Input Provided", 2001, ["Incident Already Resolved"]), collection: "/incidents" };
2698
+ Object.assign(incident, Object.fromEntries(["status", "urgency", "title"].filter((k) => input[k] !== void 0).map((k) => [k, input[k]])), { updated_at: iso2(sequence) });
2699
+ return write2("/incidents", incident, { incident });
2700
+ }
2701
+ };
2702
+ var ENTERPRISE_OPERATIONS = {
2703
+ salesforce,
2704
+ servicenow,
2705
+ workday,
2706
+ sap,
2707
+ "microsoft-teams": teams,
2708
+ outlook,
2709
+ "entra-id": entra,
2710
+ okta,
2711
+ confluence,
2712
+ sharepoint,
2713
+ snowflake,
2714
+ netsuite,
2715
+ pagerduty
2716
+ };
2717
+ var ENTERPRISE_OPTIONAL_COLLECTIONS = {
2718
+ salesforce: Object.keys(SF_OBJECTS).map((o) => `/sobjects/${o}`),
2719
+ servicenow: Object.keys(SN_TABLES).map((t) => `/${t}`),
2720
+ workday: ["/workers", "/timeOffRequests"],
2721
+ sap: ["/A_BusinessPartner", "/A_SalesOrder"],
2722
+ "microsoft-teams": ["/channels", "/chats", "/messages"],
2723
+ outlook: ["/messages"],
2724
+ "entra-id": ["/users", "/groups", "/groupMembers"],
2725
+ okta: ["/users", "/groups", "/groupMemberships"],
2726
+ confluence: ["/pages", "/spaces", "/comments"],
2727
+ sharepoint: ["/lists", "/listItems", "/driveItems"],
2728
+ snowflake: ["/statements"],
2729
+ netsuite: NS_TYPES.map((t) => `/${t}`),
2730
+ pagerduty: ["/services", "/incidents", "/notes", "/events"]
2731
+ };
2732
+ var FREEFORM_COLLECTION_ADAPTERS = ["snowflake"];
2733
+ function enterpriseAuth(adapter, headers, url, token) {
2734
+ if (adapter === "okta") return headers.authorization === `SSWS ${token}`;
2735
+ if (adapter === "pagerduty") return headers.authorization === `Token token=${token}` || new URL(url, "http://localhost").pathname === "/v2/enqueue";
2736
+ return false;
2737
+ }
2738
+ var unsupported = (body) => ({ ...body, forwardedToProduction: false });
2739
+ var ENTERPRISE_UNSUPPORTED = {
2740
+ salesforce: [unsupported({ errorCode: "UNSUPPORTED_OPERATION", message: "Outside the AgentTwin Salesforce REST subset" })],
2741
+ servicenow: unsupported({ error: { message: "Unsupported operation", detail: "Outside the AgentTwin ServiceNow Table API subset" }, status: "failure" }),
2742
+ workday: unsupported({ error: "Unsupported operation", errors: [{ error: "Outside the AgentTwin Workday REST subset" }] }),
2743
+ sap: unsupported({ error: { code: "UNSUPPORTED", message: { lang: "en", value: "Outside the AgentTwin SAP OData subset" } } }),
2744
+ "microsoft-teams": unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Microsoft Teams Graph subset" } }),
2745
+ outlook: unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Outlook mail Graph subset" } }),
2746
+ "entra-id": unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Entra ID Graph subset" } }),
2747
+ okta: unsupported({ errorCode: "E0000022", errorSummary: "The endpoint does not support the provided HTTP method", errorCauses: [{ errorSummary: "Outside the AgentTwin Okta subset" }] }),
2748
+ confluence: unsupported({ errors: [{ status: 501, code: "UNSUPPORTED", title: "Outside the AgentTwin Confluence v2 subset" }] }),
2749
+ sharepoint: unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin SharePoint Graph subset" } }),
2750
+ snowflake: unsupported({ code: "000002", message: "Statement or SQL feature outside the AgentTwin Snowflake subset (single-table SELECT/INSERT/UPDATE/DELETE with equality filters)" }),
2751
+ netsuite: unsupported({ title: "Unsupported", status: 501, "o:errorDetails": [{ detail: "Outside the AgentTwin NetSuite REST record subset", "o:errorCode": "UNSUPPORTED" }] }),
2752
+ pagerduty: unsupported({ error: { message: "Outside the AgentTwin PagerDuty subset", code: 2e3 } })
2753
+ };
2754
+ var op = (method, endpoint, effect, errors = []) => ({ method, endpoint, effect, parameters: [], errors });
2755
+ var ENTERPRISE_CONTRACTS = {
2756
+ salesforce: {
2757
+ version: "1.0.0",
2758
+ authentication: "Bearer run-scoped test token (OAuth access token shape)",
2759
+ operations: [op("POST", "/services/data/vXX.X/sobjects/<Account|Contact|Lead|Opportunity|Case>", "create record (18-char id with object prefix)", ["400 REQUIRED_FIELD_MISSING", "404 NOT_FOUND"]), op("GET", "/services/data/vXX.X/sobjects/<object>/<id>", "retrieve record with attributes", ["404 NOT_FOUND"]), op("PATCH", "/services/data/vXX.X/sobjects/<object>/<id>", "update fields (204)"), op("DELETE", "/services/data/vXX.X/sobjects/<object>/<id>", "delete record (204)"), op("GET", "/services/data/vXX.X/query?q=SOQL", "single-object SOQL with = / != filters joined by AND and LIMIT", ["400 INVALID_TYPE"])],
2760
+ limitations: ["Five standard objects; no custom objects, relationships, ORDER BY, OR, LIKE, aggregates or Composite/Bulk API", "No validation rules, triggers, flows or sharing; only standard required fields are enforced"]
2761
+ },
2762
+ servicenow: {
2763
+ version: "1.0.0",
2764
+ authentication: "Bearer run-scoped test token",
2765
+ operations: [op("GET", "/api/now/table/<incident|change_request|problem|sc_request|sys_user>", "list with sysparm_query (= and != joined by ^), sysparm_limit/offset/fields; X-Total-Count header"), op("POST", "/api/now/table/<table>", "create record with sys_id and number (INC0010001\u2026)"), op("GET", "/api/now/table/<table>/<sys_id>", "retrieve", ["404 No Record found"]), op("PATCH|PUT", "/api/now/table/<table>/<sys_id>", "update; values stored as strings"), op("DELETE", "/api/now/table/<table>/<sys_id>", "delete (204)")],
2766
+ limitations: ["Five tables; no ^OR, LIKE, ORDERBY, dot-walking, display values, business rules, ACLs or workflows"]
2767
+ },
2768
+ workday: {
2769
+ version: "1.0.0",
2770
+ authentication: "Bearer run-scoped test token",
2771
+ operations: [op("GET", "/ccx/api/v1/<tenant>/workers", "list/search workers"), op("GET", "/ccx/api/v1/<tenant>/workers/<id>", "retrieve worker", ["404 Invalid ID"]), op("POST", "/ccx/api/absenceManagement/v1/<tenant>/workers/<id>/requestTimeOff", "submit time off; rejects dates already requested", ["400 Validation error"]), op("GET", "/ccx/api/absenceManagement/v1/<tenant>/workers/<id>/timeOffDetails", "list a worker's requests")],
2772
+ limitations: ["Workers and time off only; business processes never advance past Submitted", "No SOAP Web Services, RaaS reports, compensation, hiring or approvals"]
2773
+ },
2774
+ sap: {
2775
+ version: "1.0.0",
2776
+ authentication: "Bearer run-scoped test token; writes require the x-csrf-token fetched by a prior GET (x-csrf-token: Fetch)",
2777
+ operations: [op("GET", "/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner[('<id>')]", "list ($filter eq/and, $top, $skip) or read"), op("POST", "/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner", "create business partner", ["403 CSRF token validation failed"]), op("GET", "/sap/opu/odata/sap/API_SALES_ORDER_SRV/A_SalesOrder[('<id>')]", "list or read sales orders"), op("POST", "/sap/opu/odata/sap/API_SALES_ORDER_SRV/A_SalesOrder", "create sales order with deep-inserted to_Item; sold-to party must exist", ["400 V1/302", "403 CSRF"]), op("PATCH|MERGE", "<entity>('<id>')", "update header fields (204)")],
2778
+ limitations: ["OData v2 JSON only; no $expand, $batch, $orderby, pricing, ATP checks or delivery/billing documents"]
2779
+ },
2780
+ "microsoft-teams": {
2781
+ version: "1.0.0",
2782
+ authentication: "Bearer run-scoped test token (Graph access token shape)",
2783
+ operations: [op("GET", "/v1.0/teams/<team>/channels", "list channels"), op("POST", "/v1.0/teams/<team>/channels/<channel>/messages", "post channel message", ["400 Missing body content", "404 NotFound"]), op("GET", "/v1.0/teams/<team>/channels/<channel>/messages", "list top-level messages"), op("POST|GET", "/v1.0/teams/<team>/channels/<channel>/messages/<id>/replies", "reply / list replies"), op("POST|GET", "/v1.0/chats/<chat>/messages", "send / list chat messages")],
2784
+ limitations: ["No adaptive card rendering, mentions resolution, reactions, edits, deletes, meetings or change notifications"]
2785
+ },
2786
+ outlook: {
2787
+ version: "1.0.0",
2788
+ authentication: "Bearer run-scoped test token (Graph access token shape)",
2789
+ 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)")],
2790
+ limitations: ["No attachments, drafts, forward, rules, calendar or delta queries; inbound mail exists only as seeded records"]
2791
+ },
2792
+ "entra-id": {
2793
+ version: "1.0.0",
2794
+ authentication: "Bearer run-scoped test token (Graph access token shape)",
2795
+ operations: [op("GET|POST", "/v1.0/users", "list ($filter eq, $top, $select) / create user; duplicate UPN rejected", ["400 Request_BadRequest"]), op("GET|PATCH|DELETE", "/v1.0/users/<id|upn>", "read / update (204) / delete (204)"), op("GET", "/v1.0/groups[/<id>]", "list / read groups"), op("GET", "/v1.0/groups/<id>/members", "list members"), op("POST", "/v1.0/groups/<id>/members/$ref", "add member (204); duplicates rejected"), op("DELETE", "/v1.0/groups/<id>/members/<user>/$ref", "remove member (204)")],
2796
+ limitations: ["Passwords are accepted but never stored; no sign-in, licences, roles, app registrations or conditional access"]
2797
+ },
2798
+ okta: {
2799
+ version: "1.0.0",
2800
+ authentication: "SSWS run-scoped test token (Okta API token header)",
2801
+ operations: [op("GET|POST", "/api/v1/users", "list (q, filter eq, limit) / create (?activate=false stages); duplicate login rejected", ["400 E0000001"]), op("GET|POST|DELETE", "/api/v1/users/<id|login>", "read / partial profile update / delete (first DELETE deactivates, second removes)", ["404 E0000007"]), op("POST", "/api/v1/users/<id>/lifecycle/<activate|deactivate|suspend|unsuspend>", "status transitions; invalid ones rejected"), op("GET", "/api/v1/groups[/<id>]", "list / read groups"), op("GET|PUT|DELETE", "/api/v1/groups/<id>/users[/<user>]", "list / add / remove members")],
2802
+ limitations: ["No authentication flows, factors, apps, policies, event hooks or rate-limit headers; pagination links omitted"]
2803
+ },
2804
+ confluence: {
2805
+ version: "1.0.0",
2806
+ authentication: "Bearer run-scoped test token",
2807
+ operations: [op("GET|POST", "/wiki/api/v2/pages", "list (space-id, title, status, limit) / create; duplicate title in a space rejected", ["400 BAD_REQUEST"]), op("GET|PUT|DELETE", "/wiki/api/v2/pages/<id>", "read (body-format=storage) / update requiring version+1 / trash", ["409 CONFLICT", "404 NOT_FOUND"]), op("GET", "/wiki/api/v2/spaces", "list spaces"), op("POST", "/wiki/api/v2/footer-comments", "comment on a page")],
2808
+ limitations: ["Storage representation only; no attachments, labels, permissions, page tree moves, CQL search or v1 content API"]
2809
+ },
2810
+ sharepoint: {
2811
+ version: "1.0.0",
2812
+ authentication: "Bearer run-scoped test token (Graph access token shape)",
2813
+ operations: [op("GET", "/v1.0/sites/<site>/lists", "list lists"), op("GET|POST", "/v1.0/sites/<site>/lists/<list>/items", "list (expand=fields, $top) / create item"), op("GET|DELETE", "/v1.0/sites/<site>/lists/<list>/items/<id>", "read / delete", ["404 itemNotFound"]), op("PATCH", "/v1.0/sites/<site>/lists/<list>/items/<id>/fields", "update fields"), op("GET|POST", "/v1.0/sites/<site>/drive/root/children", "list / create folder; name conflicts honour conflictBehavior", ["409 nameAlreadyExists"])],
2814
+ limitations: ["No file content upload or download, versions, permissions, column validation or search"]
2815
+ },
2816
+ snowflake: {
2817
+ version: "1.0.0",
2818
+ authentication: "Bearer run-scoped test token (key-pair JWT shape)",
2819
+ operations: [op("POST", "/api/v2/statements", "execute one single-table SELECT (WHERE =/!= AND, ORDER BY, LIMIT), INSERT \u2026 VALUES, UPDATE \u2026 SET \u2026 WHERE or DELETE; ? bindings supported; values returned as strings", ["422 002003 object does not exist"]), op("GET", "/api/v2/statements/<handle>", "fetch a previous result")],
2820
+ limitations: ["Twins the HTTP SQL API v2; the native drivers (snowflake-sdk, snowflake-connector-python) speak a different wire protocol and must be pointed at the SQL API or a json-collection stand-in", "Each table is a declared collection named in upper case; no joins, functions, aggregates, transactions, DDL, async execution or result partitions"]
2821
+ },
2822
+ netsuite: {
2823
+ version: "1.0.0",
2824
+ authentication: "Bearer run-scoped test token (OAuth 2.0 shape)",
2825
+ operations: [op("GET", "/services/rest/record/v1/<customer|vendor|salesOrder|invoice|vendorBill>", 'list ids and links only (q: field IS "v", limit, offset)'), op("POST", "/services/rest/record/v1/<type>", "create; 204 with Location header and no body", ["400 USER_ERROR", "400 INVALID_KEY_OR_REF"]), op("GET|PATCH|DELETE", "/services/rest/record/v1/<type>/<id>", "read / update (204) / delete (204)", ["404 NONEXISTENT_ID"])],
2826
+ limitations: ["Five record types; no SuiteQL, sublists beyond item lines, subsidiaries, workflows or SuiteScript; X-NetSuite-Idempotency-Key is honoured like Idempotency-Key"]
2827
+ },
2828
+ pagerduty: {
2829
+ version: "1.0.0",
2830
+ authentication: "Token token=<run-scoped test token> for REST; Events API v2 uses the seeded service integration_key as routing_key",
2831
+ operations: [op("POST", "/v2/enqueue", "Events API v2 trigger/acknowledge/resolve; an open dedup_key groups instead of paging again (202)", ["400 invalid event"]), op("GET|POST", "/incidents", "list (statuses[], service_ids[], incident_key) / create; requires From header; open incident_key rejected", ["400 2001"]), op("GET|PUT", "/incidents/<id>", "read / acknowledge or resolve"), op("GET|POST", "/incidents/<id>/notes", "list / add notes"), op("GET", "/services", "list seeded services")],
2832
+ limitations: ["No escalation policies, schedules, on-call, notifications, alert grouping windows or webhooks"]
2833
+ }
2834
+ };
2835
+
1319
2836
  // src/runtime/spec.ts
1320
2837
  var ADAPTER_OPTIONAL_COLLECTIONS = {
1321
- stripe: ["/v1/charges", "/v1/refunds", "/v1/events"]
2838
+ stripe: ["/v1/charges", "/v1/refunds", "/v1/events"],
2839
+ ...ENTERPRISE_OPTIONAL_COLLECTIONS
1322
2840
  };
1323
2841
  var ADAPTER_COLLECTIONS = {
1324
2842
  slack: ["/messages", "/channels"],
@@ -1339,9 +2857,11 @@ var ADAPTER_COLLECTIONS = {
1339
2857
  twilio: ["/2010-04-01/Messages", "/2010-04-01/Calls"],
1340
2858
  composio: ["/connected_accounts", "/tools", "/messages"],
1341
2859
  "google-oauth": ["/clients", "/grants", "/tokens"],
1342
- zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"]
2860
+ zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"],
2861
+ // Enterprise twins: any subset of their optional collections; Snowflake tables are free-form.
2862
+ ...Object.fromEntries(ENTERPRISE_ADAPTERS.filter((a) => !FREEFORM_COLLECTION_ADAPTERS.includes(a)).map((a) => [a, []]))
1343
2863
  };
1344
- var FAULT_TYPES = ["timeout-after-write", "blackhole", "server-error", "duplicate-write"];
2864
+ var FAULT_TYPES = ["timeout-after-write", "blackhole", "server-error", "duplicate-write", "slow-response"];
1345
2865
  var PROPERTY_KINDS = ["unique-per-act", "no-loss", "effect-count"];
1346
2866
  var object2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1347
2867
  var namePattern = /^[a-z][a-z0-9_]{0,39}$/;
@@ -1366,7 +2886,7 @@ function parseWorld(value) {
1366
2886
  if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
1367
2887
  const item = service;
1368
2888
  if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
1369
- 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"].includes(String(item.adapter))) invalid("unsupported service adapter");
2889
+ 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", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter)) invalid("unsupported service adapter");
1370
2890
  const paths = /* @__PURE__ */ new Set();
1371
2891
  for (const entry of item.collections) {
1372
2892
  if (!object2(entry) || typeof entry.path !== "string" || !/^\/[a-zA-Z0-9_/-]+$/.test(entry.path) || entry.path.includes("//") || paths.has(entry.path)) invalid("collection paths must be unique absolute HTTP paths");
@@ -1421,12 +2941,12 @@ function parseWorld(value) {
1421
2941
  }
1422
2942
  }
1423
2943
  if (v.fault !== void 0) {
1424
- if (!object2(v.fault) || !known2(v.fault) || !FAULT_TYPES.includes(v.fault.type)) invalid("fault requires an existing service/path and a supported type: timeout-after-write, blackhole, server-error or duplicate-write");
2944
+ if (!object2(v.fault) || !known2(v.fault) || !FAULT_TYPES.includes(v.fault.type)) invalid("fault requires an existing service/path and a supported type: timeout-after-write, blackhole, server-error, duplicate-write or slow-response");
1425
2945
  const f = v.fault;
1426
2946
  const allowed = ["service", "path", "type"];
1427
2947
  const count = f.count, windowMs = f.windowMs;
1428
- if (f.type === "timeout-after-write") {
1429
- if (!inRangeInt(f.delayMs, 1, 1e4)) invalid("timeout-after-write fault requires delayMs 1\u201310000; the delay is declared application-visible behavior, never seeded");
2948
+ if (f.type === "timeout-after-write" || f.type === "slow-response") {
2949
+ if (!inRangeInt(f.delayMs, 1, 12e4)) invalid(`${f.type} fault requires delayMs 1\u2013120000; the delay is declared application-visible behavior, never seeded`);
1430
2950
  allowed.push("delayMs");
1431
2951
  } else if (f.delayMs !== void 0) invalid(`${f.type} fault does not take delayMs`);
1432
2952
  if (f.type === "server-error") {
@@ -1435,8 +2955,12 @@ function parseWorld(value) {
1435
2955
  allowed.push("count", "windowMs");
1436
2956
  } else {
1437
2957
  if (!["blackhole", "duplicate-write"].includes(f.type) && windowMs !== void 0) invalid(`${f.type} fault does not take windowMs`);
1438
- if (["blackhole", "duplicate-write"].includes(f.type) && count !== void 0 && !inRangeInt(count, 1, 100)) invalid(`${f.type} fault count must be 1\u2013100`);
1439
- if (["blackhole", "duplicate-write"].includes(f.type)) allowed.push("count");
2958
+ if (["blackhole", "duplicate-write", "slow-response"].includes(f.type) && count !== void 0 && !inRangeInt(count, 1, 100)) invalid(`${f.type} fault count must be 1\u2013100`);
2959
+ if (["blackhole", "duplicate-write", "slow-response"].includes(f.type)) allowed.push("count");
2960
+ }
2961
+ if (f.schedule !== void 0) {
2962
+ if (f.type === "timeout-after-write" || !["seeded", "first"].includes(f.schedule)) invalid(`${f.type} fault does not take schedule ${String(f.schedule)}; use seeded or first`);
2963
+ allowed.push("schedule");
1440
2964
  }
1441
2965
  if (Object.keys(f).some((k) => !allowed.includes(k))) invalid(`unknown fault field for ${f.type}`);
1442
2966
  }
@@ -1513,12 +3037,16 @@ function parseWorld(value) {
1513
3037
  }
1514
3038
 
1515
3039
  // src/runtime/http-world.ts
3040
+ var idempotencyKeyDigest = (key) => typeof key === "string" && key ? `sha256:${createHash5("sha256").update(key).digest("hex").slice(0, 16)}` : void 0;
1516
3041
  var HttpWorld = class {
1517
- constructor(spec, seed) {
3042
+ /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
3043
+ constructor(spec, seed, options = {}) {
1518
3044
  this.spec = spec;
3045
+ this.options = options;
1519
3046
  this.seed = normalizeSeed(seed);
1520
3047
  }
1521
3048
  spec;
3049
+ options;
1522
3050
  events = [];
1523
3051
  state = /* @__PURE__ */ Object.create(null);
1524
3052
  credentials = /* @__PURE__ */ Object.create(null);
@@ -1538,6 +3066,11 @@ var HttpWorld = class {
1538
3066
  const source = this.sourceContext.getStore();
1539
3067
  this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...record2 ? { record: structuredClone(record2) } : {}, ...source ? { source } : {} });
1540
3068
  }
3069
+ /** Tags the event just recorded with the request's idempotency key digest. */
3070
+ keyed(key) {
3071
+ const digest = idempotencyKeyDigest(key), last = this.events[this.events.length - 1];
3072
+ if (digest && last) last.idempotencyKey = digest;
3073
+ }
1541
3074
  rejectUnsupported(service, method, path, detail) {
1542
3075
  this.unsupported.push(`${service}: ${method} ${path}: ${detail}`);
1543
3076
  this.record(service, "unsupported", path, detail);
@@ -1555,7 +3088,9 @@ var HttpWorld = class {
1555
3088
  const token = `at_world_${new SeedStream(this.seed, `credential:${service.name}`).nextHex(24)}`;
1556
3089
  const faultOrdinalsFor = fault && fault.service === service.name ? faultOrdinals(fault, this.seed) : null;
1557
3090
  const faultKey = `${fault?.type ?? ""}\0${service.name}\0${fault?.path ?? ""}`;
1558
- const adapterService = service.adapter === "stripe" || service.adapter && REST_ADAPTER_NAMES.includes(service.adapter);
3091
+ const enterprise = isEnterpriseAdapter(service.adapter) ? service.adapter : void 0;
3092
+ const generated = generatedAdapter(service.adapter);
3093
+ const adapterService = service.adapter === "stripe" || !!enterprise || !!generated || service.adapter && REST_ADAPTER_NAMES.includes(service.adapter);
1559
3094
  const restAdapter = service.adapter && REST_ADAPTER_NAMES.includes(service.adapter) ? REST_ADAPTERS[service.adapter] : void 0;
1560
3095
  const altAuth = (headers) => service.adapter === "composio" || service.adapter === "anthropic" ? headers["x-api-key"] === token : service.adapter === "shopify" ? headers["x-shopify-access-token"] === token : service.adapter === "datadog" ? headers["dd-api-key"] === token && headers["dd-application-key"] === token : service.adapter === "discord" ? headers.authorization === `Bot ${token}` : false;
1561
3096
  const data = /* @__PURE__ */ Object.create(null);
@@ -1568,26 +3103,27 @@ var HttpWorld = class {
1568
3103
  const latencyMs = () => latency && this.spec.latency ? this.spec.latency.minMs + latency.nextInt(this.spec.latency.maxMs - this.spec.latency.minMs + 1) : 0;
1569
3104
  const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
1570
3105
  const epoch = this.epoch;
1571
- const send = (code, body) => {
3106
+ const send = (code, body, headers = {}) => {
1572
3107
  if (!res.destroyed) {
1573
- res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {} });
1574
- res.end(JSON.stringify(body));
3108
+ res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
3109
+ res.end(code === 204 || code === 202 && body === null ? void 0 : typeof body === "string" && headers["content-type"] ? body : JSON.stringify(body));
1575
3110
  }
1576
3111
  };
1577
- const respond = (code, body) => {
3112
+ const respond = (code, body, headers) => {
1578
3113
  const ms = latencyMs();
1579
3114
  if (ms <= 0) {
1580
- send(code, body);
3115
+ send(code, body, headers);
1581
3116
  return;
1582
3117
  }
1583
3118
  const timer = setTimeout(() => {
1584
3119
  this.timers.delete(timer);
1585
- if (epoch === this.epoch) send(code, body);
3120
+ if (epoch === this.epoch) send(code, body, headers);
1586
3121
  }, ms);
1587
3122
  this.timers.add(timer);
1588
3123
  };
1589
3124
  const normalPath = (url, method) => {
1590
3125
  const parsed = new URL(url, "http://localhost");
3126
+ if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
1591
3127
  if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
1592
3128
  if (service.adapter === "composio") {
1593
3129
  if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
@@ -1603,6 +3139,21 @@ var HttpWorld = class {
1603
3139
  return parsed.pathname;
1604
3140
  };
1605
3141
  const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
3142
+ const requestKey = req.headers["idempotency-key"];
3143
+ const respondSlowly = (target, operation, code, body, headers) => {
3144
+ if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
3145
+ respond(code, body, headers);
3146
+ return;
3147
+ }
3148
+ this.faultActions++;
3149
+ this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
3150
+ this.keyed(requestKey);
3151
+ const timer = setTimeout(() => {
3152
+ this.timers.delete(timer);
3153
+ if (epoch === this.epoch) respond(code, body, headers);
3154
+ }, fault.delayMs);
3155
+ this.timers.add(timer);
3156
+ };
1606
3157
  const darkFault = () => {
1607
3158
  if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
1608
3159
  const target = normalPath(req.url ?? "/", req.method);
@@ -1613,8 +3164,9 @@ var HttpWorld = class {
1613
3164
  return fault.type;
1614
3165
  };
1615
3166
  try {
1616
- if (req.headers.authorization !== `Bearer ${token}` && !altAuth(req.headers)) {
1617
- this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
3167
+ const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
3168
+ if (!anyCredential && req.headers.authorization !== `Bearer ${token}` && !altAuth(req.headers) && !(enterprise && enterpriseAuth(enterprise, req.headers, req.url ?? "/", token)) && !(generated && generated.auth(req.headers, req.url ?? "/", token))) {
3169
+ this.record(service.name, "auth-denied", req.url ?? "", `invalid test credential (credential headers received: ${Object.keys(req.headers).filter((k) => /auth|key|token|secret/i.test(k)).join(", ") || "none"}; all header names: ${Object.keys(req.headers).join(", ")})`);
1618
3170
  respond(401, { error: "invalid_test_credential" });
1619
3171
  return;
1620
3172
  }
@@ -1624,13 +3176,15 @@ var HttpWorld = class {
1624
3176
  }
1625
3177
  const darkness = darkFault();
1626
3178
  if (darkness === "blackhole") {
1627
- this.record(service.name, "fault", fault.path, `blackhole: request dropped (matched ordinal ${this.candidateCounts.get(faultKey) - 1} of the seeded schedule); nothing committed`);
3179
+ this.record(service.name, "fault", fault.path, `blackhole: request dropped (matched ordinal ${this.candidateCounts.get(faultKey) - 1} of the seeded schedule); nothing committed (${req.method ?? "request"})`);
3180
+ this.keyed(requestKey);
1628
3181
  return;
1629
3182
  }
1630
3183
  if (darkness === "server-error") {
1631
3184
  const windowMs = fault.windowMs ?? 0;
1632
3185
  const delay = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
1633
- this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed`);
3186
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed (${req.method ?? "request"})`);
3187
+ this.keyed(requestKey);
1634
3188
  const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
1635
3189
  if (delay <= 0) {
1636
3190
  respond500();
@@ -1657,7 +3211,7 @@ var HttpWorld = class {
1657
3211
  }
1658
3212
  const slack = service.adapter === "slack";
1659
3213
  const slackMethod = path.replace(/^\/api\//, "");
1660
- let payload;
3214
+ let payload, rawBody;
1661
3215
  if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
1662
3216
  const chunks = [];
1663
3217
  let bytes = 0;
@@ -1671,7 +3225,19 @@ var HttpWorld = class {
1671
3225
  }
1672
3226
  const text = Buffer.concat(chunks).toString("utf8");
1673
3227
  let parsed;
1674
- if (service.adapter === "google-oauth") {
3228
+ const mode = generated?.bodyMode(req.headers["content-type"]);
3229
+ if ((enterprise || generated) && !text.trim()) parsed = {};
3230
+ else if (mode === "form") {
3231
+ const form = new URLSearchParams(text);
3232
+ parsed = {};
3233
+ for (const key2 of new Set(form.keys())) {
3234
+ const all = form.getAll(key2);
3235
+ parsed[key2] = all.length > 1 ? all : all[0];
3236
+ }
3237
+ } else if (mode === "raw") {
3238
+ rawBody = text;
3239
+ parsed = {};
3240
+ } else if (service.adapter === "google-oauth") {
1675
3241
  if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
1676
3242
  respond(400, { error: "invalid_request" });
1677
3243
  return;
@@ -1683,7 +3249,7 @@ var HttpWorld = class {
1683
3249
  }
1684
3250
  parsed = Object.fromEntries(form);
1685
3251
  } else try {
1686
- parsed = (slack || service.adapter === "stripe") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text)) : JSON.parse(text);
3252
+ parsed = (slack || service.adapter === "stripe" || service.adapter === "twilio") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text)) : JSON.parse(text);
1687
3253
  } catch {
1688
3254
  respond(400, { error: "expected_json_object" });
1689
3255
  return;
@@ -1698,9 +3264,10 @@ var HttpWorld = class {
1698
3264
  respond(409, { error: "world_reset" });
1699
3265
  return;
1700
3266
  }
1701
- if (service.adapter === "stripe" || restAdapter) {
3267
+ if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
3268
+ if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
1702
3269
  const params = payload ?? Object.fromEntries(url.searchParams);
1703
- const keyHeader2 = req.headers["idempotency-key"];
3270
+ const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
1704
3271
  const key2 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
1705
3272
  const signature2 = JSON.stringify(params);
1706
3273
  const previous2 = key2 ? keys.get(key2) : void 0;
@@ -1710,28 +3277,35 @@ var HttpWorld = class {
1710
3277
  return;
1711
3278
  }
1712
3279
  this.record(service.name, "replay", path, "same-key response replay", previous2.record);
1713
- respond(previous2.status ?? 200, previous2.record);
3280
+ this.keyed(keyHeader2);
3281
+ respondSlowly(path, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
1714
3282
  return;
1715
3283
  }
1716
- const result = restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, this.events.length + 1) : stripeOperation(req.method ?? "", path, params, data, this.events.length + 1);
3284
+ const query = Object.fromEntries(url.searchParams);
3285
+ const invoke = (sequence) => generated ? generated.handle({ method: req.method ?? "", path, query, headers: req.headers, ...payload ? { body: structuredClone(payload) } : {}, ...rawBody !== void 0 ? { raw: rawBody } : {} }, data, sequence, this.seed) : enterprise ? ENTERPRISE_OPERATIONS[enterprise](req.method ?? "", path, structuredClone(payload ?? {}), query, req.headers, data, sequence) : restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, sequence) : stripeOperation(req.method ?? "", path, params, data, sequence);
3286
+ const headers = (r) => "headers" in r ? r.headers : void 0;
3287
+ const result = invoke(this.events.length + 1);
1717
3288
  if (!result) {
1718
3289
  this.rejectUnsupported(service.name, req.method ?? "", path, `unsupported ${service.adapter} operation or parameters`);
1719
- respond(501, restAdapter ? restUnsupportedBody(service.adapter) : { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the verified AgentTwin Stripe subset" }, forwardedToProduction: false });
3290
+ respond(501, generated ? generated.unsupported(req.method ?? "", path) : enterprise ? ENTERPRISE_UNSUPPORTED[enterprise] : restAdapter ? restUnsupportedBody(service.adapter) : { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the verified AgentTwin Stripe subset" }, forwardedToProduction: false });
1720
3291
  return;
1721
3292
  }
1722
- if (result.operation) this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
1723
- if (key2 && (result.status === 200 || result.status === 201)) keys.set(key2, { body: signature2, record: structuredClone(result.body), status: result.status });
3293
+ if (result.operation) {
3294
+ this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
3295
+ this.keyed(keyHeader2);
3296
+ }
3297
+ if (key2 && (result.status === 200 || result.status === 201 || enterprise && (result.status === 202 || result.status === 204))) keys.set(key2, { body: signature2, record: structuredClone(result.body), status: result.status, ...headers(result) ? { headers: headers(result) } : {} });
1724
3298
  const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key2 && matchesFault(result.collection);
1725
3299
  const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
1726
3300
  if (duplicate2) {
1727
- const second = restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, this.events.length + 1) : stripeOperation(req.method ?? "", path, params, data, this.events.length + 1);
3301
+ const second = invoke(this.events.length + 1);
1728
3302
  if (second?.operation === "write") {
1729
3303
  this.record(service.name, second.operation, second.collection, path, "record" in second ? second.record : second.body);
1730
3304
  this.faultActions++;
1731
3305
  this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result.collection})`);
1732
3306
  } else if (second) {
1733
3307
  this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
1734
- respond(second.status, second.body);
3308
+ respond(second.status, second.body, headers(second));
1735
3309
  return;
1736
3310
  }
1737
3311
  }
@@ -1739,12 +3313,13 @@ var HttpWorld = class {
1739
3313
  this.fired = true;
1740
3314
  this.faultActions++;
1741
3315
  this.record(service.name, "fault", result.collection, `write committed; response delayed ${fault.delayMs}ms`);
3316
+ this.keyed(keyHeader2);
1742
3317
  const timer = setTimeout(() => {
1743
3318
  this.timers.delete(timer);
1744
- respond(result.status, result.body);
3319
+ respond(result.status, result.body, headers(result));
1745
3320
  }, fault.delayMs);
1746
3321
  this.timers.add(timer);
1747
- } else respond(result.status, result.body);
3322
+ } else respondSlowly(result.collection, result.operation ?? "request", result.status, result.body, headers(result));
1748
3323
  return;
1749
3324
  }
1750
3325
  if (slack) {
@@ -1771,12 +3346,12 @@ var HttpWorld = class {
1771
3346
  }
1772
3347
  if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
1773
3348
  this.record(service.name, "read", path, `${data[path].length} records`);
1774
- if (slack && path === "/channels") respond(200, { ok: true, channels: data[path], response_metadata: { next_cursor: "" } });
3349
+ if (slack && path === "/channels") respondSlowly(path, "read", 200, { ok: true, channels: data[path], response_metadata: { next_cursor: "" } });
1775
3350
  else if (slack) {
1776
3351
  const channel = payload?.channel ?? url.searchParams.get("channel");
1777
3352
  if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
1778
- else respond(200, { ok: true, messages: data[path].filter((m) => m.channel === channel), has_more: false });
1779
- } else respond(200, { data: data[path] });
3353
+ else respondSlowly(path, "read", 200, { ok: true, messages: data[path].filter((m) => m.channel === channel), has_more: false });
3354
+ } else respondSlowly(path, "read", 200, { data: data[path] });
1780
3355
  return;
1781
3356
  }
1782
3357
  const body = payload;
@@ -1805,7 +3380,8 @@ var HttpWorld = class {
1805
3380
  return;
1806
3381
  }
1807
3382
  this.record(service.name, "replay", path, "same-key response replay", previous.record);
1808
- respond(200, previous.record);
3383
+ this.keyed(keyHeader);
3384
+ respondSlowly(path, "replay", 200, previous.record);
1809
3385
  return;
1810
3386
  }
1811
3387
  const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
@@ -1818,6 +3394,7 @@ var HttpWorld = class {
1818
3394
  data[path].push(row);
1819
3395
  if (key) keys.set(key, { body: signature, record: row });
1820
3396
  this.record(service.name, "write", path, String(row.id), row);
3397
+ this.keyed(keyHeader);
1821
3398
  if (duplicate) {
1822
3399
  index++;
1823
3400
  while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
@@ -1832,12 +3409,13 @@ var HttpWorld = class {
1832
3409
  this.fired = true;
1833
3410
  this.faultActions++;
1834
3411
  this.record(service.name, "fault", path, `write committed; response delayed ${fault.delayMs}ms`);
3412
+ this.keyed(keyHeader);
1835
3413
  const timer = setTimeout(() => {
1836
3414
  this.timers.delete(timer);
1837
3415
  respond(faultResponse, reply);
1838
3416
  }, fault.delayMs);
1839
3417
  this.timers.add(timer);
1840
- } else respond(faultResponse, reply);
3418
+ } else respondSlowly(path, "write", faultResponse, reply);
1841
3419
  } catch {
1842
3420
  respond(500, { error: "world_request_error" });
1843
3421
  }
@@ -2257,7 +3835,8 @@ var CONTRACTS = {
2257
3835
  { method: "GET", endpoint: "/api/v2/organizations.json", effect: "list seeded organizations", parameters: [], errors: [] }
2258
3836
  ],
2259
3837
  limitations: ["Bounded Support API v2 subset: ticket create/list/get/update plus users and organizations lists", "No macros, views, triggers, audits, attachments, bulk updates or deletes", "Users and organizations are seed-only records; their updates are unsupported", "Unknown fields and operations return 501 and make coverage incomplete"]
2260
- }
3838
+ },
3839
+ ...ENTERPRISE_CONTRACTS
2261
3840
  };
2262
3841
  function operationMatrix(spec) {
2263
3842
  return {
@@ -2268,7 +3847,7 @@ function operationMatrix(spec) {
2268
3847
  name: s.name,
2269
3848
  adapter: s.adapter ?? "json-collection",
2270
3849
  version: CONTRACTS[s.adapter ?? "json-collection"].version,
2271
- operations: s.adapter === "slack" ? CONTRACTS.slack.operations : s.adapter === "stripe" ? CONTRACTS.stripe.operations : s.adapter && s.adapter !== "json-collection" ? CONTRACTS[s.adapter].operations : s.collections.flatMap((c) => CONTRACTS["json-collection"].operations.map((op) => ({ ...op, endpoint: c.path })))
3850
+ operations: s.adapter === "slack" ? CONTRACTS.slack.operations : s.adapter === "stripe" ? CONTRACTS.stripe.operations : s.adapter && s.adapter !== "json-collection" ? CONTRACTS[s.adapter].operations : s.collections.flatMap((c) => CONTRACTS["json-collection"].operations.map((op2) => ({ ...op2, endpoint: c.path })))
2272
3851
  })) ?? []
2273
3852
  };
2274
3853
  }