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.
- package/README.md +7 -9
- package/dist/api.js +9240 -1135
- package/dist/cli.js +26 -21
- package/dist/dashboard/assets/next/static/chunks/1250-7571b1a697f6bb4a.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/2868-424d32cfc8ae81c9.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/9675.d833ca9b2d89cf8a.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-9390b6ace45cc1ff.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/about/page-f7d9ffd4f6138e0e.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/auth/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/blog/layout-1e8a656895b65474.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/compare/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/contact/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-2d0408d8f22d7921.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-9c11295678539a5f.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/developers/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-f9fca2c08f779fa0.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-220e50b34fd67668.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/guides/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/layout-cd911546738f01ed.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/not-found-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/page-6d01bfbee0186f28.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/pricing/page-1200305185e4183f.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/privacy/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/{layout-a5cf565e017886d3.js → layout-a1c12faf8094e40e.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/page-07c8054d57c9089b.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-aa11ba1b9100c0ca.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/webpack-40324749d289e4a5.js +1 -0
- package/dist/dashboard/assets/next/static/css/1d1b20bd9fb076d4.css +1 -0
- package/dist/dashboard/assets/next/static/css/2c38dfe54afd9bb6.css +1 -0
- package/dist/dashboard/assets/next/static/css/39133c9a03c8edb8.css +1 -0
- package/dist/dashboard/assets/next/static/css/{18afa3e32331c41d.css → 42045de5f39b50ca.css} +1 -1
- package/dist/dashboard/assets/next/static/css/{77c0c440ebb56bc4.css → 423c6df577acd447.css} +1 -1
- package/dist/dashboard/assets/next/static/css/{d131a6499fe6cf19.css → 4bbe78c2fe206b92.css} +1 -1
- package/dist/dashboard/assets/next/static/css/7109685b391c1c46.css +1 -0
- package/dist/dashboard/assets/next/static/css/96134c7d160c4fc3.css +1 -0
- package/dist/dashboard/assets/next/static/css/b068ffd8e6f22102.css +1 -0
- package/dist/dashboard/assets/next/static/css/bbce83b7ab716064.css +1 -0
- package/dist/dashboard/index.html +6 -2
- package/dist/engine.js +21898 -10960
- package/dist/gateway.js +9254 -1142
- package/dist/worker.js +1641 -62
- package/dist/world-host.js +2380 -80
- package/package.json +18 -3
- package/dist/dashboard/assets/next/static/chunks/1482.c28f7cd0f92885c1.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/2868-b80a3af454408935.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/3056.ffa9a4d44a274b29.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/5531-fde254dbd21c3153.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/9675.14739028910476e4.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-43db8aef3fa81958.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/about/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/auth/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/blog/layout-563d8763d65d66b5.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/compare/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/contact/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-1afe915ed22ac5ed.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-0eb9937f1e5e9c1e.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/developers/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-1800a8f06aeb4acb.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-1fd02494889ae794.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/guides/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/layout-993a96283a3ceb07.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/page-2e622bb9a3459541.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/pricing/page-40f352fe5093a0ff.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/privacy/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/page-3905446ec0206fb5.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-3f5dbcdbf95bb2fc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/webpack-d20e6727e78cdbc8.js +0 -1
- package/dist/dashboard/assets/next/static/css/7263c178012081d9.css +0 -1
- package/dist/dashboard/assets/next/static/css/d5d08788c3435fdf.css +0 -1
- /package/dist/dashboard/assets/next/static/{JSI_XeT8MHbUAs8aF59pe → 5ub3D2yzS8DE7w2qZd1nv}/_buildManifest.js +0 -0
- /package/dist/dashboard/assets/next/static/{JSI_XeT8MHbUAs8aF59pe → 5ub3D2yzS8DE7w2qZd1nv}/_ssgManifest.js +0 -0
package/dist/world-host.js
CHANGED
|
@@ -74,7 +74,29 @@ if(originalFetch)globalThis.fetch=async function(input,init){
|
|
|
74
74
|
const target=route?route.endpoint+url.pathname+url.search:url.href;
|
|
75
75
|
return originalFetch(new Request(target,request),{headers,redirect:'error'});
|
|
76
76
|
};
|
|
77
|
-
|
|
77
|
+
const plainHttp={request:http.request,get:http.get};
|
|
78
|
+
const loopback=host=>['127.0.0.1','localhost','::1','[::1]'].includes(host);
|
|
79
|
+
function blockNode(origin){if(!blockedOrigins.has(origin)&&blockedOrigins.size<100){blockedOrigins.add(origin);const violation={origin:origin.slice(0,2048),reason:'unmapped-http-origin'};if(config.stdioViolations)process.stdout.write('\n\x1eAGENTTWIN_FETCH_V1:'+JSON.stringify({kind:'violation',...violation})+'\n');else require('node:fs').appendFileSync(config.violationsPath,JSON.stringify(violation)+'\n');}throw new Error('AgentTwin blocked a request to an unmapped origin: '+origin);}
|
|
80
|
+
// SDKs on node:http/https (Stripe, Slack via axios) reach mapped vendor origins only through their twin.
|
|
81
|
+
function routeNode(method,route,url,options,index,args){
|
|
82
|
+
const target=new URL(route.endpoint),headers={};
|
|
83
|
+
const raw=Array.isArray(options.headers)?Object.fromEntries(options.headers.reduce((pairs,item,i,all)=>i%2?pairs:[...pairs,[item,all[i+1]]],[])):options.headers||{};
|
|
84
|
+
for(const [key,value] of Object.entries(raw))if(!['authorization','cookie','proxy-authorization','host'].includes(key.toLowerCase()))headers[key]=value;
|
|
85
|
+
headers.authorization='Bearer '+route.token;headers.host=target.host;
|
|
86
|
+
const location=source();if(location)headers['x-agenttwin-source']=location;
|
|
87
|
+
const path=index===1?url.pathname+url.search:(options.path||'/');
|
|
88
|
+
const {agent:_agent,servername:_servername,createConnection:_connection,...rest}=options;
|
|
89
|
+
const updated={...rest,protocol:'http:',hostname:target.hostname,host:target.hostname,port:target.port,path,headers};
|
|
90
|
+
const tail=index===1?args.slice(args[1]&&typeof args[1]==='object'?2:1):args.slice(1);
|
|
91
|
+
const req=plainHttp[method].call(http,updated,...tail);
|
|
92
|
+
// Plain-HTTP twin: clients that write only after 'secureConnect' (stripe-node) need the handshake signal.
|
|
93
|
+
if(url.protocol==='https:')req.once('socket',socket=>{if(socket.connecting)socket.once('connect',()=>socket.emit('secureConnect'));else socket.emit('secureConnect');});
|
|
94
|
+
return req;
|
|
95
|
+
}
|
|
96
|
+
for(const mod of [http,https])for(const method of ['request','get']){const original=mod[method];mod[method]=function(...args){let options,url,index;try{if(typeof args[0]==='string'||args[0] instanceof URL){url=new URL(args[0]);index=1;options=args[1]&&typeof args[1]==='object'?args[1]:{};}else{index=0;options=args[0]||{};url=new URL((options.protocol||(mod===https?'https:':'http:'))+'//'+(options.hostname||options.host||'localhost')+(options.port?':'+options.port:''));}}catch{return original.apply(this,args);}
|
|
97
|
+
if(config.routing&&Object.hasOwn(config.routes,url.origin))return routeNode(method,config.routes[url.origin],url,options,index,args);
|
|
98
|
+
if(config.routing&&!origins.has(url.origin)&&!loopback(url.hostname))blockNode(url.origin);
|
|
99
|
+
if(!origins.has(url.origin))return original.apply(this,args);const location=source();if(!location)return original.apply(this,args);const headers=Array.isArray(options.headers)?[...options.headers,'x-agenttwin-source',location]:{...options.headers,'x-agenttwin-source':location};const updated={...options,headers};if(index===1&&typeof args[1]==='function')args.splice(1,0,updated);else args[index]=updated;return original.apply(this,args);};}
|
|
78
100
|
require('node:module').syncBuiltinESMExports();
|
|
79
101
|
`;
|
|
80
102
|
await writeFile(path, hook, { mode: 384 });
|
|
@@ -177,9 +199,9 @@ function stripeOperation(method, path, params, data, sequence) {
|
|
|
177
199
|
const match = /^\/v1\/(customers|payment_intents)(?:\/([^/]+))?(?:\/(confirm))?$/.exec(path);
|
|
178
200
|
if (!match || !["GET", "POST"].includes(method)) return void 0;
|
|
179
201
|
const [, resource, id, action] = match, collection = `/v1/${resource}`, rows2 = data[collection];
|
|
180
|
-
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;
|
|
202
|
+
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;
|
|
181
203
|
if (!allowed || resource === "customers" && action || resource === "payment_intents" && method === "GET" && !id) return void 0;
|
|
182
|
-
if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
|
|
204
|
+
if (Object.keys(params).some((k) => !allowed.includes(k.replace(/\[.*$/, "")))) return void 0;
|
|
183
205
|
if (method === "GET" && !id) {
|
|
184
206
|
const limit = params.limit === void 0 ? 10 : Number(params.limit);
|
|
185
207
|
if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...error(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
|
|
@@ -202,13 +224,28 @@ function stripeOperation(method, path, params, data, sequence) {
|
|
|
202
224
|
row.last_payment_error = payment === "pm_card_chargeDeclined" ? { code: "card_declined", decline_code: "generic_decline", message: "Your card was declined." } : null;
|
|
203
225
|
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" };
|
|
204
226
|
}
|
|
227
|
+
const form = Object.fromEntries(Object.entries(params).map(([k, v]) => [k, v])), nested = {};
|
|
228
|
+
for (const [key, value] of Object.entries(form)) {
|
|
229
|
+
const m = /^([^[]+)((?:\[[^\]]*\])+)$/.exec(key);
|
|
230
|
+
if (!m) {
|
|
231
|
+
nested[key] = value;
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
const path2 = [m[1], ...[...m[2].matchAll(/\[([^\]]*)\]/g)].map((x) => x[1])];
|
|
235
|
+
let cursor = nested;
|
|
236
|
+
for (const part of path2.slice(0, -1)) {
|
|
237
|
+
if (typeof cursor[part] !== "object" || cursor[part] === null) cursor[part] = {};
|
|
238
|
+
cursor = cursor[part];
|
|
239
|
+
}
|
|
240
|
+
cursor[path2.at(-1)] = value;
|
|
241
|
+
}
|
|
205
242
|
const prefix = resource === "customers" ? "cus" : "pi";
|
|
206
243
|
let suffix = sequence;
|
|
207
244
|
while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
|
|
208
245
|
const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: 17e8, livemode: false };
|
|
209
246
|
if (resource === "customers") {
|
|
210
247
|
if (params.email !== void 0 && typeof params.email !== "string") return { ...error(400, "parameter_invalid", "email must be a string", "email"), collection };
|
|
211
|
-
Object.assign(created2, { email: null, name: null, description: null, ...
|
|
248
|
+
Object.assign(created2, { email: null, name: null, description: null, metadata: {}, ...nested });
|
|
212
249
|
} else {
|
|
213
250
|
const amount = Number(params.amount);
|
|
214
251
|
if (!Number.isSafeInteger(amount) || amount < 1) return { ...error(400, "parameter_invalid_integer", "amount must be a positive integer", "amount"), collection };
|
|
@@ -221,6 +258,10 @@ function stripeOperation(method, path, params, data, sequence) {
|
|
|
221
258
|
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 });
|
|
222
259
|
}
|
|
223
260
|
if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
|
|
261
|
+
if (resource === "payment_intents") {
|
|
262
|
+
for (const key of ["description", "receipt_email", "statement_descriptor", "capture_method"]) if (nested[key] !== void 0) created2[key] = nested[key];
|
|
263
|
+
}
|
|
264
|
+
if (resource === "payment_intents") created2.metadata = typeof nested.metadata === "object" && nested.metadata ? nested.metadata : {};
|
|
224
265
|
rows2.push(created2);
|
|
225
266
|
if (created2.status === "succeeded") chargeFor(created2, data, sequence);
|
|
226
267
|
const declined = resource === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
|
|
@@ -235,7 +276,11 @@ var init_stripe_adapter = __esm({
|
|
|
235
276
|
});
|
|
236
277
|
|
|
237
278
|
// src/runtime/llm-adapter.ts
|
|
279
|
+
function hasToolResult(messages) {
|
|
280
|
+
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")));
|
|
281
|
+
}
|
|
238
282
|
function lastUserText(messages) {
|
|
283
|
+
if (typeof messages === "string") return messages;
|
|
239
284
|
if (!Array.isArray(messages)) return "";
|
|
240
285
|
const user = [...messages].reverse().find((m) => m && typeof m === "object" && m.role === "user");
|
|
241
286
|
const content = user?.content;
|
|
@@ -243,10 +288,10 @@ function lastUserText(messages) {
|
|
|
243
288
|
if (Array.isArray(content)) return content.map((part) => part && typeof part === "object" && typeof part.text === "string" ? part.text : "").join("\n");
|
|
244
289
|
return "";
|
|
245
290
|
}
|
|
246
|
-
function nextScripted(data, prompt) {
|
|
291
|
+
function nextScripted(data, prompt, toolResult = false) {
|
|
247
292
|
const scripts = data["/responses"];
|
|
248
293
|
if (!scripts) return void 0;
|
|
249
|
-
const usable = (row) => !row.used || row.repeat === true;
|
|
294
|
+
const usable = (row) => (!row.used || row.repeat === true) && (typeof row.afterToolResult !== "boolean" || row.afterToolResult === toolResult);
|
|
250
295
|
const matched = scripts.find((row) => usable(row) && typeof row.match === "string" && prompt.includes(row.match));
|
|
251
296
|
const script = matched ?? scripts.find((row) => usable(row) && row.match === void 0);
|
|
252
297
|
if (!script) return void 0;
|
|
@@ -272,10 +317,11 @@ function parsedInput(value) {
|
|
|
272
317
|
function openaiOperation(method, path, params, _headers, data, sequence) {
|
|
273
318
|
const collection = "/requests";
|
|
274
319
|
if (path === "/v1/requests" || path === "/requests") return method === "GET" ? { status: 200, body: { object: "list", data: data[collection] }, collection, operation: "read" } : void 0;
|
|
320
|
+
if (method === "POST" && ["/v1/responses", "/responses"].includes(path)) return openaiResponsesOperation(params, data, sequence);
|
|
275
321
|
if (method !== "POST" || !["/v1/chat/completions", "/chat/completions"].includes(path)) return void 0;
|
|
276
322
|
if (params.stream === true || !Array.isArray(params.messages)) return void 0;
|
|
277
323
|
const prompt = lastUserText(params.messages);
|
|
278
|
-
const script = nextScripted(data, prompt);
|
|
324
|
+
const script = nextScripted(data, prompt, hasToolResult(params.messages));
|
|
279
325
|
if (!script) return void 0;
|
|
280
326
|
const id = `chatcmpl_at_${sequence}`;
|
|
281
327
|
const toolCalls = script.calls.map((call, index) => ({ id: `call_at_${sequence}_${index}`, type: "function", function: { name: String(call.name), arguments: arg(call.arguments) } }));
|
|
@@ -291,13 +337,40 @@ function openaiOperation(method, path, params, _headers, data, sequence) {
|
|
|
291
337
|
};
|
|
292
338
|
return { status: 200, body, collection, record: entry, operation: "write" };
|
|
293
339
|
}
|
|
340
|
+
function openaiResponsesOperation(params, data, sequence) {
|
|
341
|
+
const collection = "/requests";
|
|
342
|
+
if (params.stream === true || typeof params.input !== "string" && !Array.isArray(params.input)) return void 0;
|
|
343
|
+
const prompt = lastUserText(params.input);
|
|
344
|
+
const script = nextScripted(data, prompt);
|
|
345
|
+
if (!script) return void 0;
|
|
346
|
+
const id = `resp_at_${sequence}`;
|
|
347
|
+
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" }));
|
|
348
|
+
const entry = record(data, "openai", params.model, prompt, id, calls.map((call) => call.name));
|
|
349
|
+
if (!entry) return { status: 429, body: { error: { type: "world_capacity", message: "World record capacity reached" } }, collection };
|
|
350
|
+
const message = script.content !== null ? [{ type: "message", id: `msg_at_${sequence}`, role: "assistant", status: "completed", content: [{ type: "output_text", text: script.content, annotations: [] }] }] : [];
|
|
351
|
+
const body = {
|
|
352
|
+
id,
|
|
353
|
+
object: "response",
|
|
354
|
+
created_at: 17e8,
|
|
355
|
+
status: "completed",
|
|
356
|
+
model: params.model ?? "agenttwin-scripted",
|
|
357
|
+
error: null,
|
|
358
|
+
incomplete_details: null,
|
|
359
|
+
output: [...message, ...calls],
|
|
360
|
+
parallel_tool_calls: true,
|
|
361
|
+
tool_choice: params.tool_choice ?? "auto",
|
|
362
|
+
tools: Array.isArray(params.tools) ? params.tools : [],
|
|
363
|
+
usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } }
|
|
364
|
+
};
|
|
365
|
+
return { status: 200, body, collection, record: entry, operation: "write" };
|
|
366
|
+
}
|
|
294
367
|
function anthropicOperation(method, path, params, _headers, data, sequence) {
|
|
295
368
|
const collection = "/requests";
|
|
296
369
|
if (path === "/v1/requests" || path === "/requests") return method === "GET" ? { status: 200, body: { data: data[collection] }, collection, operation: "read" } : void 0;
|
|
297
370
|
if (method !== "POST" || !["/v1/messages", "/messages"].includes(path)) return void 0;
|
|
298
371
|
if (params.stream === true || !Array.isArray(params.messages)) return void 0;
|
|
299
372
|
const prompt = lastUserText(params.messages);
|
|
300
|
-
const script = nextScripted(data, prompt);
|
|
373
|
+
const script = nextScripted(data, prompt, hasToolResult(params.messages));
|
|
301
374
|
if (!script) return void 0;
|
|
302
375
|
const id = `msg_at_${sequence}`;
|
|
303
376
|
const toolUses = script.calls.map((call, index) => ({ type: "tool_use", id: `toolu_at_${sequence}_${index}`, name: String(call.name), input: parsedInput(call.arguments) }));
|
|
@@ -426,10 +499,10 @@ function parseGmailRaw(raw) {
|
|
|
426
499
|
if (headers.some((h) => h.name.toLowerCase() === match[1].toLowerCase())) return { error: "Duplicate MIME headers are outside the verified subset", unsupported: true };
|
|
427
500
|
headers.push({ name: match[1], value: match[2] });
|
|
428
501
|
}
|
|
429
|
-
const
|
|
430
|
-
if (!
|
|
431
|
-
if (
|
|
432
|
-
if (
|
|
502
|
+
const header3 = (name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
|
|
503
|
+
if (!header3("to")) return { error: "MIME To header is required", unsupported: false };
|
|
504
|
+
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 };
|
|
505
|
+
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 };
|
|
433
506
|
const text = mime.slice(boundary + 4);
|
|
434
507
|
return { headers, text, encodedBody: Buffer.from(text).toString("base64url"), bytes: bytes.length };
|
|
435
508
|
}
|
|
@@ -579,11 +652,11 @@ function linearOperation(method, path, params, _headers, data, sequence) {
|
|
|
579
652
|
}
|
|
580
653
|
if (root[1] === "issueCreate") {
|
|
581
654
|
if (!isObject(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
|
|
582
|
-
if (Object.keys(input).some((k) => !["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k))) return void 0;
|
|
655
|
+
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;
|
|
583
656
|
if (typeof input.title !== "string" || !input.title) return { status: 200, body: { data: null, errors: [{ message: "Issue title required" }] }, collection: "/issues" };
|
|
584
|
-
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() };
|
|
657
|
+
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() };
|
|
585
658
|
rows(data, "/issues").push(issue);
|
|
586
|
-
return write(200, "/issues", { data: { issueCreate: { success: true, issue: structuredClone(issue) } } }, issue);
|
|
659
|
+
return write(200, "/issues", { data: { issueCreate: { success: true, lastSyncId: sequence, issue: structuredClone(issue) } } }, issue);
|
|
587
660
|
}
|
|
588
661
|
if (root[1] === "issueUpdate") {
|
|
589
662
|
if (!isObject(input) || arg2("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
|
|
@@ -738,7 +811,7 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
|
|
|
738
811
|
return ok(collection, { total: rows(data, collection).length, results: page.map((r) => hubspotEnvelope(r)) });
|
|
739
812
|
}
|
|
740
813
|
if (method !== "POST") return void 0;
|
|
741
|
-
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 ${object4}`, category: "VALIDATION_ERROR" });
|
|
814
|
+
if (Object.keys(params).some((k) => k !== "properties" && k !== "associations") || params.associations !== void 0 && !Array.isArray(params.associations) || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: `Invalid input JSON on line 1: Unable to process JSON: properties required for ${object4}`, category: "VALIDATION_ERROR" });
|
|
742
815
|
const record3 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso(), updatedAt: iso() };
|
|
743
816
|
rows(data, collection).push(record3);
|
|
744
817
|
return created(collection, hubspotEnvelope(record3), record3);
|
|
@@ -932,7 +1005,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
|
|
|
932
1005
|
if (!match) return void 0;
|
|
933
1006
|
const [, calendar, eventId] = match;
|
|
934
1007
|
if (calendar !== "primary") return googleError(EVENTS, 404, `Not Found: no twin state for calendar ${calendar}`);
|
|
935
|
-
const
|
|
1008
|
+
const scalar2 = (value) => ["summary", "description", "location"].filter((k) => params[k] !== void 0 && str(params[k]) === void 0);
|
|
936
1009
|
const meetingField = (value) => value !== void 0 && !Array.isArray(value) && !isObject(value);
|
|
937
1010
|
if (!eventId) {
|
|
938
1011
|
if (method === "GET") {
|
|
@@ -973,7 +1046,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
|
|
|
973
1046
|
if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
|
|
974
1047
|
if (typeof params.summary !== "string" || !params.summary) return fail(400, "Event summary is required.");
|
|
975
1048
|
if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
|
|
976
|
-
const scalarBad =
|
|
1049
|
+
const scalarBad = scalar2(params);
|
|
977
1050
|
if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
|
|
978
1051
|
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() };
|
|
979
1052
|
rowsIn(data, EVENTS).push(event2);
|
|
@@ -985,7 +1058,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
|
|
|
985
1058
|
if (method === "PATCH") {
|
|
986
1059
|
if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
|
|
987
1060
|
if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
|
|
988
|
-
const scalarBad =
|
|
1061
|
+
const scalarBad = scalar2(params);
|
|
989
1062
|
if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
|
|
990
1063
|
for (const [k, v] of Object.entries(params)) if (["summary", "description", "location", "start", "end", "attendees", "status"].includes(k)) event[k] = structuredClone(v);
|
|
991
1064
|
event.updated = iso();
|
|
@@ -1172,7 +1245,7 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
|
|
|
1172
1245
|
const collection = `/2010-04-01/${resource}`;
|
|
1173
1246
|
const records = rowsIn(data, collection);
|
|
1174
1247
|
const fail = (status, code, message) => ({ status, body: { status, code, message, more_info: "" }, collection });
|
|
1175
|
-
const
|
|
1248
|
+
const stamp2 = () => {
|
|
1176
1249
|
const [date, time] = iso().split("T");
|
|
1177
1250
|
return `${date} ${time.slice(0, 8)}`;
|
|
1178
1251
|
};
|
|
@@ -1183,7 +1256,7 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
|
|
|
1183
1256
|
if (missing.length) return fail(400, missing.length === allowed.length ? "21211" : "21606", `No parameter provided for ${allowed.filter((k) => missing.includes(k)).join(", ")}`);
|
|
1184
1257
|
const prefix = resource === "Messages" ? "SM" : "CA";
|
|
1185
1258
|
const sid = `${prefix}${sha(`${prefix.toLowerCase()}:${sequence}:${accountSid}`).slice(0, 32)}`;
|
|
1186
|
-
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:
|
|
1259
|
+
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` };
|
|
1187
1260
|
records.push(record2);
|
|
1188
1261
|
return created(collection, structuredClone(record2), record2);
|
|
1189
1262
|
}
|
|
@@ -1359,6 +1432,7 @@ function normalizeSeed(seed) {
|
|
|
1359
1432
|
}
|
|
1360
1433
|
function faultOrdinals(selection, seed) {
|
|
1361
1434
|
const count = selection.type === "timeout-after-write" ? 1 : selection.count ?? 1;
|
|
1435
|
+
if (selection.schedule === "first") return Array.from({ length: Math.min(count, FAULT_SCHEDULE_WINDOW) }, (_, i) => i);
|
|
1362
1436
|
const stream = new SeedStream(seed, `fault:${selection.type}:${selection.service}:${selection.path}`);
|
|
1363
1437
|
const all = Array.from({ length: FAULT_SCHEDULE_WINDOW }, (_, i) => i);
|
|
1364
1438
|
for (let i = all.length - 1; i > 0; i--) {
|
|
@@ -1423,6 +1497,1498 @@ var init_postgres_clock = __esm({
|
|
|
1423
1497
|
}
|
|
1424
1498
|
});
|
|
1425
1499
|
|
|
1500
|
+
// src/runtime/compiler/model.ts
|
|
1501
|
+
function fromPattern(pattern, stream) {
|
|
1502
|
+
let p = pattern.replace(/^\^/, "").replace(/\$$/, "");
|
|
1503
|
+
let out = "";
|
|
1504
|
+
const pick = (chars) => chars[stream.nextInt(chars.length)];
|
|
1505
|
+
const expand = (cls) => {
|
|
1506
|
+
let chars = "";
|
|
1507
|
+
for (let i = 0; i < cls.length; i++) {
|
|
1508
|
+
if (cls[i] === "\\" && cls[i + 1]) {
|
|
1509
|
+
const c = cls[++i];
|
|
1510
|
+
chars += c === "d" ? "0123456789" : c === "w" ? "abcdefghijklmnopqrstuvwxyz0123456789" : c;
|
|
1511
|
+
continue;
|
|
1512
|
+
}
|
|
1513
|
+
if (cls[i + 1] === "-" && cls[i + 2]) {
|
|
1514
|
+
for (let c = cls.charCodeAt(i); c <= cls.charCodeAt(i + 2); c++) chars += String.fromCharCode(c);
|
|
1515
|
+
i += 2;
|
|
1516
|
+
continue;
|
|
1517
|
+
}
|
|
1518
|
+
chars += cls[i];
|
|
1519
|
+
}
|
|
1520
|
+
return chars;
|
|
1521
|
+
};
|
|
1522
|
+
for (let guard = 0; p && guard < 200; guard++) {
|
|
1523
|
+
let chars;
|
|
1524
|
+
if (p[0] === "[") {
|
|
1525
|
+
const end = p.indexOf("]");
|
|
1526
|
+
if (end < 0) return;
|
|
1527
|
+
chars = expand(p.slice(1, end));
|
|
1528
|
+
p = p.slice(end + 1);
|
|
1529
|
+
} else if (p[0] === "\\") {
|
|
1530
|
+
const c = p[1];
|
|
1531
|
+
chars = c === "d" ? "0123456789" : c === "w" ? "abcdefghijklmnopqrstuvwxyz0123456789" : c === "-" || c === "." || c === "_" ? c : "";
|
|
1532
|
+
if (!chars) return;
|
|
1533
|
+
p = p.slice(2);
|
|
1534
|
+
} else if (p[0] === "(") {
|
|
1535
|
+
const end = p.indexOf(")");
|
|
1536
|
+
const options = p.slice(1, end).replace(/^\?:/, "").split("|");
|
|
1537
|
+
if (end < 0 || options.some((o) => !/^[A-Za-z0-9_-]*$/.test(o))) return;
|
|
1538
|
+
chars = "";
|
|
1539
|
+
p = p.slice(end + 1);
|
|
1540
|
+
if (p[0] === "?") {
|
|
1541
|
+
p = p.slice(1);
|
|
1542
|
+
continue;
|
|
1543
|
+
}
|
|
1544
|
+
out += options[stream.nextInt(options.length)];
|
|
1545
|
+
continue;
|
|
1546
|
+
} else if ("|?.".includes(p[0])) return;
|
|
1547
|
+
else {
|
|
1548
|
+
chars = p[0];
|
|
1549
|
+
p = p.slice(1);
|
|
1550
|
+
}
|
|
1551
|
+
let count = 1;
|
|
1552
|
+
const q = p.match(/^\{(\d+)(?:,(\d*))?\}|^[+*]/);
|
|
1553
|
+
if (q) {
|
|
1554
|
+
p = p.slice(q[0].length);
|
|
1555
|
+
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]);
|
|
1556
|
+
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);
|
|
1557
|
+
}
|
|
1558
|
+
if (!chars.length) return;
|
|
1559
|
+
for (let i = 0; i < count; i++) out += pick(chars);
|
|
1560
|
+
}
|
|
1561
|
+
return p ? void 0 : out;
|
|
1562
|
+
}
|
|
1563
|
+
function fakeValue(schema, name, stream, depth = 0, sequence = 0) {
|
|
1564
|
+
if (!schema) return void 0;
|
|
1565
|
+
if (schema.example !== void 0 && depth > 0 && typeof schema.example !== "object") return schema.example;
|
|
1566
|
+
if (schema.enum?.length) return schema.enum[stream.nextInt(schema.enum.length)];
|
|
1567
|
+
const n = name.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
1568
|
+
const type = schema.type ?? (schema.properties ? "object" : schema.items ? "array" : "string");
|
|
1569
|
+
if (type === "object") {
|
|
1570
|
+
if (depth > 3 || schema["x-recursive"]) return {};
|
|
1571
|
+
const out = {};
|
|
1572
|
+
for (const [key, child] of Object.entries(schema.properties ?? {})) {
|
|
1573
|
+
const v = fakeValue(child, key, stream, depth + 1, sequence);
|
|
1574
|
+
if (v !== void 0) out[key] = v;
|
|
1575
|
+
}
|
|
1576
|
+
return out;
|
|
1577
|
+
}
|
|
1578
|
+
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)];
|
|
1579
|
+
if (type === "boolean") return /^(is)?(deleted|archived|disabled|test)$/.test(n) ? false : stream.nextInt(2) === 1;
|
|
1580
|
+
if (type === "integer" || type === "number") {
|
|
1581
|
+
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);
|
|
1582
|
+
if (/created|updated|timestamp|date|time/.test(n) && max > 1e6) return Math.floor(twinClock(sequence).getTime() / 1e3);
|
|
1583
|
+
const v = min + stream.nextInt(Math.max(1, Math.floor(max - min) + 1));
|
|
1584
|
+
return type === "number" && /rate|ratio|percent|score/.test(n) ? Math.round(stream.next() * 1e3) / 1e3 : v;
|
|
1585
|
+
}
|
|
1586
|
+
if (schema.pattern) {
|
|
1587
|
+
const v = fromPattern(schema.pattern, stream);
|
|
1588
|
+
if (v !== void 0) return v;
|
|
1589
|
+
}
|
|
1590
|
+
const f = schema.format ?? "";
|
|
1591
|
+
if (f === "date-time-rfc-2822") return twinClock(sequence).toUTCString();
|
|
1592
|
+
if (f === "date-time" || /_at$|At$|^date|date$|time$|timestamp/.test(name)) return f === "date" ? twinClock(sequence).toISOString().slice(0, 10) : twinClock(sequence).toISOString();
|
|
1593
|
+
if (/^num|count$|segments|quantity/.test(n)) return String(1 + stream.nextInt(3));
|
|
1594
|
+
if (/price|amount|cost|fee/.test(n)) return (stream.nextInt(1e4) / 100).toFixed(2);
|
|
1595
|
+
if (/^uri$|path$/.test(n)) return `/${n}/${stream.nextHex(6)}`;
|
|
1596
|
+
if (f === "date") return twinClock(sequence).toISOString().slice(0, 10);
|
|
1597
|
+
if (f === "email" || n.includes("email")) return `${FIRST[stream.nextInt(10)].toLowerCase()}.${LAST[stream.nextInt(10)].toLowerCase()}@example.com`;
|
|
1598
|
+
if (f === "uri" || f === "url" || /url$|uri$|link$|website|href/.test(n)) return `https://example.com/${n || "resource"}/${stream.nextHex(4)}`;
|
|
1599
|
+
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)}`;
|
|
1600
|
+
if (/phone|^to$|^from$|number/.test(n)) return `+1555${String(1e6 + stream.nextInt(8999999))}`;
|
|
1601
|
+
if (/firstname|givenname/.test(n)) return FIRST[stream.nextInt(10)];
|
|
1602
|
+
if (/lastname|surname|familyname/.test(n)) return LAST[stream.nextInt(10)];
|
|
1603
|
+
if (/company|organization|org|account(name)?$/.test(n)) return COMPANY[stream.nextInt(10)];
|
|
1604
|
+
if (/^name$|fullname|displayname|username/.test(n)) return `${FIRST[stream.nextInt(10)]} ${LAST[stream.nextInt(10)]}`;
|
|
1605
|
+
if (/currency/.test(n)) return "usd";
|
|
1606
|
+
if (/country/.test(n)) return "US";
|
|
1607
|
+
if (/status|state|stage/.test(n)) return "active";
|
|
1608
|
+
if (/^id$|id$|sid$|key$|token$/.test(n)) return `${n.replace(/id$|sid$|key$|token$/, "").slice(0, 4) || "id"}_${stream.nextHex(6)}`;
|
|
1609
|
+
if (/title|subject|summary|dealname|^name/.test(n)) return `${COMPANY[stream.nextInt(10)]} ${WORDS[stream.nextInt(10)]}`;
|
|
1610
|
+
if (/description|body|text|message|content|note|comment/.test(n)) return `Synthetic ${WORDS[stream.nextInt(10)]} note ${stream.nextHex(2)}`;
|
|
1611
|
+
const s = `${n || "value"}_${stream.nextHex(3)}`;
|
|
1612
|
+
return schema.maxLength && s.length > schema.maxLength ? s.slice(0, schema.maxLength) : s;
|
|
1613
|
+
}
|
|
1614
|
+
var tierLabel, FIRST, LAST, COMPANY, WORDS, twinClock, streamFor, normName, singular;
|
|
1615
|
+
var init_model = __esm({
|
|
1616
|
+
"src/runtime/compiler/model.ts"() {
|
|
1617
|
+
"use strict";
|
|
1618
|
+
init_seed();
|
|
1619
|
+
tierLabel = (twin) => `${twin.tier} (${twin.fidelity}: ${twin.source.kind}${twin.source.license ? `, ${twin.source.license}` : ""})`;
|
|
1620
|
+
FIRST = ["Avery", "Jordan", "Riley", "Morgan", "Casey", "Quinn", "Harper", "Rowan", "Emerson", "Sage"];
|
|
1621
|
+
LAST = ["Chen", "Patel", "Okafor", "Silva", "Novak", "Haddad", "Larsen", "Moreau", "Kim", "Rossi"];
|
|
1622
|
+
COMPANY = ["Northwind", "Globex", "Initech", "Umbrella Labs", "Acme Freight", "Vandelay", "Hooli", "Soylent", "Stark Supply", "Wayne Analytics"];
|
|
1623
|
+
WORDS = ["renewal", "onboarding", "enterprise plan", "pilot", "expansion", "support", "quarterly review", "migration", "integration", "upgrade"];
|
|
1624
|
+
twinClock = (sequence) => new Date(Date.UTC(2026, 0, 5, 9, 0, 0) + sequence * 6e4);
|
|
1625
|
+
streamFor = (seed, purpose) => new SeedStream(normalizeSeed(seed ?? "42"), purpose);
|
|
1626
|
+
normName = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
1627
|
+
singular = (s) => s.replace(/ies$/, "y").replace(/(sses|xes|ches|shes)$/, (m) => m.slice(0, -2)).replace(/([^s])s$/, "$1");
|
|
1628
|
+
}
|
|
1629
|
+
});
|
|
1630
|
+
|
|
1631
|
+
// src/runtime/compiler/engine.ts
|
|
1632
|
+
function materialize(schema, mode, stream, sequence, name = "", depth = 0) {
|
|
1633
|
+
if (!schema) return mode === "seed" ? {} : void 0;
|
|
1634
|
+
if (mode === "seed") return fakeValue(schema, name, stream, depth, sequence);
|
|
1635
|
+
if (schema.default !== void 0) return structuredClone(schema.default);
|
|
1636
|
+
if (schema.enum?.length) return schema.enum[0];
|
|
1637
|
+
const type = schema.type ?? (schema.properties ? "object" : void 0);
|
|
1638
|
+
if (type === "object") {
|
|
1639
|
+
if (depth > 4 || schema["x-recursive"]) return {};
|
|
1640
|
+
const out = {};
|
|
1641
|
+
const all = !schema.required, required = new Set(schema.required ?? []);
|
|
1642
|
+
for (const [k, child] of Object.entries(schema.properties ?? {})) {
|
|
1643
|
+
const n = normName(k);
|
|
1644
|
+
if (CREATED.has(n) || UPDATED.has(n)) {
|
|
1645
|
+
out[k] = stamp(child, sequence);
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
if (!all && !required.has(k) && child.default === void 0 && !(child.enum?.length === 1)) continue;
|
|
1649
|
+
if (child.nullable && !child.enum && child.type !== "object" && child.type !== "array" && !/^(id|sid|object|status|type)$/.test(n)) {
|
|
1650
|
+
out[k] = null;
|
|
1651
|
+
continue;
|
|
1652
|
+
}
|
|
1653
|
+
const v = materialize(child, mode, stream, sequence, k, depth + 1);
|
|
1654
|
+
if (v !== void 0) out[k] = v;
|
|
1655
|
+
}
|
|
1656
|
+
return out;
|
|
1657
|
+
}
|
|
1658
|
+
if (type === "array") return [];
|
|
1659
|
+
return fakeValue(schema, name, stream, depth, sequence);
|
|
1660
|
+
}
|
|
1661
|
+
function overlay(target, input, schema, merge) {
|
|
1662
|
+
const props = schema?.properties ?? {};
|
|
1663
|
+
for (const [k, v] of Object.entries(input)) {
|
|
1664
|
+
const key = Object.hasOwn(props, k) ? k : Object.keys(props).find((p) => normName(p) === normName(k)) ?? k;
|
|
1665
|
+
const child = props[key];
|
|
1666
|
+
if (isObj(v) && isObj(target[key]) && merge) {
|
|
1667
|
+
const next = structuredClone(target[key]);
|
|
1668
|
+
overlay(next, v, child, true);
|
|
1669
|
+
target[key] = next;
|
|
1670
|
+
} else target[key] = isObj(v) || Array.isArray(v) ? structuredClone(v) : coerce(v, child);
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
function newId(resource, rows2, stream) {
|
|
1674
|
+
const s = resource.idSchema, taken = new Set(rows2.map((r) => String(r[resource.idField])));
|
|
1675
|
+
for (let i = 0; i < 50; i++) {
|
|
1676
|
+
let id;
|
|
1677
|
+
if (s?.type === "integer" || s?.type === "number") id = rows2.reduce((m, r) => Math.max(m, Number(r[resource.idField]) || 0), 1e3) + 1 + i;
|
|
1678
|
+
else if (s?.pattern) id = fromPattern(s.pattern, stream);
|
|
1679
|
+
if (id === void 0 && typeof s?.example === "string" && /^[A-Za-z]{1,8}_/.test(s.example)) id = s.example.split("_")[0] + "_" + stream.nextHex(12);
|
|
1680
|
+
if (id === void 0 && s?.format === "uuid") id = fakeValue(s, "id", stream);
|
|
1681
|
+
if (id === void 0 && typeof s?.example === "string" && /^\d+$/.test(s.example)) id = String(1e7 + stream.nextInt(89999999));
|
|
1682
|
+
id ??= `${singular(resource.name).replace(/[^a-z0-9]/gi, "").slice(0, 4).toLowerCase() || "obj"}_${stream.nextHex(10)}`;
|
|
1683
|
+
if (!taken.has(String(id))) return id;
|
|
1684
|
+
}
|
|
1685
|
+
return `${resource.name}_${stream.nextHex(16)}`;
|
|
1686
|
+
}
|
|
1687
|
+
function routes(twin) {
|
|
1688
|
+
let list2 = cache.get(twin);
|
|
1689
|
+
if (list2) return list2;
|
|
1690
|
+
list2 = twin.operations.map((op2) => {
|
|
1691
|
+
const names = [];
|
|
1692
|
+
let literal = 0;
|
|
1693
|
+
const source = op2.path.split("/").map((seg) => {
|
|
1694
|
+
if (!seg.includes("{")) {
|
|
1695
|
+
literal++;
|
|
1696
|
+
return seg.replace(/[.*+?^$()|[\]\\]/g, "\\$&");
|
|
1697
|
+
}
|
|
1698
|
+
return seg.split(/(\{[^}]+\})/).map((part) => {
|
|
1699
|
+
const m = part.match(/^\{([^}]+?)(\+)?\}$/);
|
|
1700
|
+
if (!m) return part.replace(/[.*+?^$()|[\]\\]/g, "\\$&");
|
|
1701
|
+
names.push(m[1]);
|
|
1702
|
+
return m[2] ? "(.+)" : "([^/]+?)";
|
|
1703
|
+
}).join("");
|
|
1704
|
+
}).join("/");
|
|
1705
|
+
return { op: op2, re: new RegExp(`^${source}/?$`), names, score: literal * 10 - names.length };
|
|
1706
|
+
}).sort((a, b) => b.score - a.score);
|
|
1707
|
+
cache.set(twin, list2);
|
|
1708
|
+
return list2;
|
|
1709
|
+
}
|
|
1710
|
+
function matchOperation(twin, method, path) {
|
|
1711
|
+
const candidates = [path];
|
|
1712
|
+
if (twin.basePath && path.startsWith(twin.basePath + "/")) candidates.push(path.slice(twin.basePath.length));
|
|
1713
|
+
for (const p of candidates) for (const r of routes(twin)) {
|
|
1714
|
+
if (r.op.method !== method) continue;
|
|
1715
|
+
const m = p.match(r.re);
|
|
1716
|
+
if (m) return { op: r.op, params: Object.fromEntries(r.names.map((n, i) => [n, decodeURIComponent(m[i + 1])])) };
|
|
1717
|
+
}
|
|
1718
|
+
return;
|
|
1719
|
+
}
|
|
1720
|
+
function errorBody(twin, op2, status, code, message, seed) {
|
|
1721
|
+
const documented = op2?.errors ?? [];
|
|
1722
|
+
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);
|
|
1723
|
+
const finalStatus = choice?.status && Math.floor(choice.status / 100) === Math.floor(status / 100) ? choice.status : status;
|
|
1724
|
+
if (!choice?.schema || choice.schema.type !== "object") return { status: finalStatus, body: { error: { code, message, status: finalStatus }, forwardedToProduction: false } };
|
|
1725
|
+
const body = materialize(choice.schema, "create", streamFor(seed, `error:${twin.id}`), 0);
|
|
1726
|
+
const fill = (node, schema, depth) => {
|
|
1727
|
+
for (const [k, s] of Object.entries(schema?.properties ?? {})) {
|
|
1728
|
+
const n = normName(k);
|
|
1729
|
+
if (MESSAGE.has(n) && (s.type ?? "string") === "string") node[k] = message;
|
|
1730
|
+
else if (CODE.has(n) && (s.type ?? "string") === "string" && !s.enum) node[k] = code;
|
|
1731
|
+
else if (CODE.has(n) && (s.type === "integer" || s.type === "number")) node[k] = finalStatus;
|
|
1732
|
+
else if (STATUS.has(n) && (s.type === "integer" || s.type === "number")) node[k] = finalStatus;
|
|
1733
|
+
else if (n === "error" && (s.type ?? "string") === "string") node[k] = code;
|
|
1734
|
+
else if (s.type === "object" && depth < 2 && /error/.test(n)) {
|
|
1735
|
+
node[k] = isObj(node[k]) ? node[k] : {};
|
|
1736
|
+
fill(node[k], s, depth + 1);
|
|
1737
|
+
} else if (s.type === "array" && s.items?.type === "object" && depth < 2 && /error/.test(n)) {
|
|
1738
|
+
const item = {};
|
|
1739
|
+
fill(item, s.items, depth + 1);
|
|
1740
|
+
node[k] = [item];
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
};
|
|
1744
|
+
fill(body, choice.schema, 0);
|
|
1745
|
+
return { status: finalStatus, body };
|
|
1746
|
+
}
|
|
1747
|
+
function inScope(row, resource, params, op2) {
|
|
1748
|
+
for (const p of op2.parentParams ?? []) {
|
|
1749
|
+
const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
|
|
1750
|
+
const value = row[parentKey(p)] ?? (field ? row[field] : void 0);
|
|
1751
|
+
if (value !== void 0 && String(value) !== params[p]) return false;
|
|
1752
|
+
}
|
|
1753
|
+
return true;
|
|
1754
|
+
}
|
|
1755
|
+
function withParents(row, resource, op2, params) {
|
|
1756
|
+
const out = visible(row);
|
|
1757
|
+
for (const p of op2.parentParams ?? []) {
|
|
1758
|
+
const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
|
|
1759
|
+
if (field && (out[field] === void 0 || out[field] === null)) out[field] = params[p];
|
|
1760
|
+
}
|
|
1761
|
+
return out;
|
|
1762
|
+
}
|
|
1763
|
+
function shape(op2, resource, record2, stream, sequence, params = {}) {
|
|
1764
|
+
const r = op2.response;
|
|
1765
|
+
const out = withParents(record2, resource, op2, params);
|
|
1766
|
+
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;
|
|
1767
|
+
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)));
|
|
1768
|
+
if (!holder) return out;
|
|
1769
|
+
const env = materialize(r, "create", stream, sequence);
|
|
1770
|
+
for (const [k, s] of Object.entries(r.properties)) if (normName(k) === "success" && s.type === "boolean") env[k] = true;
|
|
1771
|
+
env[holder[0]] = out;
|
|
1772
|
+
return env;
|
|
1773
|
+
}
|
|
1774
|
+
function listEnvelope(op2, page, info, stream, sequence) {
|
|
1775
|
+
const r = op2.response;
|
|
1776
|
+
if (!r || op2.listKey === "" || r.type === "array") return page;
|
|
1777
|
+
const env = materialize(r, "create", stream, sequence) ?? {};
|
|
1778
|
+
env[op2.listKey ?? "data"] = page;
|
|
1779
|
+
const walk = (node, schema, depth) => {
|
|
1780
|
+
for (const [k, s] of Object.entries(schema?.properties ?? {})) {
|
|
1781
|
+
const n = normName(k);
|
|
1782
|
+
if (k === op2.listKey && depth === 0) continue;
|
|
1783
|
+
if (["hasmore", "more", "istruncated", "hasnextpage"].includes(n)) node[k] = !!info.next;
|
|
1784
|
+
else if (["total", "totalcount", "totalresults", "totalsize", "resultsize"].includes(n) && (s.type === "integer" || s.type === "number")) node[k] = info.total;
|
|
1785
|
+
else if (["nextcursor", "nextpagetoken", "nexttoken", "endcursor", "after", "cursor", "nextcontinuationtoken", "nextmarker", "offset"].includes(n)) node[k] = info.next ?? (s.nullable ? null : n === "offset" ? 0 : "");
|
|
1786
|
+
else if (["nextpageuri", "nextpageurl", "next", "nextlink", "odatanextlink", "nexturl"].includes(n) && (s.type ?? "string") === "string") node[k] = info.nextUrl ?? null;
|
|
1787
|
+
else if (s.type === "object" && depth < 2 && /paging|pageinfo|meta|metadata|pagination|links|next|responsemetadata/.test(n)) {
|
|
1788
|
+
if (n === "next" && !info.next) {
|
|
1789
|
+
delete node[k];
|
|
1790
|
+
continue;
|
|
1791
|
+
}
|
|
1792
|
+
node[k] = isObj(node[k]) ? node[k] : {};
|
|
1793
|
+
walk(node[k], s, depth + 1);
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
walk(env, r, 0);
|
|
1798
|
+
return env;
|
|
1799
|
+
}
|
|
1800
|
+
function handleRest(twin, req, data, ctx) {
|
|
1801
|
+
const match = matchOperation(twin, req.method, req.path);
|
|
1802
|
+
if (!match || !match.op.supported) return void 0;
|
|
1803
|
+
const { op: op2, params } = match, resource = resourceOf(twin, op2), collection = resource.collection;
|
|
1804
|
+
const rows2 = data[collection] ??= [];
|
|
1805
|
+
const stream = streamFor(ctx.seed, `${twin.id}:${collection}:${ctx.sequence}`);
|
|
1806
|
+
const fail = (status, code, message) => {
|
|
1807
|
+
const e = errorBody(twin, op2, status, code, message, ctx.seed);
|
|
1808
|
+
return { status: e.status, body: e.body, collection };
|
|
1809
|
+
};
|
|
1810
|
+
const authNames = new Set(twin.auth.filter((a) => a.type === "api-key").map((a) => normName(a.name ?? "")));
|
|
1811
|
+
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}`);
|
|
1812
|
+
const body = req.body ?? {};
|
|
1813
|
+
const writes = ["create", "update", "replace", "upsert", "action"].includes(op2.kind) || op2.kind === "singleton" && req.method !== "GET";
|
|
1814
|
+
if (writes && op2.body && op2.bodyEncoding !== "raw") {
|
|
1815
|
+
if (op2.bodyRequired && !Object.keys(body).length && op2.kind !== "action") return fail(400, "body_missing", "Request body is required");
|
|
1816
|
+
const props = op2.body.properties ?? {};
|
|
1817
|
+
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}`);
|
|
1818
|
+
if (op2.bodyEncoding === "json") for (const [k, v] of Object.entries(body)) {
|
|
1819
|
+
const s = props[k];
|
|
1820
|
+
if (!s || v === null && s.nullable) continue;
|
|
1821
|
+
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);
|
|
1822
|
+
if (!ok2) return fail(400, "invalid_type", `Field ${k} must be ${t}`);
|
|
1823
|
+
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(", ")}`);
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
const id = op2.idParam ? params[op2.idParam] : void 0;
|
|
1827
|
+
const scoped = rows2.filter((r) => inScope(r, resource, params, op2));
|
|
1828
|
+
if (op2.kind === "list") {
|
|
1829
|
+
const filters = [];
|
|
1830
|
+
let size = 20, cursor, cursorName = "";
|
|
1831
|
+
for (const p of op2.params.filter((p2) => p2.in === "query")) {
|
|
1832
|
+
const n = normName(p.name), v = req.query[p.name];
|
|
1833
|
+
if (PAGE_SIZE.test(n) && (p.schema?.type === "integer" || p.schema?.type === "number" || n !== "count")) {
|
|
1834
|
+
const d = Number(v ?? p.schema?.default ?? 20);
|
|
1835
|
+
size = Math.max(1, Math.min(Number.isFinite(d) ? d : 20, p.schema?.maximum ?? 1e3));
|
|
1836
|
+
continue;
|
|
1837
|
+
}
|
|
1838
|
+
if (CURSOR.test(n)) {
|
|
1839
|
+
if (v !== void 0) {
|
|
1840
|
+
cursor = v;
|
|
1841
|
+
cursorName = n;
|
|
1842
|
+
} else cursorName ||= n;
|
|
1843
|
+
continue;
|
|
1844
|
+
}
|
|
1845
|
+
if (v !== void 0) filters.push([p.name, v]);
|
|
1846
|
+
}
|
|
1847
|
+
const matches2 = scoped.filter((r) => filters.every(([k, v]) => {
|
|
1848
|
+
const field = Object.keys(r).find((f) => normName(f) === normName(k));
|
|
1849
|
+
const value = field !== void 0 ? r[field] : isObj(r.properties) ? r.properties[k] : void 0;
|
|
1850
|
+
return value === void 0 || String(value) === v;
|
|
1851
|
+
}));
|
|
1852
|
+
let start = 0;
|
|
1853
|
+
if (cursor !== void 0) {
|
|
1854
|
+
const i = matches2.findIndex((r) => String(r[resource.idField]) === cursor);
|
|
1855
|
+
start = i >= 0 ? i + 1 : cursorName === "page" ? Math.max(0, (Number(cursor) - 1) * size) : Number.isFinite(Number(cursor)) ? Number(cursor) : 0;
|
|
1856
|
+
}
|
|
1857
|
+
const page = matches2.slice(start, start + size).map((r) => withParents(r, resource, op2, params));
|
|
1858
|
+
const more = start + size < matches2.length;
|
|
1859
|
+
const next2 = more ? cursorName === "startingafter" ? String(page[page.length - 1][resource.idField]) : String(start + size) : void 0;
|
|
1860
|
+
const nextUrl = next2 ? `${req.path}?${new URLSearchParams({ ...req.query, [op2.params.find((p) => normName(p.name) === cursorName)?.name ?? "after"]: next2 })}` : void 0;
|
|
1861
|
+
return { status: op2.status, body: listEnvelope(op2, page, { total: matches2.length, ...next2 ? { next: next2 } : {}, ...nextUrl ? { nextUrl } : {} }, stream, ctx.sequence), collection, operation: "read" };
|
|
1862
|
+
}
|
|
1863
|
+
if (op2.kind === "singleton") {
|
|
1864
|
+
if (req.method === "GET") {
|
|
1865
|
+
const row3 = scoped[0] ?? materialize(resource.schema ?? op2.response, "seed", streamFor(ctx.seed, `singleton:${twin.id}:${collection}`), 0);
|
|
1866
|
+
if (!scoped.length && isObj(row3)) rows2.push(row3);
|
|
1867
|
+
return { status: op2.status, body: visible(row3), collection, operation: "read" };
|
|
1868
|
+
}
|
|
1869
|
+
if (req.method === "DELETE") {
|
|
1870
|
+
rows2.length = 0;
|
|
1871
|
+
return { status: op2.status === 200 && !op2.response ? 204 : op2.status, body: op2.response ? {} : null, collection, operation: "write", record: {} };
|
|
1872
|
+
}
|
|
1873
|
+
const row2 = scoped[0] ?? {};
|
|
1874
|
+
overlay(row2, body, op2.body, true);
|
|
1875
|
+
if (!scoped.length) rows2.push(row2);
|
|
1876
|
+
return { status: op2.status, body: visible(row2), collection, operation: "write", record: row2 };
|
|
1877
|
+
}
|
|
1878
|
+
if (op2.kind === "create" || op2.kind === "upsert" && findRow(scoped, resource, id) < 0) {
|
|
1879
|
+
if (rows2.length >= 1e4) return fail(429, "capacity", "Twin collection is full");
|
|
1880
|
+
const record2 = materialize(resource.schema ?? op2.response, "create", stream, ctx.sequence) ?? {};
|
|
1881
|
+
overlay(record2, body, resource.schema, true);
|
|
1882
|
+
const supplied = Object.keys(body).find((k) => normName(k) === normName(resource.idField));
|
|
1883
|
+
if (id !== void 0) record2[resource.idField] = id;
|
|
1884
|
+
else if (!supplied) record2[resource.idField] = newId(resource, rows2, stream);
|
|
1885
|
+
else if (findRow(scoped, resource, String(record2[resource.idField])) >= 0) return fail(409, "conflict", `${resource.name} ${record2[resource.idField]} already exists`);
|
|
1886
|
+
for (const p of op2.parentParams ?? []) {
|
|
1887
|
+
const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
|
|
1888
|
+
if (field && record2[field] === void 0) record2[field] = params[p];
|
|
1889
|
+
else if (!field) record2[parentKey(p)] = params[p];
|
|
1890
|
+
}
|
|
1891
|
+
rows2.push(record2);
|
|
1892
|
+
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) };
|
|
1893
|
+
}
|
|
1894
|
+
const index = rows2.findIndex((r) => String(r[resource.idField]) === id && inScope(r, resource, params, op2));
|
|
1895
|
+
if (index < 0) return { ...fail(404, "not_found", `No such ${singular(resource.name)}: ${id}`), operation: "read" };
|
|
1896
|
+
const row = rows2[index];
|
|
1897
|
+
if (op2.kind === "read") return { status: op2.status, body: shape(op2, resource, row, stream, ctx.sequence, params), collection, operation: "read" };
|
|
1898
|
+
if (op2.kind === "delete") {
|
|
1899
|
+
rows2.splice(index, 1);
|
|
1900
|
+
const props = op2.response?.properties;
|
|
1901
|
+
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;
|
|
1902
|
+
return { status: reply ? op2.status : op2.status === 200 ? 204 : op2.status, body: reply, collection, operation: "write", record: visible(row) };
|
|
1903
|
+
}
|
|
1904
|
+
if (op2.kind === "action") {
|
|
1905
|
+
const verb = normName(op2.path.split("/").pop() ?? "");
|
|
1906
|
+
const status = Object.entries(resource.schema?.properties ?? {}).find(([k]) => /^(status|state)$/i.test(k));
|
|
1907
|
+
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"));
|
|
1908
|
+
if (status && target !== void 0) row[status[0]] = target;
|
|
1909
|
+
overlay(row, body, resource.schema, true);
|
|
1910
|
+
for (const [k, s] of Object.entries(resource.schema?.properties ?? {})) if (UPDATED.has(normName(k))) row[k] = stamp(s, ctx.sequence);
|
|
1911
|
+
return { status: op2.status, body: shape(op2, resource, row, stream, ctx.sequence, params), collection, operation: "write", record: visible(row) };
|
|
1912
|
+
}
|
|
1913
|
+
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);
|
|
1914
|
+
overlay(next, body, resource.schema, op2.kind === "update");
|
|
1915
|
+
next[resource.idField] = row[resource.idField];
|
|
1916
|
+
for (const [k, s] of Object.entries(resource.schema?.properties ?? {})) if (UPDATED.has(normName(k))) next[k] = stamp(s, ctx.sequence);
|
|
1917
|
+
rows2[index] = next;
|
|
1918
|
+
return { status: op2.status === 201 ? 200 : op2.status, body: shape(op2, resource, next, stream, ctx.sequence, params), collection, operation: "write", record: visible(next) };
|
|
1919
|
+
}
|
|
1920
|
+
var HIDDEN, visible, isObj, CREATED, UPDATED, stamp, coerce, cache, pathKnown, MESSAGE, CODE, STATUS, PAGE_SIZE, CURSOR, resourceOf, findRow, parentKey;
|
|
1921
|
+
var init_engine = __esm({
|
|
1922
|
+
"src/runtime/compiler/engine.ts"() {
|
|
1923
|
+
"use strict";
|
|
1924
|
+
init_model();
|
|
1925
|
+
HIDDEN = "__at_";
|
|
1926
|
+
visible = (row) => {
|
|
1927
|
+
if (Array.isArray(row)) return row.map(visible);
|
|
1928
|
+
if (!row || typeof row !== "object") return row;
|
|
1929
|
+
const out = {};
|
|
1930
|
+
for (const [k, v] of Object.entries(row)) if (!k.startsWith(HIDDEN)) out[k] = visible(v);
|
|
1931
|
+
return out;
|
|
1932
|
+
};
|
|
1933
|
+
isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
1934
|
+
CREATED = /* @__PURE__ */ new Set(["createdat", "created", "datecreated", "createdtime", "createtime", "createdate", "insertedat", "creationdate", "createdon"]);
|
|
1935
|
+
UPDATED = /* @__PURE__ */ new Set(["updatedat", "updated", "dateupdated", "lastmodified", "lastmodifieddate", "hslastmodifieddate", "modifiedat", "updatetime", "updatedtime", "lastupdated", "modifiedon", "updatedon"]);
|
|
1936
|
+
stamp = (schema, sequence) => {
|
|
1937
|
+
const d = twinClock(sequence);
|
|
1938
|
+
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();
|
|
1939
|
+
};
|
|
1940
|
+
coerce = (value, schema) => {
|
|
1941
|
+
if (typeof value !== "string" || !schema) return value;
|
|
1942
|
+
if (schema.type === "integer" || schema.type === "number") {
|
|
1943
|
+
const n = Number(value);
|
|
1944
|
+
return Number.isFinite(n) ? n : value;
|
|
1945
|
+
}
|
|
1946
|
+
if (schema.type === "boolean") return value === "true" ? true : value === "false" ? false : value;
|
|
1947
|
+
return value;
|
|
1948
|
+
};
|
|
1949
|
+
cache = /* @__PURE__ */ new WeakMap();
|
|
1950
|
+
pathKnown = (twin, path) => ["GET", "POST", "PUT", "PATCH", "DELETE"].some((m) => matchOperation(twin, m, path));
|
|
1951
|
+
MESSAGE = /* @__PURE__ */ new Set(["message", "detail", "errordescription", "title", "description", "errormessage"]);
|
|
1952
|
+
CODE = /* @__PURE__ */ new Set(["code", "errorcode", "errortype", "category"]);
|
|
1953
|
+
STATUS = /* @__PURE__ */ new Set(["status", "statuscode", "httpstatus", "httpstatuscode"]);
|
|
1954
|
+
PAGE_SIZE = /^(limit|perpage|pagesize|maxresults|maxitems|top|size|first|count|maxkeys)$/;
|
|
1955
|
+
CURSOR = /^(after|startingafter|cursor|pagetoken|nextpagetoken|offset|start|skip|page|marker|continuationtoken|nexttoken|startafter|startindex)$/;
|
|
1956
|
+
resourceOf = (twin, op2) => twin.resources.find((r) => r.collection === op2.resource);
|
|
1957
|
+
findRow = (rows2, resource, id) => rows2.findIndex((r) => String(r[resource.idField]) === id);
|
|
1958
|
+
parentKey = (name) => HIDDEN + name;
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
|
|
1962
|
+
// src/runtime/compiler/adapters.ts
|
|
1963
|
+
function twinAuth(twin, headers, url, token) {
|
|
1964
|
+
const authorization = header(headers, "authorization") ?? "";
|
|
1965
|
+
for (const scheme of twin.auth) {
|
|
1966
|
+
if ((scheme.type === "bearer" || scheme.type === "oauth2") && authorization === `Bearer ${token}`) return true;
|
|
1967
|
+
if (scheme.type === "basic" && /^Basic /i.test(authorization)) {
|
|
1968
|
+
const [user, ...rest] = Buffer.from(authorization.slice(6), "base64").toString("utf8").split(":");
|
|
1969
|
+
if (user === token || rest.join(":") === token) return true;
|
|
1970
|
+
}
|
|
1971
|
+
if (scheme.type === "api-key" && scheme.name) {
|
|
1972
|
+
if (scheme.in === "query" && new URL(url, "http://localhost").searchParams.get(scheme.name) === token) return true;
|
|
1973
|
+
if (scheme.in !== "query" && (header(headers, scheme.name) === token || header(headers, scheme.name) === `Bearer ${token}`)) return true;
|
|
1974
|
+
}
|
|
1975
|
+
if (scheme.type === "sigv4" && new RegExp(`Credential=${token.replace(/[^a-zA-Z0-9_]/g, "")}/`).test(authorization)) return true;
|
|
1976
|
+
if (scheme.type === "none") return true;
|
|
1977
|
+
}
|
|
1978
|
+
return false;
|
|
1979
|
+
}
|
|
1980
|
+
function generatedAdapter(adapter) {
|
|
1981
|
+
const twin = adapter ? twins.get(adapter) : void 0;
|
|
1982
|
+
if (!twin) return;
|
|
1983
|
+
const handler = protocolHandlers.get(twin.protocol);
|
|
1984
|
+
return {
|
|
1985
|
+
twin,
|
|
1986
|
+
handle: (req, data, sequence, seed) => handler ? handler(twin, req, data, { seed, sequence }) : void 0,
|
|
1987
|
+
auth: (headers, url, token) => twinAuth(twin, headers, url, token),
|
|
1988
|
+
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 }),
|
|
1989
|
+
collectionOf: (method, path) => twin.protocol === "rest" ? (() => {
|
|
1990
|
+
const m = matchOperation(twin, method, path);
|
|
1991
|
+
return m ? m.op.resource : void 0;
|
|
1992
|
+
})() : void 0,
|
|
1993
|
+
bodyMode: (contentType) => {
|
|
1994
|
+
const t = (contentType ?? "").toLowerCase();
|
|
1995
|
+
return /json/.test(t) ? "json" : /x-www-form-urlencoded/.test(t) ? "form" : twin.protocol === "graphql" ? "json" : t || twin.protocol.startsWith("aws-rest") ? "raw" : "json";
|
|
1996
|
+
}
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
var twins, protocolHandlers, isGeneratedAdapter, header;
|
|
2000
|
+
var init_adapters = __esm({
|
|
2001
|
+
"src/runtime/compiler/adapters.ts"() {
|
|
2002
|
+
"use strict";
|
|
2003
|
+
init_engine();
|
|
2004
|
+
init_model();
|
|
2005
|
+
twins = /* @__PURE__ */ new Map();
|
|
2006
|
+
protocolHandlers = /* @__PURE__ */ new Map([["rest", handleRest]]);
|
|
2007
|
+
isGeneratedAdapter = (adapter) => typeof adapter === "string" && adapter.startsWith("generated:") && twins.has(adapter);
|
|
2008
|
+
header = (h, name) => {
|
|
2009
|
+
const v = h[name.toLowerCase()];
|
|
2010
|
+
return Array.isArray(v) ? v[0] : v;
|
|
2011
|
+
};
|
|
2012
|
+
}
|
|
2013
|
+
});
|
|
2014
|
+
|
|
2015
|
+
// src/runtime/enterprise-twins.ts
|
|
2016
|
+
import { createHash as createHash4 } from "crypto";
|
|
2017
|
+
function eqFilter(expression, quote) {
|
|
2018
|
+
const parts = expression.split(/\s+and\s+/i), tests = [];
|
|
2019
|
+
for (const part of parts) {
|
|
2020
|
+
const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote}([^${quote}]*)${quote}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
|
|
2021
|
+
if (!m) return null;
|
|
2022
|
+
const value = m[2] !== void 0 ? m[2] : m[3] === "null" ? null : m[3] === "true" ? true : m[3] === "false" ? false : Number(m[3]);
|
|
2023
|
+
tests.push((r) => {
|
|
2024
|
+
const actual = m[1].split(".").reduce((v, k) => v?.[k], r);
|
|
2025
|
+
return actual === value || typeof value === "number" && String(actual) === String(value);
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
return (r) => tests.every((t) => t(r));
|
|
2029
|
+
}
|
|
2030
|
+
function soql(q) {
|
|
2031
|
+
const m = /^\s*SELECT\s+(.+?)\s+FROM\s+(\w+)(?:\s+WHERE\s+(.+?))?(?:\s+LIMIT\s+(\d+))?\s*$/i.exec(q);
|
|
2032
|
+
if (!m || /\(|\bORDER\b|\bGROUP\b|\bOR\b|\bLIKE\b|\bIN\b/i.test(m[1] + " " + (m[3] ?? ""))) return null;
|
|
2033
|
+
const tests = [];
|
|
2034
|
+
for (const cond of m[3] ? m[3].split(/\s+AND\s+/i) : []) {
|
|
2035
|
+
const c = /^\s*(\w+)\s*(=|!=)\s*(?:'((?:[^'\\]|\\.)*)'|(true|false|null|-?\d+(?:\.\d+)?))\s*$/i.exec(cond);
|
|
2036
|
+
if (!c) return null;
|
|
2037
|
+
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]);
|
|
2038
|
+
const field = c[1].toLowerCase();
|
|
2039
|
+
tests.push((r) => {
|
|
2040
|
+
const k = Object.keys(r).find((key) => key.toLowerCase() === field);
|
|
2041
|
+
const equal = (k ? r[k] : null) === value;
|
|
2042
|
+
return c[2] === "=" ? equal : !equal;
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
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 };
|
|
2046
|
+
}
|
|
2047
|
+
function sqlWhere(clause, bindings, counter) {
|
|
2048
|
+
if (!clause) return () => true;
|
|
2049
|
+
const tests = [];
|
|
2050
|
+
for (const part of clause.split(/\s+AND\s+/i)) {
|
|
2051
|
+
const c = new RegExp(`^\\s*("?[\\w$]+"?)\\s*(=|!=|<>)\\s*${VALUE}\\s*$`, "i").exec(part);
|
|
2052
|
+
if (!c) return null;
|
|
2053
|
+
const column = ident(c[1]), value = sfSqlValue(c[3], bindings, counter);
|
|
2054
|
+
if (value === void 0) return null;
|
|
2055
|
+
tests.push((r) => String(r[column] ?? null) === String(value) === (c[2] === "="));
|
|
2056
|
+
}
|
|
2057
|
+
return (r) => tests.every((t) => t(r));
|
|
2058
|
+
}
|
|
2059
|
+
function enterpriseAuth(adapter, headers, url, token) {
|
|
2060
|
+
if (adapter === "okta") return headers.authorization === `SSWS ${token}`;
|
|
2061
|
+
if (adapter === "pagerduty") return headers.authorization === `Token token=${token}` || new URL(url, "http://localhost").pathname === "/v2/enqueue";
|
|
2062
|
+
return false;
|
|
2063
|
+
}
|
|
2064
|
+
var ENTERPRISE_ADAPTERS, isEnterpriseAdapter, EPOCH2, iso2, hash, isObject2, scalar, flat, read, write2, table, limitOf, nextNumber, header2, SF_OBJECTS, sfError, sfView, salesforce, SN_TABLES, snTime, snError, servicenow, wdError, workday, SAP_SETS, sapError, sapView, sap, graphError, graphId, graphPage, teams, address, outlook, entra, oktaError, oktaId, okta, cfError, storage, confluence, sharepoint, sfSqlValue, VALUE, ident, snowflake, NS_TYPES, nsError, nsLink, netsuite, pdError, pdId, pagerduty, ENTERPRISE_OPERATIONS, ENTERPRISE_OPTIONAL_COLLECTIONS, FREEFORM_COLLECTION_ADAPTERS, unsupported, ENTERPRISE_UNSUPPORTED, op, ENTERPRISE_CONTRACTS;
|
|
2065
|
+
var init_enterprise_twins = __esm({
|
|
2066
|
+
"src/runtime/enterprise-twins.ts"() {
|
|
2067
|
+
"use strict";
|
|
2068
|
+
ENTERPRISE_ADAPTERS = ["salesforce", "servicenow", "workday", "sap", "microsoft-teams", "outlook", "entra-id", "okta", "confluence", "sharepoint", "snowflake", "netsuite", "pagerduty"];
|
|
2069
|
+
isEnterpriseAdapter = (name) => ENTERPRISE_ADAPTERS.includes(name);
|
|
2070
|
+
EPOCH2 = 17e8;
|
|
2071
|
+
iso2 = (sequence) => new Date((EPOCH2 + sequence) * 1e3).toISOString();
|
|
2072
|
+
hash = (seed) => createHash4("sha256").update(seed).digest("hex");
|
|
2073
|
+
isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
2074
|
+
scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
|
|
2075
|
+
flat = (v) => Object.values(v).every(scalar);
|
|
2076
|
+
read = (collection, body, status = 200, headers) => ({ status, body, collection, operation: "read", ...headers ? { headers } : {} });
|
|
2077
|
+
write2 = (collection, record2, body, status = 200, headers) => ({ status, body, collection, record: structuredClone(record2), operation: "write", ...headers ? { headers } : {} });
|
|
2078
|
+
table = (data, collection) => data[collection] ??= [];
|
|
2079
|
+
limitOf = (value, fallback, max) => {
|
|
2080
|
+
if (value === void 0) return fallback;
|
|
2081
|
+
const n = Number(value);
|
|
2082
|
+
return Number.isInteger(n) && n >= 1 && n <= max ? n : null;
|
|
2083
|
+
};
|
|
2084
|
+
nextNumber = (rows2, key, start) => rows2.reduce((max, r) => Math.max(max, Number(String(r[key] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
|
|
2085
|
+
header2 = (headers, name) => {
|
|
2086
|
+
const v = headers[name];
|
|
2087
|
+
return Array.isArray(v) ? v[0] : v;
|
|
2088
|
+
};
|
|
2089
|
+
SF_OBJECTS = {
|
|
2090
|
+
Account: { prefix: "001", required: ["Name"] },
|
|
2091
|
+
Contact: { prefix: "003", required: ["LastName"] },
|
|
2092
|
+
Lead: { prefix: "00Q", required: ["LastName", "Company"] },
|
|
2093
|
+
Opportunity: { prefix: "006", required: ["Name", "StageName", "CloseDate"] },
|
|
2094
|
+
Case: { prefix: "500", required: [] }
|
|
2095
|
+
};
|
|
2096
|
+
sfError = (status, errorCode, message, fields = []) => ({ status, body: [{ message, errorCode, fields }] });
|
|
2097
|
+
sfView = (object4, version, r, fields) => {
|
|
2098
|
+
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;
|
|
2099
|
+
return { attributes: { type: object4, url: `/services/data/${version}/sobjects/${object4}/${r.Id}` }, ...pick };
|
|
2100
|
+
};
|
|
2101
|
+
salesforce = (method, path, body, query, _headers, data, sequence) => {
|
|
2102
|
+
const m = /^\/services\/data\/(v\d+\.\d)\/(.+)$/.exec(path);
|
|
2103
|
+
if (!m) return;
|
|
2104
|
+
const [, version, rest] = m;
|
|
2105
|
+
if (rest === "query" && method === "GET") {
|
|
2106
|
+
const parsed = typeof query.q === "string" ? soql(query.q) : null;
|
|
2107
|
+
if (!parsed) return;
|
|
2108
|
+
const name = Object.keys(SF_OBJECTS).find((o) => o.toLowerCase() === parsed.object.toLowerCase());
|
|
2109
|
+
if (!name) return { ...sfError(400, "INVALID_TYPE", `sObject type '${parsed.object}' is not supported.`), collection: "/sobjects" };
|
|
2110
|
+
const records = table(data, `/sobjects/${name}`).filter(parsed.where).slice(0, parsed.limit ?? 2e3);
|
|
2111
|
+
return read(`/sobjects/${name}`, { totalSize: records.length, done: true, records: records.map((r) => sfView(name, version, r, parsed.fields)) });
|
|
2112
|
+
}
|
|
2113
|
+
const s = /^sobjects\/(\w+)(?:\/(\w{15,18}))?$/.exec(rest);
|
|
2114
|
+
if (!s) return;
|
|
2115
|
+
const object4 = s[1], spec = SF_OBJECTS[object4], collection = `/sobjects/${object4}`;
|
|
2116
|
+
if (!spec) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
|
|
2117
|
+
const rows2 = table(data, collection);
|
|
2118
|
+
if (!s[2] && method === "POST") {
|
|
2119
|
+
if (!flat(body)) return;
|
|
2120
|
+
const missing = spec.required.filter((f) => body[f] === void 0 || body[f] === null || body[f] === "");
|
|
2121
|
+
if (missing.length) return { ...sfError(400, "REQUIRED_FIELD_MISSING", `Required fields are missing: [${missing.join(", ")}]`, missing), collection };
|
|
2122
|
+
const id = (spec.prefix + hash(`salesforce:${object4}:${sequence}:${rows2.length}`).slice(0, 12)).toUpperCase().replace(/^00Q/i, "00Q") + "AAA";
|
|
2123
|
+
const record3 = { Id: id, ...body, CreatedDate: iso2(sequence), LastModifiedDate: iso2(sequence), IsDeleted: false };
|
|
2124
|
+
rows2.push(record3);
|
|
2125
|
+
return write2(collection, record3, { id, success: true, errors: [] }, 201);
|
|
2126
|
+
}
|
|
2127
|
+
if (!s[2]) return;
|
|
2128
|
+
const record2 = rows2.find((r) => r.Id === s[2] || String(r.Id).slice(0, 15) === s[2].slice(0, 15));
|
|
2129
|
+
if (!record2) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
|
|
2130
|
+
if (method === "GET") return read(collection, sfView(object4, version, record2));
|
|
2131
|
+
if (method === "PATCH") {
|
|
2132
|
+
if (!flat(body) || "Id" in body) return;
|
|
2133
|
+
Object.assign(record2, body, { LastModifiedDate: iso2(sequence) });
|
|
2134
|
+
return write2(collection, record2, null, 204);
|
|
2135
|
+
}
|
|
2136
|
+
if (method === "DELETE") {
|
|
2137
|
+
rows2.splice(rows2.indexOf(record2), 1);
|
|
2138
|
+
return write2(collection, { ...record2, IsDeleted: true }, null, 204);
|
|
2139
|
+
}
|
|
2140
|
+
};
|
|
2141
|
+
SN_TABLES = { incident: "INC", change_request: "CHG", problem: "PRB", sc_request: "REQ", sys_user: null };
|
|
2142
|
+
snTime = (sequence) => iso2(sequence).replace("T", " ").slice(0, 19);
|
|
2143
|
+
snError = (status, message, detail) => ({ status, body: { error: { message, detail }, status: "failure" } });
|
|
2144
|
+
servicenow = (method, path, body, query, _headers, data, sequence) => {
|
|
2145
|
+
const m = /^\/api\/now\/(?:v\d\/)?table\/(\w+)(?:\/([0-9a-f]{32}))?$/.exec(path);
|
|
2146
|
+
if (!m) return;
|
|
2147
|
+
const [, name, sysId] = m, collection = `/${name}`;
|
|
2148
|
+
if (!(name in SN_TABLES)) return { ...snError(400, "Invalid table", `Invalid table ${name}`), collection };
|
|
2149
|
+
const rows2 = table(data, collection);
|
|
2150
|
+
if (!sysId && method === "GET") {
|
|
2151
|
+
const limit = limitOf(query.sysparm_limit, 1e4, 1e4), offset = Number(query.sysparm_offset ?? 0);
|
|
2152
|
+
if (limit === null || !Number.isInteger(offset) || offset < 0) return;
|
|
2153
|
+
const tests = [];
|
|
2154
|
+
for (const clause of query.sysparm_query ? query.sysparm_query.split("^") : []) {
|
|
2155
|
+
const c = /^(\w+)(!=|=)(.*)$/.exec(clause);
|
|
2156
|
+
if (!c || /^(OR|NQ|ORDERBY)/.test(clause)) return;
|
|
2157
|
+
tests.push((r) => String(r[c[1]] ?? "") === c[3] === (c[2] === "="));
|
|
2158
|
+
}
|
|
2159
|
+
const matched = rows2.filter((r) => tests.every((t) => t(r)));
|
|
2160
|
+
const fields = query.sysparm_fields?.split(",").map((f) => f.trim());
|
|
2161
|
+
const page = matched.slice(offset, offset + limit).map((r) => fields ? Object.fromEntries(fields.map((f) => [f, r[f] ?? ""])) : r);
|
|
2162
|
+
return read(collection, { result: page }, 200, { "x-total-count": String(matched.length) });
|
|
2163
|
+
}
|
|
2164
|
+
if (!sysId && method === "POST") {
|
|
2165
|
+
if (!flat(body) || "sys_id" in body) return;
|
|
2166
|
+
const prefix = SN_TABLES[name];
|
|
2167
|
+
const record3 = {
|
|
2168
|
+
sys_id: hash(`servicenow:${name}:${sequence}:${rows2.length}`).slice(0, 32),
|
|
2169
|
+
...prefix ? { number: `${prefix}${String(nextNumber(rows2, "number", 10001)).padStart(7, "0")}` } : {},
|
|
2170
|
+
...name === "incident" ? { state: "1", impact: "3", urgency: "3", priority: "5" } : {},
|
|
2171
|
+
...Object.fromEntries(Object.entries(body).map(([k, v]) => [k, v === null ? "" : String(v)])),
|
|
2172
|
+
sys_created_on: snTime(sequence),
|
|
2173
|
+
sys_updated_on: snTime(sequence),
|
|
2174
|
+
sys_mod_count: "0"
|
|
2175
|
+
};
|
|
2176
|
+
rows2.push(record3);
|
|
2177
|
+
return write2(collection, record3, { result: record3 }, 201);
|
|
2178
|
+
}
|
|
2179
|
+
if (!sysId) return;
|
|
2180
|
+
const record2 = rows2.find((r) => r.sys_id === sysId);
|
|
2181
|
+
if (!record2) return { ...snError(404, "No Record found", "Record doesn't exist or ACL restricts the record retrieval"), collection };
|
|
2182
|
+
if (method === "GET") return read(collection, { result: record2 });
|
|
2183
|
+
if (method === "PATCH" || method === "PUT") {
|
|
2184
|
+
if (!flat(body) || "sys_id" in body || "number" in body) return;
|
|
2185
|
+
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) });
|
|
2186
|
+
return write2(collection, record2, { result: record2 });
|
|
2187
|
+
}
|
|
2188
|
+
if (method === "DELETE") {
|
|
2189
|
+
rows2.splice(rows2.indexOf(record2), 1);
|
|
2190
|
+
return write2(collection, record2, null, 204);
|
|
2191
|
+
}
|
|
2192
|
+
};
|
|
2193
|
+
wdError = (status, error, errors = []) => ({ status, body: { error, errors } });
|
|
2194
|
+
workday = (method, path, body, query, _headers, data, sequence) => {
|
|
2195
|
+
const m = /^\/ccx\/api\/(?:v1|staffing\/v\d+|absenceManagement\/v\d+)\/([\w-]+)\/workers(?:\/([\w-]+))?(?:\/(requestTimeOff|timeOffDetails))?$/.exec(path);
|
|
2196
|
+
if (!m) return;
|
|
2197
|
+
const [, , workerId, action] = m, workers = table(data, "/workers"), requests = table(data, "/timeOffRequests");
|
|
2198
|
+
if (!workerId && method === "GET") {
|
|
2199
|
+
const limit = limitOf(query.limit, 20, 100), offset = Number(query.offset ?? 0);
|
|
2200
|
+
if (limit === null || !Number.isInteger(offset) || offset < 0) return;
|
|
2201
|
+
const search = query.search?.toLowerCase();
|
|
2202
|
+
const matched = workers.filter((w) => !search || String(w.descriptor ?? "").toLowerCase().includes(search) || String(w.primaryWorkEmail ?? "").toLowerCase() === search);
|
|
2203
|
+
return read("/workers", { total: matched.length, data: matched.slice(offset, offset + limit) });
|
|
2204
|
+
}
|
|
2205
|
+
const worker = workers.find((w) => w.id === workerId);
|
|
2206
|
+
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" };
|
|
2207
|
+
if (!action && method === "GET") return read("/workers", worker);
|
|
2208
|
+
if (action === "timeOffDetails" && method === "GET") {
|
|
2209
|
+
const own = requests.filter((r) => r.worker?.id === workerId);
|
|
2210
|
+
return read("/timeOffRequests", { total: own.length, data: own });
|
|
2211
|
+
}
|
|
2212
|
+
if (action === "requestTimeOff" && method === "POST") {
|
|
2213
|
+
const days = body.days;
|
|
2214
|
+
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"))
|
|
2215
|
+
return { ...wdError(400, "Validation error", [{ error: "Each day requires a date (YYYY-MM-DD) and a timeOffType id", field: "days" }]), collection: "/timeOffRequests" };
|
|
2216
|
+
const taken = new Set(requests.filter((r) => r.worker?.id === workerId && r.status !== "Canceled").flatMap((r) => r.days.map((d) => d.date)));
|
|
2217
|
+
const clash = days.find((d) => taken.has(d.date));
|
|
2218
|
+
if (clash) return { ...wdError(400, "Validation error", [{ error: `Time off has already been requested for ${clash.date}.`, field: "days" }]), collection: "/timeOffRequests" };
|
|
2219
|
+
const record2 = {
|
|
2220
|
+
id: hash(`workday:timeoff:${sequence}:${requests.length}`).slice(0, 32),
|
|
2221
|
+
descriptor: `Time Off Request: ${worker.descriptor}`,
|
|
2222
|
+
worker: { id: workerId, descriptor: worker.descriptor },
|
|
2223
|
+
days: days.map((d) => ({ date: d.date, dailyQuantity: Number(d.dailyQuantity ?? 8), timeOffType: { id: d.timeOffType.id } })),
|
|
2224
|
+
status: "Submitted",
|
|
2225
|
+
businessProcessParameters: { overallStatus: "In Progress", comment: isObject2(body.businessProcessParameters) ? body.businessProcessParameters.comment ?? null : null },
|
|
2226
|
+
createdOn: iso2(sequence)
|
|
2227
|
+
};
|
|
2228
|
+
requests.push(record2);
|
|
2229
|
+
return write2("/timeOffRequests", record2, record2, 201);
|
|
2230
|
+
}
|
|
2231
|
+
};
|
|
2232
|
+
SAP_SETS = { A_BusinessPartner: { service: "API_BUSINESS_PARTNER", key: "BusinessPartner" }, A_SalesOrder: { service: "API_SALES_ORDER_SRV", key: "SalesOrder" } };
|
|
2233
|
+
sapError = (status, code, value, headers) => ({ status, body: { error: { code, message: { lang: "en", value } } }, ...headers ? { headers } : {} });
|
|
2234
|
+
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 });
|
|
2235
|
+
sap = (method, path, body, query, headers, data, sequence) => {
|
|
2236
|
+
const m = /^\/sap\/opu\/odata\/sap\/(API_BUSINESS_PARTNER|API_SALES_ORDER_SRV)\/(A_BusinessPartner|A_SalesOrder)(?:\('([^']{1,20})'\))?$/.exec(path);
|
|
2237
|
+
if (!m || SAP_SETS[m[2]].service !== m[1]) return;
|
|
2238
|
+
const [, , set, key] = m, collection = `/${set}`, rows2 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
|
|
2239
|
+
if (method === "GET") {
|
|
2240
|
+
const issued = header2(headers, "x-csrf-token")?.toLowerCase() === "fetch" ? { "x-csrf-token": csrf } : void 0;
|
|
2241
|
+
if (key) {
|
|
2242
|
+
const record3 = rows2.find((r) => r[SAP_SETS[set].key] === key);
|
|
2243
|
+
return record3 ? read(collection, { d: sapView(set, record3) }, 200, issued) : { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection };
|
|
2244
|
+
}
|
|
2245
|
+
const where = query.$filter ? eqFilter(query.$filter, "'") : () => true;
|
|
2246
|
+
const top = limitOf(query.$top, 1e3, 5e3), skip = Number(query.$skip ?? 0);
|
|
2247
|
+
if (!where || top === null || !Number.isInteger(skip) || skip < 0) return;
|
|
2248
|
+
return read(collection, { d: { results: rows2.filter(where).slice(skip, skip + top).map((r) => sapView(set, r)) } }, 200, issued);
|
|
2249
|
+
}
|
|
2250
|
+
if (header2(headers, "x-csrf-token") !== csrf) return { ...sapError(403, "403", "CSRF token validation failed", { "x-csrf-token": "Required" }), collection };
|
|
2251
|
+
if (method === "POST" && !key) {
|
|
2252
|
+
if (set === "A_BusinessPartner") {
|
|
2253
|
+
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 };
|
|
2254
|
+
const record4 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${(EPOCH2 + sequence) * 1e3})/`, BusinessPartnerIsBlocked: false };
|
|
2255
|
+
rows2.push(record4);
|
|
2256
|
+
return write2(collection, record4, { d: sapView(set, record4) }, 201);
|
|
2257
|
+
}
|
|
2258
|
+
const items = isObject2(body.to_Item) && Array.isArray(body.to_Item.results) ? body.to_Item.results : null;
|
|
2259
|
+
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 };
|
|
2260
|
+
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 };
|
|
2261
|
+
const total = items.reduce((sum, i) => sum + Number(i.NetAmount ?? 0), 0);
|
|
2262
|
+
const { to_Item: _items, ...header_ } = body;
|
|
2263
|
+
const record3 = {
|
|
2264
|
+
SalesOrder: String(nextNumber(rows2, "SalesOrder", 1)).padStart(10, "0"),
|
|
2265
|
+
...header_,
|
|
2266
|
+
TransactionCurrency: body.TransactionCurrency ?? "USD",
|
|
2267
|
+
TotalNetAmount: total.toFixed(2),
|
|
2268
|
+
OverallSDProcessStatus: "A",
|
|
2269
|
+
CreationDate: `/Date(${(EPOCH2 + sequence) * 1e3})/`,
|
|
2270
|
+
to_Item: { results: items.map((i, n) => ({ SalesOrderItem: String((n + 1) * 10), ...i })) }
|
|
2271
|
+
};
|
|
2272
|
+
rows2.push(record3);
|
|
2273
|
+
return write2(collection, record3, { d: sapView(set, record3) }, 201);
|
|
2274
|
+
}
|
|
2275
|
+
const record2 = key ? rows2.find((r) => r[SAP_SETS[set].key] === key) : void 0;
|
|
2276
|
+
if (!record2) return key ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
|
|
2277
|
+
if (method === "PATCH" || method === "MERGE") {
|
|
2278
|
+
if (!flat(body) || SAP_SETS[set].key in body) return;
|
|
2279
|
+
Object.assign(record2, body);
|
|
2280
|
+
return write2(collection, record2, null, 204);
|
|
2281
|
+
}
|
|
2282
|
+
};
|
|
2283
|
+
graphError = (status, code, message, sequence) => ({ status, body: { error: { code, message, innerError: { date: iso2(sequence), "request-id": hash(`graph:${sequence}:${code}`).slice(0, 36) } } } });
|
|
2284
|
+
graphId = (seed) => {
|
|
2285
|
+
const h = hash(seed);
|
|
2286
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
|
|
2287
|
+
};
|
|
2288
|
+
graphPage = (rows2, query) => {
|
|
2289
|
+
const where = query.$filter ? eqFilter(query.$filter, "'") : () => true, top = limitOf(query.$top, 100, 999);
|
|
2290
|
+
if (!where || top === null) return null;
|
|
2291
|
+
const select = query.$select?.split(",").map((s) => s.trim());
|
|
2292
|
+
return rows2.filter(where).slice(0, top).map((r) => select ? Object.fromEntries([["id", r.id], ...select.map((s) => [s, r[s] ?? null])]) : r);
|
|
2293
|
+
};
|
|
2294
|
+
teams = (method, path, body, query, _headers, data, sequence) => {
|
|
2295
|
+
const m = /^\/v1\.0\/(?:teams\/([\w-]+)\/channels(?:\/([\w:@.%-]+)\/messages(?:\/(\d+)\/replies)?)?|chats\/([\w:@.%-]+)\/messages)$/.exec(path);
|
|
2296
|
+
if (!m) return;
|
|
2297
|
+
const [, teamId, rawChannel, parentId, rawChat] = m, channels = table(data, "/channels"), messages = table(data, "/messages");
|
|
2298
|
+
if (teamId && !rawChannel && method === "GET") return read("/channels", { value: channels.filter((c) => c.teamId === teamId) });
|
|
2299
|
+
const channelId = rawChannel && decodeURIComponent(rawChannel), chatId = rawChat && decodeURIComponent(rawChat);
|
|
2300
|
+
const exists = channelId ? channels.some((c) => c.teamId === teamId && c.id === channelId) : table(data, "/chats").some((c) => c.id === chatId);
|
|
2301
|
+
if (!exists) return { ...graphError(404, "NotFound", "Resource not found", sequence), collection: "/messages" };
|
|
2302
|
+
const scope = (r) => channelId ? r.channelIdentity?.channelId === channelId && r.channelIdentity?.teamId === teamId : r.chatId === chatId;
|
|
2303
|
+
if (method === "GET") {
|
|
2304
|
+
const page = graphPage(messages.filter((r) => scope(r) && (parentId ? r.replyToId === parentId : !r.replyToId)), query);
|
|
2305
|
+
return page ? read("/messages", { "@odata.count": page.length, value: page }) : void 0;
|
|
2306
|
+
}
|
|
2307
|
+
if (method !== "POST") return;
|
|
2308
|
+
if (!isObject2(body.body) || typeof body.body.content !== "string" || !body.body.content.trim()) return { ...graphError(400, "BadRequest", "Missing body content", sequence), collection: "/messages" };
|
|
2309
|
+
if (body.body.contentType !== void 0 && !["text", "html"].includes(body.body.contentType)) return;
|
|
2310
|
+
if (parentId && !messages.some((r) => scope(r) && r.id === parentId)) return { ...graphError(404, "NotFound", "Resource not found", sequence), collection: "/messages" };
|
|
2311
|
+
const record2 = {
|
|
2312
|
+
id: String((EPOCH2 + sequence) * 1e3 + messages.length),
|
|
2313
|
+
replyToId: parentId ?? null,
|
|
2314
|
+
messageType: "message",
|
|
2315
|
+
createdDateTime: iso2(sequence),
|
|
2316
|
+
lastModifiedDateTime: iso2(sequence),
|
|
2317
|
+
importance: body.importance ?? "normal",
|
|
2318
|
+
subject: body.subject ?? null,
|
|
2319
|
+
body: { contentType: body.body.contentType ?? "text", content: body.body.content },
|
|
2320
|
+
from: { application: null, user: { id: "agenttwin-app", displayName: "Agent" } },
|
|
2321
|
+
...channelId ? { channelIdentity: { teamId, channelId } } : { chatId },
|
|
2322
|
+
attachments: [],
|
|
2323
|
+
mentions: []
|
|
2324
|
+
};
|
|
2325
|
+
messages.push(record2);
|
|
2326
|
+
return write2("/messages", record2, record2, 201);
|
|
2327
|
+
};
|
|
2328
|
+
address = (r) => isObject2(r) && isObject2(r.emailAddress) && typeof r.emailAddress.address === "string" && /^[^@\s]+@[^@\s]+$/.test(r.emailAddress.address);
|
|
2329
|
+
outlook = (method, path, body, query, _headers, data, sequence) => {
|
|
2330
|
+
const m = /^\/v1\.0\/(?:me|users\/[^/]+)\/(sendMail|messages|mailFolders\/(inbox|sentitems)\/messages|messages\/([\w=-]+)(?:\/(reply))?)$/.exec(path);
|
|
2331
|
+
if (!m) return;
|
|
2332
|
+
const messages = table(data, "/messages"), [, route, folder, id, reply] = m;
|
|
2333
|
+
const store = (message, parentFolderId) => {
|
|
2334
|
+
const record3 = {
|
|
2335
|
+
id: Buffer.from(hash(`outlook:${sequence}:${messages.length}`).slice(0, 30)).toString("base64url"),
|
|
2336
|
+
createdDateTime: iso2(sequence),
|
|
2337
|
+
sentDateTime: iso2(sequence),
|
|
2338
|
+
receivedDateTime: iso2(sequence),
|
|
2339
|
+
subject: message.subject ?? "",
|
|
2340
|
+
body: message.body ?? { contentType: "text", content: "" },
|
|
2341
|
+
toRecipients: message.toRecipients ?? [],
|
|
2342
|
+
ccRecipients: message.ccRecipients ?? [],
|
|
2343
|
+
from: { emailAddress: { address: "agent@contoso.test", name: "Agent" } },
|
|
2344
|
+
isRead: true,
|
|
2345
|
+
isDraft: false,
|
|
2346
|
+
importance: message.importance ?? "normal",
|
|
2347
|
+
parentFolderId,
|
|
2348
|
+
conversationId: message.conversationId ?? graphId(`conv:${sequence}`)
|
|
2349
|
+
};
|
|
2350
|
+
messages.push(record3);
|
|
2351
|
+
return record3;
|
|
2352
|
+
};
|
|
2353
|
+
if (route === "sendMail" && method === "POST") {
|
|
2354
|
+
const message = body.message;
|
|
2355
|
+
if (!isObject2(message)) return { ...graphError(400, "ErrorInvalidRequest", "The message is missing.", sequence), collection: "/messages" };
|
|
2356
|
+
const recipients = [...message.toRecipients ?? [], ...message.ccRecipients ?? [], ...message.bccRecipients ?? []];
|
|
2357
|
+
if (!recipients.length || !recipients.every(address)) return { ...graphError(400, "ErrorInvalidRecipients", "At least one recipient isn't valid.", sequence), collection: "/messages" };
|
|
2358
|
+
if (message.attachments?.length) return;
|
|
2359
|
+
return write2("/messages", store(message, "sentitems"), null, 202);
|
|
2360
|
+
}
|
|
2361
|
+
if ((route === "messages" || folder) && method === "GET") {
|
|
2362
|
+
const page = graphPage(messages.filter((r) => !folder || r.parentFolderId === folder), query);
|
|
2363
|
+
return page ? read("/messages", { value: page }) : void 0;
|
|
2364
|
+
}
|
|
2365
|
+
const record2 = id ? messages.find((r) => r.id === id) : void 0;
|
|
2366
|
+
if (!record2) return id ? { ...graphError(404, "ErrorItemNotFound", "The specified object was not found in the store.", sequence), collection: "/messages" } : void 0;
|
|
2367
|
+
if (!reply && method === "GET") return read("/messages", record2);
|
|
2368
|
+
if (!reply && method === "PATCH") {
|
|
2369
|
+
if (Object.keys(body).some((k) => !["isRead", "categories", "importance", "flag"].includes(k))) return;
|
|
2370
|
+
Object.assign(record2, body);
|
|
2371
|
+
return write2("/messages", record2, record2);
|
|
2372
|
+
}
|
|
2373
|
+
if (reply && method === "POST") {
|
|
2374
|
+
const to = record2.parentFolderId === "sentitems" ? record2.toRecipients : [record2.from];
|
|
2375
|
+
return write2("/messages", store({ subject: `RE: ${record2.subject}`, body: { contentType: "text", content: String(body.comment ?? "") }, toRecipients: to, conversationId: record2.conversationId }, "sentitems"), null, 202);
|
|
2376
|
+
}
|
|
2377
|
+
};
|
|
2378
|
+
entra = (method, path, body, query, _headers, data, sequence) => {
|
|
2379
|
+
const m = /^\/v1\.0\/(users|groups)(?:\/([^/]+))?(?:\/members(?:\/([\w-]+))?(\/\$ref)?)?$/.exec(path);
|
|
2380
|
+
if (!m) return;
|
|
2381
|
+
const [, kind, rawKey, memberId, ref] = m, users = table(data, "/users"), groups2 = table(data, "/groups"), members = table(data, "/groupMembers");
|
|
2382
|
+
const key = rawKey && decodeURIComponent(rawKey), membersRoute = path.includes("/members");
|
|
2383
|
+
if (kind === "users" && !key) {
|
|
2384
|
+
if (method === "GET") {
|
|
2385
|
+
const page = graphPage(users, query);
|
|
2386
|
+
return page ? read("/users", { value: page }) : void 0;
|
|
2387
|
+
}
|
|
2388
|
+
if (method !== "POST") return;
|
|
2389
|
+
const required = ["accountEnabled", "displayName", "mailNickname", "userPrincipalName"];
|
|
2390
|
+
if (required.some((f) => body[f] === void 0) || !isObject2(body.passwordProfile) || typeof body.passwordProfile.password !== "string")
|
|
2391
|
+
return { ...graphError(400, "Request_BadRequest", `Invalid value specified for property '${required.find((f) => body[f] === void 0) ?? "passwordProfile"}' of resource 'User'.`, sequence), collection: "/users" };
|
|
2392
|
+
if (users.some((u) => String(u.userPrincipalName).toLowerCase() === String(body.userPrincipalName).toLowerCase()))
|
|
2393
|
+
return { ...graphError(400, "Request_BadRequest", "Another object with the same value for property userPrincipalName already exists.", sequence), collection: "/users" };
|
|
2394
|
+
const { passwordProfile: _secret, ...profile } = body;
|
|
2395
|
+
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) };
|
|
2396
|
+
users.push(record2);
|
|
2397
|
+
return write2("/users", record2, record2, 201);
|
|
2398
|
+
}
|
|
2399
|
+
if (kind === "groups" && !key && method === "GET") {
|
|
2400
|
+
const page = graphPage(groups2, query);
|
|
2401
|
+
return page ? read("/groups", { value: page }) : void 0;
|
|
2402
|
+
}
|
|
2403
|
+
if (kind === "users") {
|
|
2404
|
+
const user = users.find((u) => u.id === key || String(u.userPrincipalName).toLowerCase() === String(key).toLowerCase());
|
|
2405
|
+
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" };
|
|
2406
|
+
if (membersRoute) return;
|
|
2407
|
+
if (method === "GET") return read("/users", user);
|
|
2408
|
+
if (method === "PATCH") {
|
|
2409
|
+
if (Object.keys(body).some((k) => ["id", "userPrincipalName", "passwordProfile"].includes(k)) || !flat(body)) return;
|
|
2410
|
+
Object.assign(user, body);
|
|
2411
|
+
return write2("/users", user, null, 204);
|
|
2412
|
+
}
|
|
2413
|
+
if (method === "DELETE") {
|
|
2414
|
+
users.splice(users.indexOf(user), 1);
|
|
2415
|
+
for (const link of members.filter((l) => l.userId === user.id)) members.splice(members.indexOf(link), 1);
|
|
2416
|
+
return write2("/users", user, null, 204);
|
|
2417
|
+
}
|
|
2418
|
+
return;
|
|
2419
|
+
}
|
|
2420
|
+
const group = groups2.find((g) => g.id === key);
|
|
2421
|
+
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" };
|
|
2422
|
+
if (!membersRoute) return method === "GET" ? read("/groups", group) : void 0;
|
|
2423
|
+
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 })) });
|
|
2424
|
+
if (method === "POST" && !memberId && ref) {
|
|
2425
|
+
const target = /\/directoryObjects\/([\w-]+)$/.exec(String(body["@odata.id"] ?? ""))?.[1];
|
|
2426
|
+
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" };
|
|
2427
|
+
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" };
|
|
2428
|
+
const link = { id: `${group.id}:${target}`, groupId: group.id, userId: target, addedDateTime: iso2(sequence) };
|
|
2429
|
+
members.push(link);
|
|
2430
|
+
return write2("/groupMembers", link, null, 204);
|
|
2431
|
+
}
|
|
2432
|
+
if (method === "DELETE" && memberId && ref) {
|
|
2433
|
+
const link = members.find((l) => l.groupId === group.id && l.userId === memberId);
|
|
2434
|
+
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" };
|
|
2435
|
+
members.splice(members.indexOf(link), 1);
|
|
2436
|
+
return write2("/groupMembers", link, null, 204);
|
|
2437
|
+
}
|
|
2438
|
+
};
|
|
2439
|
+
oktaError = (status, errorCode, errorSummary, causes = []) => ({ status, body: { errorCode, errorSummary, errorLink: errorCode, errorId: `oae${hash(errorSummary).slice(0, 19)}`, errorCauses: causes.map((errorSummary2) => ({ errorSummary: errorSummary2 })) } });
|
|
2440
|
+
oktaId = (prefix, seed) => prefix + Buffer.from(hash(seed)).toString("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, 17);
|
|
2441
|
+
okta = (method, path, body, query, _headers, data, sequence) => {
|
|
2442
|
+
const m = /^\/api\/v1\/(users|groups)(?:\/([^/]+))?(?:\/(users)(?:\/([\w]+))?|\/lifecycle\/(activate|deactivate|suspend|unsuspend))?$/.exec(path);
|
|
2443
|
+
if (!m) return;
|
|
2444
|
+
const [, kind, rawKey, groupUsers, memberId, lifecycle] = m, users = table(data, "/users"), groups2 = table(data, "/groups"), memberships = table(data, "/groupMemberships");
|
|
2445
|
+
const key = rawKey && decodeURIComponent(rawKey);
|
|
2446
|
+
const notFound2 = (what, type) => ({ ...oktaError(404, "E0000007", `Not found: Resource not found: ${what} (${type})`), collection: `/${kind}` });
|
|
2447
|
+
if (kind === "users" && !key) {
|
|
2448
|
+
if (method === "GET") {
|
|
2449
|
+
const limit = limitOf(query.limit, 200, 200);
|
|
2450
|
+
if (limit === null) return;
|
|
2451
|
+
let rows2 = users;
|
|
2452
|
+
if (query.filter) {
|
|
2453
|
+
const where = eqFilter(query.filter, '"');
|
|
2454
|
+
if (!where) return;
|
|
2455
|
+
rows2 = rows2.filter(where);
|
|
2456
|
+
}
|
|
2457
|
+
if (query.q) {
|
|
2458
|
+
const q = query.q.toLowerCase();
|
|
2459
|
+
rows2 = rows2.filter((u) => ["firstName", "lastName", "email", "login"].some((f) => String(u.profile?.[f] ?? "").toLowerCase().startsWith(q)));
|
|
2460
|
+
}
|
|
2461
|
+
return read("/users", rows2.slice(0, limit));
|
|
2462
|
+
}
|
|
2463
|
+
if (method !== "POST") return;
|
|
2464
|
+
const profile = body.profile;
|
|
2465
|
+
if (!isObject2(profile) || !["firstName", "lastName", "email", "login"].every((f) => typeof profile[f] === "string" && profile[f]))
|
|
2466
|
+
return { ...oktaError(400, "E0000001", "Api validation failed: profile", ["profile: firstName, lastName, email and login are required"]), collection: "/users" };
|
|
2467
|
+
if (users.some((u) => String(u.profile?.login).toLowerCase() === String(profile.login).toLowerCase()))
|
|
2468
|
+
return { ...oktaError(400, "E0000001", "Api validation failed: login", ["login: An object with this field already exists in the current organization"]), collection: "/users" };
|
|
2469
|
+
const active = query.activate !== "false";
|
|
2470
|
+
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 } };
|
|
2471
|
+
users.push(record2);
|
|
2472
|
+
return write2("/users", record2, record2);
|
|
2473
|
+
}
|
|
2474
|
+
if (kind === "groups" && !key && method === "GET") {
|
|
2475
|
+
const q = query.q?.toLowerCase();
|
|
2476
|
+
return read("/groups", groups2.filter((g) => !q || String(g.profile?.name ?? "").toLowerCase().startsWith(q)));
|
|
2477
|
+
}
|
|
2478
|
+
if (kind === "users") {
|
|
2479
|
+
const user = users.find((u) => u.id === key || String(u.profile?.login).toLowerCase() === String(key).toLowerCase());
|
|
2480
|
+
if (!user) return notFound2(String(key), "User");
|
|
2481
|
+
if (lifecycle && method === "POST") {
|
|
2482
|
+
const from = user.status;
|
|
2483
|
+
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;
|
|
2484
|
+
if (!to) return { ...oktaError(400, "E0000001", `Api validation failed: Cannot ${lifecycle} a user with status ${from}`), collection: "/users" };
|
|
2485
|
+
Object.assign(user, { status: to, statusChanged: iso2(sequence), lastUpdated: iso2(sequence), ...to === "ACTIVE" ? { activated: iso2(sequence) } : {} });
|
|
2486
|
+
return write2("/users", user, {});
|
|
2487
|
+
}
|
|
2488
|
+
if (lifecycle || groupUsers) return;
|
|
2489
|
+
if (method === "GET") return read("/users", user);
|
|
2490
|
+
if (method === "POST") {
|
|
2491
|
+
if (!isObject2(body.profile) || Object.keys(body).some((k) => k !== "profile") || !flat(body.profile)) return;
|
|
2492
|
+
Object.assign(user.profile, body.profile, {});
|
|
2493
|
+
user.lastUpdated = iso2(sequence);
|
|
2494
|
+
return write2("/users", user, user);
|
|
2495
|
+
}
|
|
2496
|
+
if (method === "DELETE") {
|
|
2497
|
+
if (user.status !== "DEPROVISIONED") {
|
|
2498
|
+
Object.assign(user, { status: "DEPROVISIONED", statusChanged: iso2(sequence), lastUpdated: iso2(sequence) });
|
|
2499
|
+
return write2("/users", user, null, 204);
|
|
2500
|
+
}
|
|
2501
|
+
users.splice(users.indexOf(user), 1);
|
|
2502
|
+
for (const link of memberships.filter((l) => l.userId === user.id)) memberships.splice(memberships.indexOf(link), 1);
|
|
2503
|
+
return write2("/users", { ...user, status: "DELETED" }, null, 204);
|
|
2504
|
+
}
|
|
2505
|
+
return;
|
|
2506
|
+
}
|
|
2507
|
+
const group = groups2.find((g) => g.id === key);
|
|
2508
|
+
if (!group) return notFound2(String(key), "UserGroup");
|
|
2509
|
+
if (!groupUsers) return method === "GET" && !lifecycle ? read("/groups", group) : void 0;
|
|
2510
|
+
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));
|
|
2511
|
+
if (!memberId) return;
|
|
2512
|
+
if (!users.some((u) => u.id === memberId)) return { ...notFound2(memberId, "User"), collection: "/groupMemberships" };
|
|
2513
|
+
const existing = memberships.find((l) => l.groupId === group.id && l.userId === memberId);
|
|
2514
|
+
if (method === "PUT") {
|
|
2515
|
+
if (existing) return write2("/groupMemberships", existing, null, 204);
|
|
2516
|
+
const link = { id: `${group.id}:${memberId}`, groupId: group.id, userId: memberId, created: iso2(sequence) };
|
|
2517
|
+
memberships.push(link);
|
|
2518
|
+
return write2("/groupMemberships", link, null, 204);
|
|
2519
|
+
}
|
|
2520
|
+
if (method === "DELETE") {
|
|
2521
|
+
if (existing) memberships.splice(memberships.indexOf(existing), 1);
|
|
2522
|
+
return write2("/groupMemberships", existing ?? { groupId: group.id, userId: memberId }, null, 204);
|
|
2523
|
+
}
|
|
2524
|
+
};
|
|
2525
|
+
cfError = (status, code, title) => ({ status, body: { errors: [{ status, code, title, detail: null }] } });
|
|
2526
|
+
storage = (b) => isObject2(b) && b.representation === "storage" && typeof b.value === "string";
|
|
2527
|
+
confluence = (method, path, body, query, _headers, data, sequence) => {
|
|
2528
|
+
const m = /^\/wiki\/api\/v2\/(pages|spaces|footer-comments)(?:\/(\d+))?$/.exec(path);
|
|
2529
|
+
if (!m) return;
|
|
2530
|
+
const [, kind, id] = m, pages = table(data, "/pages"), spaces = table(data, "/spaces"), comments = table(data, "/comments");
|
|
2531
|
+
const view2 = (p) => {
|
|
2532
|
+
const { body: content, ...rest } = p;
|
|
2533
|
+
return query["body-format"] === "storage" ? { ...rest, body: { storage: content } } : rest;
|
|
2534
|
+
};
|
|
2535
|
+
const nextId2 = () => String(nextNumber([...pages, ...comments], "id", 98305));
|
|
2536
|
+
if (kind === "spaces" && method === "GET" && !id) return read("/spaces", { results: spaces, _links: {} });
|
|
2537
|
+
if (kind === "footer-comments" && method === "POST" && !id) {
|
|
2538
|
+
const page2 = pages.find((p) => p.id === String(body.pageId) && p.status !== "trashed");
|
|
2539
|
+
if (!page2) return { ...cfError(404, "NOT_FOUND", "Page not found"), collection: "/comments" };
|
|
2540
|
+
if (!storage(body.body)) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "Comment body must use the storage representation"), collection: "/comments" };
|
|
2541
|
+
const record2 = { id: nextId2(), pageId: page2.id, status: "current", title: `Re: ${page2.title}`, version: { number: 1, createdAt: iso2(sequence) }, body: body.body };
|
|
2542
|
+
comments.push(record2);
|
|
2543
|
+
return write2("/comments", record2, record2);
|
|
2544
|
+
}
|
|
2545
|
+
if (kind !== "pages") return;
|
|
2546
|
+
if (!id && method === "GET") {
|
|
2547
|
+
const limit = limitOf(query.limit, 25, 250);
|
|
2548
|
+
if (limit === null) return;
|
|
2549
|
+
const status = query.status ?? "current";
|
|
2550
|
+
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(view2), _links: {} });
|
|
2551
|
+
}
|
|
2552
|
+
if (!id && method === "POST") {
|
|
2553
|
+
if (!spaces.some((s) => s.id === String(body.spaceId))) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "Invalid space id"), collection: "/pages" };
|
|
2554
|
+
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" };
|
|
2555
|
+
if (pages.some((p) => p.spaceId === String(body.spaceId) && p.title === body.title && p.status !== "trashed"))
|
|
2556
|
+
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" };
|
|
2557
|
+
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 };
|
|
2558
|
+
pages.push(record2);
|
|
2559
|
+
return write2("/pages", record2, view2(record2));
|
|
2560
|
+
}
|
|
2561
|
+
const page = pages.find((p) => p.id === id && p.status !== "trashed");
|
|
2562
|
+
if (!page) return { ...cfError(404, "NOT_FOUND", "Page not found"), collection: "/pages" };
|
|
2563
|
+
if (method === "GET") return read("/pages", view2(page));
|
|
2564
|
+
if (method === "PUT") {
|
|
2565
|
+
const provided = isObject2(body.version) ? Number(body.version.number) : NaN;
|
|
2566
|
+
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" };
|
|
2567
|
+
if (typeof body.title !== "string" || !storage(body.body)) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "A page update requires title, body and version"), collection: "/pages" };
|
|
2568
|
+
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 ?? "" : "" } });
|
|
2569
|
+
return write2("/pages", page, view2(page));
|
|
2570
|
+
}
|
|
2571
|
+
if (method === "DELETE") {
|
|
2572
|
+
page.status = "trashed";
|
|
2573
|
+
return write2("/pages", page, null, 204);
|
|
2574
|
+
}
|
|
2575
|
+
};
|
|
2576
|
+
sharepoint = (method, path, body, query, _headers, data, sequence) => {
|
|
2577
|
+
const m = /^\/v1\.0\/sites\/([^/]+)\/(?:lists(?:\/([^/]+)\/items(?:\/(\d+)(\/fields)?)?)?|drive\/root\/children)$/.exec(path);
|
|
2578
|
+
if (!m) return;
|
|
2579
|
+
const [, siteId, listKey, itemId, fieldsRoute] = m, lists = table(data, "/lists"), items = table(data, "/listItems"), files = table(data, "/driveItems");
|
|
2580
|
+
if (path.endsWith("/drive/root/children")) {
|
|
2581
|
+
if (method === "GET") return read("/driveItems", { value: files.filter((f) => f.siteId === siteId) });
|
|
2582
|
+
if (method !== "POST" || typeof body.name !== "string" || !body.name || /[\\/:*?"<>|]/.test(body.name) || !isObject2(body.folder)) return;
|
|
2583
|
+
let name = body.name;
|
|
2584
|
+
if (files.some((f) => f.siteId === siteId && f.name === name)) {
|
|
2585
|
+
const behaviour = body["@microsoft.graph.conflictBehavior"] ?? "fail";
|
|
2586
|
+
if (behaviour !== "rename") return { ...graphError(409, "nameAlreadyExists", "The specified item name already exists.", sequence), collection: "/driveItems" };
|
|
2587
|
+
let n = 1;
|
|
2588
|
+
while (files.some((f) => f.siteId === siteId && f.name === `${body.name} ${n}`)) n++;
|
|
2589
|
+
name = `${body.name} ${n}`;
|
|
2590
|
+
}
|
|
2591
|
+
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)}` };
|
|
2592
|
+
files.push(record2);
|
|
2593
|
+
return write2("/driveItems", record2, record2, 201);
|
|
2594
|
+
}
|
|
2595
|
+
if (!listKey) return method === "GET" ? read("/lists", { value: lists.filter((l) => l.siteId === siteId) }) : void 0;
|
|
2596
|
+
const list2 = lists.find((l) => l.siteId === siteId && (l.id === listKey || l.displayName === decodeURIComponent(listKey)));
|
|
2597
|
+
if (!list2) return { ...graphError(404, "itemNotFound", "The requested list was not found.", sequence), collection: "/listItems" };
|
|
2598
|
+
const own = items.filter((i) => i.listId === list2.id);
|
|
2599
|
+
const view2 = (i, withFields = query.expand === "fields" || query.$expand === "fields") => {
|
|
2600
|
+
const { listId: _l, siteId: _s, fields, ...rest } = i;
|
|
2601
|
+
return withFields ? { ...rest, fields } : rest;
|
|
2602
|
+
};
|
|
2603
|
+
if (!itemId && method === "GET") {
|
|
2604
|
+
const top = limitOf(query.$top, 200, 5e3);
|
|
2605
|
+
return top === null ? void 0 : read("/listItems", { value: own.slice(0, top).map((i) => view2(i)) });
|
|
2606
|
+
}
|
|
2607
|
+
if (!itemId && method === "POST") {
|
|
2608
|
+
if (!isObject2(body.fields) || !flat(body.fields)) return { ...graphError(400, "invalidRequest", "Invalid request: fields are required.", sequence), collection: "/listItems" };
|
|
2609
|
+
const id = String(nextNumber(own, "id", 1));
|
|
2610
|
+
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 } };
|
|
2611
|
+
items.push(record2);
|
|
2612
|
+
return write2("/listItems", record2, view2(record2, true), 201);
|
|
2613
|
+
}
|
|
2614
|
+
const item = own.find((i) => i.id === itemId);
|
|
2615
|
+
if (!item) return { ...graphError(404, "itemNotFound", "The resource could not be found.", sequence), collection: "/listItems" };
|
|
2616
|
+
if (method === "GET" && !fieldsRoute) return read("/listItems", view2(item));
|
|
2617
|
+
if (method === "PATCH" && fieldsRoute) {
|
|
2618
|
+
if (!flat(body) || "id" in body) return;
|
|
2619
|
+
Object.assign(item.fields, body);
|
|
2620
|
+
item.lastModifiedDateTime = iso2(sequence);
|
|
2621
|
+
return write2("/listItems", item, item.fields);
|
|
2622
|
+
}
|
|
2623
|
+
if (method === "DELETE" && !fieldsRoute) {
|
|
2624
|
+
items.splice(items.indexOf(item), 1);
|
|
2625
|
+
return write2("/listItems", item, null, 204);
|
|
2626
|
+
}
|
|
2627
|
+
};
|
|
2628
|
+
sfSqlValue = (token, bindings, counter) => {
|
|
2629
|
+
if (token === "?") {
|
|
2630
|
+
const b = bindings[String(++counter.n)];
|
|
2631
|
+
return isObject2(b) ? String(b.type).toUpperCase() === "FIXED" || String(b.type).toUpperCase() === "REAL" ? Number(b.value) : b.value : void 0;
|
|
2632
|
+
}
|
|
2633
|
+
if (/^'.*'$/s.test(token)) return token.slice(1, -1).replace(/''/g, "'");
|
|
2634
|
+
if (/^null$/i.test(token)) return null;
|
|
2635
|
+
if (/^(true|false)$/i.test(token)) return token.toLowerCase() === "true";
|
|
2636
|
+
if (/^-?\d+(\.\d+)?$/.test(token)) return Number(token);
|
|
2637
|
+
return void 0;
|
|
2638
|
+
};
|
|
2639
|
+
VALUE = `('(?:[^']|'')*'|\\?|-?\\d+(?:\\.\\d+)?|null|true|false)`;
|
|
2640
|
+
ident = (name) => name.startsWith('"') ? name.slice(1, -1) : name.toUpperCase();
|
|
2641
|
+
snowflake = (method, path, body, _query, _headers, data, sequence) => {
|
|
2642
|
+
const m = /^\/api\/v2\/statements(?:\/([\w-]+))?$/.exec(path);
|
|
2643
|
+
if (!m) return;
|
|
2644
|
+
const log = table(data, "/statements");
|
|
2645
|
+
if (m[1]) {
|
|
2646
|
+
if (method !== "GET") return;
|
|
2647
|
+
const done = log.find((s2) => s2.statementHandle === m[1]);
|
|
2648
|
+
return done ? read("/statements", done.result) : { status: 404, collection: "/statements", body: { code: "333334", message: `Statement ${m[1]} not found`, statementHandle: m[1] } };
|
|
2649
|
+
}
|
|
2650
|
+
if (method !== "POST" || typeof body.statement !== "string") return;
|
|
2651
|
+
const statement = body.statement.trim().replace(/;\s*$/, ""), bindings = isObject2(body.bindings) ? body.bindings : {}, counter = { n: 0 };
|
|
2652
|
+
const handle = graphId(`snowflake:${sequence}:${log.length}`);
|
|
2653
|
+
const missing = (name) => ({ status: 422, collection: "/statements", body: { code: "002003", message: `SQL compilation error:
|
|
2654
|
+
Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCase()}' does not exist or not authorized.`, sqlState: "02000", statementHandle: handle } });
|
|
2655
|
+
const known2 = (name) => Object.hasOwn(data, `/${name}`) && name !== "STATEMENTS";
|
|
2656
|
+
const result = (columns, rows2, dml) => ({
|
|
2657
|
+
resultSetMetaData: { numRows: rows2.length, format: "jsonv2", partitionInfo: [{ rowCount: rows2.length }], rowType: columns.map((name) => ({ name: dml ?? name, type: dml ? "fixed" : "text", nullable: !dml })) },
|
|
2658
|
+
data: rows2.map((r) => r.map((v) => v === null || v === void 0 ? null : String(v))),
|
|
2659
|
+
code: "090001",
|
|
2660
|
+
statementStatusUrl: `/api/v2/statements/${handle}`,
|
|
2661
|
+
requestId: graphId(`sf-req:${sequence}`),
|
|
2662
|
+
sqlState: "00000",
|
|
2663
|
+
statementHandle: handle,
|
|
2664
|
+
message: "Statement executed successfully.",
|
|
2665
|
+
createdOn: (EPOCH2 + sequence) * 1e3
|
|
2666
|
+
});
|
|
2667
|
+
const remember = (collection, res, operation, record2) => {
|
|
2668
|
+
log.push({ statementHandle: handle, statement, result: res, createdOn: iso2(sequence) });
|
|
2669
|
+
return operation === "read" ? read(collection, res) : write2(collection, record2 ?? { statement }, res);
|
|
2670
|
+
};
|
|
2671
|
+
let s;
|
|
2672
|
+
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)) {
|
|
2673
|
+
const name = ident(s[2]);
|
|
2674
|
+
if (!known2(name)) return missing(name);
|
|
2675
|
+
const where = sqlWhere(s[3], bindings, counter);
|
|
2676
|
+
if (!where) return;
|
|
2677
|
+
let rows2 = data[`/${name}`].filter(where);
|
|
2678
|
+
if (s[4]) {
|
|
2679
|
+
const col = ident(s[4]), dir = s[5]?.toUpperCase() === "DESC" ? -1 : 1;
|
|
2680
|
+
rows2 = [...rows2].sort((a, b) => (a[col] > b[col] ? 1 : a[col] < b[col] ? -1 : 0) * dir);
|
|
2681
|
+
}
|
|
2682
|
+
if (s[6]) rows2 = rows2.slice(0, Number(s[6]));
|
|
2683
|
+
const columns = s[1].trim() === "*" ? [...new Set(data[`/${name}`].flatMap((r) => Object.keys(r)))] : s[1].split(",").map((c) => ident(c.trim()));
|
|
2684
|
+
if (columns.some((c) => !/^[\w$]+$/.test(c))) return;
|
|
2685
|
+
return remember(`/${name}`, result(columns, rows2.map((r) => columns.map((c) => r[c] ?? null))), "read");
|
|
2686
|
+
}
|
|
2687
|
+
if (s = /^INSERT\s+INTO\s+("?[\w$]+"?)\s*\(([^)]+)\)\s*VALUES\s*(.+)$/is.exec(statement)) {
|
|
2688
|
+
const name = ident(s[1]);
|
|
2689
|
+
if (!known2(name)) return missing(name);
|
|
2690
|
+
const columns = s[2].split(",").map((c) => ident(c.trim())), inserted = [];
|
|
2691
|
+
const tuples = s[3].match(new RegExp(`\\(\\s*${VALUE}(?:\\s*,\\s*${VALUE})*\\s*\\)`, "gi"));
|
|
2692
|
+
if (!tuples || tuples.join(",").replace(/\s/g, "") !== s[3].replace(/\s/g, "")) return;
|
|
2693
|
+
for (const tuple of tuples) {
|
|
2694
|
+
const values = tuple.slice(1, -1).match(new RegExp(VALUE, "gi")).map((v) => sfSqlValue(v, bindings, counter));
|
|
2695
|
+
if (values.length !== columns.length || values.some((v) => v === void 0)) return;
|
|
2696
|
+
inserted.push(Object.fromEntries(columns.map((c, i) => [c, values[i]])));
|
|
2697
|
+
}
|
|
2698
|
+
data[`/${name}`].push(...inserted);
|
|
2699
|
+
return remember(`/${name}`, result(["number of rows inserted"], [[inserted.length]], "number of rows inserted"), "write", inserted.length === 1 ? inserted[0] : { rows: inserted });
|
|
2700
|
+
}
|
|
2701
|
+
if (s = /^UPDATE\s+("?[\w$]+"?)\s+SET\s+(.+?)(?:\s+WHERE\s+(.+))?$/is.exec(statement)) {
|
|
2702
|
+
const name = ident(s[1]);
|
|
2703
|
+
if (!known2(name)) return missing(name);
|
|
2704
|
+
const sets = [];
|
|
2705
|
+
for (const assignment of s[2].split(/\s*,\s*(?=(?:[^']*'[^']*')*[^']*$)/)) {
|
|
2706
|
+
const a = new RegExp(`^\\s*("?[\\w$]+"?)\\s*=\\s*${VALUE}\\s*$`, "i").exec(assignment);
|
|
2707
|
+
if (!a) return;
|
|
2708
|
+
const value = sfSqlValue(a[2], bindings, counter);
|
|
2709
|
+
if (value === void 0) return;
|
|
2710
|
+
sets.push([ident(a[1]), value]);
|
|
2711
|
+
}
|
|
2712
|
+
const where = sqlWhere(s[3], bindings, counter);
|
|
2713
|
+
if (!where) return;
|
|
2714
|
+
const changed = data[`/${name}`].filter(where);
|
|
2715
|
+
for (const row of changed) for (const [k, v] of sets) row[k] = v;
|
|
2716
|
+
return remember(`/${name}`, { ...result(["number of rows updated"], [[changed.length]], "number of rows updated") }, "write", changed.length === 1 ? changed[0] : { rows: changed });
|
|
2717
|
+
}
|
|
2718
|
+
if (s = /^DELETE\s+FROM\s+("?[\w$]+"?)(?:\s+WHERE\s+(.+))?$/is.exec(statement)) {
|
|
2719
|
+
const name = ident(s[1]);
|
|
2720
|
+
if (!known2(name)) return missing(name);
|
|
2721
|
+
const where = sqlWhere(s[2], bindings, counter);
|
|
2722
|
+
if (!where) return;
|
|
2723
|
+
const removed = data[`/${name}`].filter(where);
|
|
2724
|
+
data[`/${name}`] = data[`/${name}`].filter((r) => !removed.includes(r));
|
|
2725
|
+
return remember(`/${name}`, result(["number of rows deleted"], [[removed.length]], "number of rows deleted"), "write", { deleted: removed });
|
|
2726
|
+
}
|
|
2727
|
+
};
|
|
2728
|
+
NS_TYPES = ["customer", "vendor", "salesOrder", "invoice", "vendorBill"];
|
|
2729
|
+
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 }] } });
|
|
2730
|
+
nsLink = (type, id) => [{ rel: "self", href: `/services/rest/record/v1/${type}/${id}` }];
|
|
2731
|
+
netsuite = (method, path, body, query, _headers, data, sequence) => {
|
|
2732
|
+
const m = /^\/services\/rest\/record\/v1\/(\w+)(?:\/(\d+))?$/.exec(path);
|
|
2733
|
+
if (!m || !NS_TYPES.includes(m[1])) return;
|
|
2734
|
+
const [, type, id] = m, collection = `/${type}`, rows2 = table(data, collection);
|
|
2735
|
+
if (!id && method === "GET") {
|
|
2736
|
+
const limit = limitOf(query.limit, 1e3, 1e3), offset = Number(query.offset ?? 0);
|
|
2737
|
+
if (limit === null || !Number.isInteger(offset) || offset < 0) return;
|
|
2738
|
+
let matched = rows2;
|
|
2739
|
+
if (query.q) {
|
|
2740
|
+
const tests = query.q.split(/\s+AND\s+/i).map((part) => /^\s*(\w+)\s+(IS|IS_NOT)\s+"([^"]*)"\s*$/i.exec(part));
|
|
2741
|
+
if (tests.some((t) => !t)) return;
|
|
2742
|
+
matched = rows2.filter((r) => tests.every((t) => String(r[t[1]] ?? "") === t[3] === (t[2].toUpperCase() === "IS")));
|
|
2743
|
+
}
|
|
2744
|
+
const page = matched.slice(offset, offset + limit);
|
|
2745
|
+
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 });
|
|
2746
|
+
}
|
|
2747
|
+
if (!id && method === "POST") {
|
|
2748
|
+
const entity = isObject2(body.entity) ? String(body.entity.id) : void 0;
|
|
2749
|
+
if (type === "customer" && !body.companyName && !(body.isPerson && body.lastName)) return { ...nsError(400, "Bad Request", "Please enter value(s) for: Company Name", "USER_ERROR"), collection };
|
|
2750
|
+
if (type === "vendor" && !body.companyName) return { ...nsError(400, "Bad Request", "Please enter value(s) for: Company Name", "USER_ERROR"), collection };
|
|
2751
|
+
let total;
|
|
2752
|
+
if (["salesOrder", "invoice", "vendorBill"].includes(type)) {
|
|
2753
|
+
const party = type === "vendorBill" ? "/vendor" : "/customer";
|
|
2754
|
+
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 };
|
|
2755
|
+
const lines = isObject2(body.item) && Array.isArray(body.item.items) ? body.item.items : null;
|
|
2756
|
+
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 };
|
|
2757
|
+
total = lines.reduce((sum, l) => sum + Number(l.quantity) * Number(l.rate ?? 0), 0);
|
|
2758
|
+
}
|
|
2759
|
+
const newId2 = String(nextNumber(rows2, "id", 1001));
|
|
2760
|
+
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) };
|
|
2761
|
+
rows2.push(record3);
|
|
2762
|
+
return write2(collection, record3, null, 204, { location: `/services/rest/record/v1/${type}/${newId2}` });
|
|
2763
|
+
}
|
|
2764
|
+
const record2 = id ? rows2.find((r) => r.id === id) : void 0;
|
|
2765
|
+
if (!record2) return { ...nsError(404, "Record Not Found", "The record instance does not exist. Provide a valid record instance ID.", "NONEXISTENT_ID"), collection };
|
|
2766
|
+
if (method === "GET") return read(collection, { links: nsLink(type, record2.id), ...record2 });
|
|
2767
|
+
if (method === "PATCH") {
|
|
2768
|
+
if ("id" in body) return;
|
|
2769
|
+
Object.assign(record2, body, { lastModifiedDate: iso2(sequence) });
|
|
2770
|
+
return write2(collection, record2, null, 204);
|
|
2771
|
+
}
|
|
2772
|
+
if (method === "DELETE") {
|
|
2773
|
+
rows2.splice(rows2.indexOf(record2), 1);
|
|
2774
|
+
return write2(collection, record2, null, 204);
|
|
2775
|
+
}
|
|
2776
|
+
};
|
|
2777
|
+
pdError = (status, message, code, errors = []) => ({ status, body: { error: { message, code, errors } } });
|
|
2778
|
+
pdId = (seed) => "P" + hash(seed).replace(/[^A-Z0-9]/gi, "").toUpperCase().slice(0, 6);
|
|
2779
|
+
pagerduty = (method, path, body, query, headers, data, sequence) => {
|
|
2780
|
+
const services = table(data, "/services"), incidents = table(data, "/incidents"), notes = table(data, "/notes"), events = table(data, "/events");
|
|
2781
|
+
const open = (serviceId, key) => incidents.find((i) => i.service.id === serviceId && i.incident_key === key && i.status !== "resolved");
|
|
2782
|
+
const create = (service, title, urgency, key, details) => {
|
|
2783
|
+
const id2 = pdId(`pd:incident:${sequence}:${incidents.length}`);
|
|
2784
|
+
const record2 = {
|
|
2785
|
+
id: id2,
|
|
2786
|
+
type: "incident",
|
|
2787
|
+
summary: `[#${incidents.length + 1}] ${title}`,
|
|
2788
|
+
incident_number: nextNumber(incidents, "incident_number", 1),
|
|
2789
|
+
title,
|
|
2790
|
+
status: "triggered",
|
|
2791
|
+
urgency,
|
|
2792
|
+
created_at: iso2(sequence),
|
|
2793
|
+
updated_at: iso2(sequence),
|
|
2794
|
+
incident_key: key,
|
|
2795
|
+
service: { id: service.id, type: "service_reference", summary: service.name },
|
|
2796
|
+
html_url: `https://contoso.pagerduty.test/incidents/${id2}`,
|
|
2797
|
+
...details === void 0 ? {} : { body: { type: "incident_body", details } }
|
|
2798
|
+
};
|
|
2799
|
+
incidents.push(record2);
|
|
2800
|
+
return record2;
|
|
2801
|
+
};
|
|
2802
|
+
if (path === "/v2/enqueue" && method === "POST") {
|
|
2803
|
+
const service = services.find((s) => s.integration_key && s.integration_key === body.routing_key);
|
|
2804
|
+
if (!service) return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["Invalid routing key"] } };
|
|
2805
|
+
const action = body.event_action, payload = body.payload;
|
|
2806
|
+
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')"] } };
|
|
2807
|
+
if (action === "trigger" && !(isObject2(payload) && payload.summary && payload.source && ["critical", "error", "warning", "info"].includes(payload.severity)))
|
|
2808
|
+
return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'payload.summary', 'payload.source' and 'payload.severity' are required"] } };
|
|
2809
|
+
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"] } };
|
|
2810
|
+
const key = String(body.dedup_key ?? hash(`pd:dedup:${sequence}`).slice(0, 32));
|
|
2811
|
+
const existing = open(service.id, key);
|
|
2812
|
+
if (action === "trigger" && !existing) create(service, payload.summary, payload.severity === "critical" || payload.severity === "error" ? "high" : "low", key, payload.custom_details);
|
|
2813
|
+
if (action !== "trigger" && existing) Object.assign(existing, { status: action === "acknowledge" ? "acknowledged" : "resolved", updated_at: iso2(sequence) });
|
|
2814
|
+
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) };
|
|
2815
|
+
events.push(event);
|
|
2816
|
+
return write2("/events", event, { status: "success", message: "Event processed", dedup_key: key }, 202);
|
|
2817
|
+
}
|
|
2818
|
+
const m = /^\/(incidents|services)(?:\/(\w+))?(?:\/(notes))?$/.exec(path);
|
|
2819
|
+
if (!m) return;
|
|
2820
|
+
const [, kind, id, noteRoute] = m;
|
|
2821
|
+
const from = header2(headers, "from");
|
|
2822
|
+
const needsFrom = () => ({ ...pdError(400, `You must specify a user's email address in the "From" header to perform this action`, 2001), collection: "/incidents" });
|
|
2823
|
+
if (kind === "services") return method === "GET" && !id && !noteRoute ? read("/services", { services, limit: 25, offset: 0, total: null, more: false }) : void 0;
|
|
2824
|
+
if (!id && method === "GET") {
|
|
2825
|
+
const limit = limitOf(query.limit, 25, 100), offset = Number(query.offset ?? 0), statuses = query["statuses[]"] ?? query.statuses;
|
|
2826
|
+
if (limit === null || !Number.isInteger(offset) || offset < 0) return;
|
|
2827
|
+
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));
|
|
2828
|
+
return read("/incidents", { incidents: matched.slice(offset, offset + limit), limit, offset, total: null, more: offset + limit < matched.length });
|
|
2829
|
+
}
|
|
2830
|
+
if (!id && method === "POST") {
|
|
2831
|
+
if (!from) return needsFrom();
|
|
2832
|
+
const input = body.incident;
|
|
2833
|
+
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" };
|
|
2834
|
+
const service = services.find((s) => s.id === input.service.id);
|
|
2835
|
+
if (!service) return { ...pdError(400, "Invalid Input Provided", 2001, ["Service not found"]), collection: "/incidents" };
|
|
2836
|
+
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" };
|
|
2837
|
+
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);
|
|
2838
|
+
return write2("/incidents", record2, { incident: record2 }, 201);
|
|
2839
|
+
}
|
|
2840
|
+
const incident = incidents.find((i) => i.id === id);
|
|
2841
|
+
if (!incident) return { ...pdError(404, "Not Found", 2100), collection: "/incidents" };
|
|
2842
|
+
if (noteRoute) {
|
|
2843
|
+
if (method === "GET") return read("/notes", { notes: notes.filter((n) => n.incident_id === incident.id) });
|
|
2844
|
+
if (method !== "POST") return;
|
|
2845
|
+
if (!from) return needsFrom();
|
|
2846
|
+
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" };
|
|
2847
|
+
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 } };
|
|
2848
|
+
notes.push(note);
|
|
2849
|
+
return write2("/notes", note, { note }, 201);
|
|
2850
|
+
}
|
|
2851
|
+
if (method === "GET") return read("/incidents", { incident });
|
|
2852
|
+
if (method === "PUT") {
|
|
2853
|
+
if (!from) return needsFrom();
|
|
2854
|
+
const input = body.incident;
|
|
2855
|
+
if (!isObject2(input) || !["acknowledged", "resolved"].includes(input.status ?? "") && input.urgency === void 0 && input.title === void 0) return;
|
|
2856
|
+
if (incident.status === "resolved" && input.status === "acknowledged") return { ...pdError(400, "Invalid Input Provided", 2001, ["Incident Already Resolved"]), collection: "/incidents" };
|
|
2857
|
+
Object.assign(incident, Object.fromEntries(["status", "urgency", "title"].filter((k) => input[k] !== void 0).map((k) => [k, input[k]])), { updated_at: iso2(sequence) });
|
|
2858
|
+
return write2("/incidents", incident, { incident });
|
|
2859
|
+
}
|
|
2860
|
+
};
|
|
2861
|
+
ENTERPRISE_OPERATIONS = {
|
|
2862
|
+
salesforce,
|
|
2863
|
+
servicenow,
|
|
2864
|
+
workday,
|
|
2865
|
+
sap,
|
|
2866
|
+
"microsoft-teams": teams,
|
|
2867
|
+
outlook,
|
|
2868
|
+
"entra-id": entra,
|
|
2869
|
+
okta,
|
|
2870
|
+
confluence,
|
|
2871
|
+
sharepoint,
|
|
2872
|
+
snowflake,
|
|
2873
|
+
netsuite,
|
|
2874
|
+
pagerduty
|
|
2875
|
+
};
|
|
2876
|
+
ENTERPRISE_OPTIONAL_COLLECTIONS = {
|
|
2877
|
+
salesforce: Object.keys(SF_OBJECTS).map((o) => `/sobjects/${o}`),
|
|
2878
|
+
servicenow: Object.keys(SN_TABLES).map((t) => `/${t}`),
|
|
2879
|
+
workday: ["/workers", "/timeOffRequests"],
|
|
2880
|
+
sap: ["/A_BusinessPartner", "/A_SalesOrder"],
|
|
2881
|
+
"microsoft-teams": ["/channels", "/chats", "/messages"],
|
|
2882
|
+
outlook: ["/messages"],
|
|
2883
|
+
"entra-id": ["/users", "/groups", "/groupMembers"],
|
|
2884
|
+
okta: ["/users", "/groups", "/groupMemberships"],
|
|
2885
|
+
confluence: ["/pages", "/spaces", "/comments"],
|
|
2886
|
+
sharepoint: ["/lists", "/listItems", "/driveItems"],
|
|
2887
|
+
snowflake: ["/statements"],
|
|
2888
|
+
netsuite: NS_TYPES.map((t) => `/${t}`),
|
|
2889
|
+
pagerduty: ["/services", "/incidents", "/notes", "/events"]
|
|
2890
|
+
};
|
|
2891
|
+
FREEFORM_COLLECTION_ADAPTERS = ["snowflake"];
|
|
2892
|
+
unsupported = (body) => ({ ...body, forwardedToProduction: false });
|
|
2893
|
+
ENTERPRISE_UNSUPPORTED = {
|
|
2894
|
+
salesforce: [unsupported({ errorCode: "UNSUPPORTED_OPERATION", message: "Outside the AgentTwin Salesforce REST subset" })],
|
|
2895
|
+
servicenow: unsupported({ error: { message: "Unsupported operation", detail: "Outside the AgentTwin ServiceNow Table API subset" }, status: "failure" }),
|
|
2896
|
+
workday: unsupported({ error: "Unsupported operation", errors: [{ error: "Outside the AgentTwin Workday REST subset" }] }),
|
|
2897
|
+
sap: unsupported({ error: { code: "UNSUPPORTED", message: { lang: "en", value: "Outside the AgentTwin SAP OData subset" } } }),
|
|
2898
|
+
"microsoft-teams": unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Microsoft Teams Graph subset" } }),
|
|
2899
|
+
outlook: unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Outlook mail Graph subset" } }),
|
|
2900
|
+
"entra-id": unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Entra ID Graph subset" } }),
|
|
2901
|
+
okta: unsupported({ errorCode: "E0000022", errorSummary: "The endpoint does not support the provided HTTP method", errorCauses: [{ errorSummary: "Outside the AgentTwin Okta subset" }] }),
|
|
2902
|
+
confluence: unsupported({ errors: [{ status: 501, code: "UNSUPPORTED", title: "Outside the AgentTwin Confluence v2 subset" }] }),
|
|
2903
|
+
sharepoint: unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin SharePoint Graph subset" } }),
|
|
2904
|
+
snowflake: unsupported({ code: "000002", message: "Statement or SQL feature outside the AgentTwin Snowflake subset (single-table SELECT/INSERT/UPDATE/DELETE with equality filters)" }),
|
|
2905
|
+
netsuite: unsupported({ title: "Unsupported", status: 501, "o:errorDetails": [{ detail: "Outside the AgentTwin NetSuite REST record subset", "o:errorCode": "UNSUPPORTED" }] }),
|
|
2906
|
+
pagerduty: unsupported({ error: { message: "Outside the AgentTwin PagerDuty subset", code: 2e3 } })
|
|
2907
|
+
};
|
|
2908
|
+
op = (method, endpoint, effect, errors = []) => ({ method, endpoint, effect, parameters: [], errors });
|
|
2909
|
+
ENTERPRISE_CONTRACTS = {
|
|
2910
|
+
salesforce: {
|
|
2911
|
+
version: "1.0.0",
|
|
2912
|
+
authentication: "Bearer run-scoped test token (OAuth access token shape)",
|
|
2913
|
+
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"])],
|
|
2914
|
+
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"]
|
|
2915
|
+
},
|
|
2916
|
+
servicenow: {
|
|
2917
|
+
version: "1.0.0",
|
|
2918
|
+
authentication: "Bearer run-scoped test token",
|
|
2919
|
+
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)")],
|
|
2920
|
+
limitations: ["Five tables; no ^OR, LIKE, ORDERBY, dot-walking, display values, business rules, ACLs or workflows"]
|
|
2921
|
+
},
|
|
2922
|
+
workday: {
|
|
2923
|
+
version: "1.0.0",
|
|
2924
|
+
authentication: "Bearer run-scoped test token",
|
|
2925
|
+
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")],
|
|
2926
|
+
limitations: ["Workers and time off only; business processes never advance past Submitted", "No SOAP Web Services, RaaS reports, compensation, hiring or approvals"]
|
|
2927
|
+
},
|
|
2928
|
+
sap: {
|
|
2929
|
+
version: "1.0.0",
|
|
2930
|
+
authentication: "Bearer run-scoped test token; writes require the x-csrf-token fetched by a prior GET (x-csrf-token: Fetch)",
|
|
2931
|
+
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)")],
|
|
2932
|
+
limitations: ["OData v2 JSON only; no $expand, $batch, $orderby, pricing, ATP checks or delivery/billing documents"]
|
|
2933
|
+
},
|
|
2934
|
+
"microsoft-teams": {
|
|
2935
|
+
version: "1.0.0",
|
|
2936
|
+
authentication: "Bearer run-scoped test token (Graph access token shape)",
|
|
2937
|
+
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")],
|
|
2938
|
+
limitations: ["No adaptive card rendering, mentions resolution, reactions, edits, deletes, meetings or change notifications"]
|
|
2939
|
+
},
|
|
2940
|
+
outlook: {
|
|
2941
|
+
version: "1.0.0",
|
|
2942
|
+
authentication: "Bearer run-scoped test token (Graph access token shape)",
|
|
2943
|
+
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)")],
|
|
2944
|
+
limitations: ["No attachments, drafts, forward, rules, calendar or delta queries; inbound mail exists only as seeded records"]
|
|
2945
|
+
},
|
|
2946
|
+
"entra-id": {
|
|
2947
|
+
version: "1.0.0",
|
|
2948
|
+
authentication: "Bearer run-scoped test token (Graph access token shape)",
|
|
2949
|
+
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)")],
|
|
2950
|
+
limitations: ["Passwords are accepted but never stored; no sign-in, licences, roles, app registrations or conditional access"]
|
|
2951
|
+
},
|
|
2952
|
+
okta: {
|
|
2953
|
+
version: "1.0.0",
|
|
2954
|
+
authentication: "SSWS run-scoped test token (Okta API token header)",
|
|
2955
|
+
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")],
|
|
2956
|
+
limitations: ["No authentication flows, factors, apps, policies, event hooks or rate-limit headers; pagination links omitted"]
|
|
2957
|
+
},
|
|
2958
|
+
confluence: {
|
|
2959
|
+
version: "1.0.0",
|
|
2960
|
+
authentication: "Bearer run-scoped test token",
|
|
2961
|
+
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")],
|
|
2962
|
+
limitations: ["Storage representation only; no attachments, labels, permissions, page tree moves, CQL search or v1 content API"]
|
|
2963
|
+
},
|
|
2964
|
+
sharepoint: {
|
|
2965
|
+
version: "1.0.0",
|
|
2966
|
+
authentication: "Bearer run-scoped test token (Graph access token shape)",
|
|
2967
|
+
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"])],
|
|
2968
|
+
limitations: ["No file content upload or download, versions, permissions, column validation or search"]
|
|
2969
|
+
},
|
|
2970
|
+
snowflake: {
|
|
2971
|
+
version: "1.0.0",
|
|
2972
|
+
authentication: "Bearer run-scoped test token (key-pair JWT shape)",
|
|
2973
|
+
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")],
|
|
2974
|
+
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"]
|
|
2975
|
+
},
|
|
2976
|
+
netsuite: {
|
|
2977
|
+
version: "1.0.0",
|
|
2978
|
+
authentication: "Bearer run-scoped test token (OAuth 2.0 shape)",
|
|
2979
|
+
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"])],
|
|
2980
|
+
limitations: ["Five record types; no SuiteQL, sublists beyond item lines, subsidiaries, workflows or SuiteScript; X-NetSuite-Idempotency-Key is honoured like Idempotency-Key"]
|
|
2981
|
+
},
|
|
2982
|
+
pagerduty: {
|
|
2983
|
+
version: "1.0.0",
|
|
2984
|
+
authentication: "Token token=<run-scoped test token> for REST; Events API v2 uses the seeded service integration_key as routing_key",
|
|
2985
|
+
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")],
|
|
2986
|
+
limitations: ["No escalation policies, schedules, on-call, notifications, alert grouping windows or webhooks"]
|
|
2987
|
+
}
|
|
2988
|
+
};
|
|
2989
|
+
}
|
|
2990
|
+
});
|
|
2991
|
+
|
|
1426
2992
|
// src/runtime/spec.ts
|
|
1427
2993
|
function parseWorld(value) {
|
|
1428
2994
|
const invalid = (message) => {
|
|
@@ -1444,7 +3010,7 @@ function parseWorld(value) {
|
|
|
1444
3010
|
if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
|
|
1445
3011
|
const item = service;
|
|
1446
3012
|
if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
|
|
1447
|
-
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");
|
|
3013
|
+
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");
|
|
1448
3014
|
const paths = /* @__PURE__ */ new Set();
|
|
1449
3015
|
for (const entry of item.collections) {
|
|
1450
3016
|
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");
|
|
@@ -1499,12 +3065,12 @@ function parseWorld(value) {
|
|
|
1499
3065
|
}
|
|
1500
3066
|
}
|
|
1501
3067
|
if (v.fault !== void 0) {
|
|
1502
|
-
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
|
|
3068
|
+
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");
|
|
1503
3069
|
const f = v.fault;
|
|
1504
3070
|
const allowed = ["service", "path", "type"];
|
|
1505
3071
|
const count = f.count, windowMs = f.windowMs;
|
|
1506
|
-
if (f.type === "timeout-after-write") {
|
|
1507
|
-
if (!inRangeInt(f.delayMs, 1,
|
|
3072
|
+
if (f.type === "timeout-after-write" || f.type === "slow-response") {
|
|
3073
|
+
if (!inRangeInt(f.delayMs, 1, 12e4)) invalid(`${f.type} fault requires delayMs 1\u2013120000; the delay is declared application-visible behavior, never seeded`);
|
|
1508
3074
|
allowed.push("delayMs");
|
|
1509
3075
|
} else if (f.delayMs !== void 0) invalid(`${f.type} fault does not take delayMs`);
|
|
1510
3076
|
if (f.type === "server-error") {
|
|
@@ -1513,8 +3079,12 @@ function parseWorld(value) {
|
|
|
1513
3079
|
allowed.push("count", "windowMs");
|
|
1514
3080
|
} else {
|
|
1515
3081
|
if (!["blackhole", "duplicate-write"].includes(f.type) && windowMs !== void 0) invalid(`${f.type} fault does not take windowMs`);
|
|
1516
|
-
if (["blackhole", "duplicate-write"].includes(f.type) && count !== void 0 && !inRangeInt(count, 1, 100)) invalid(`${f.type} fault count must be 1\u2013100`);
|
|
1517
|
-
if (["blackhole", "duplicate-write"].includes(f.type)) allowed.push("count");
|
|
3082
|
+
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`);
|
|
3083
|
+
if (["blackhole", "duplicate-write", "slow-response"].includes(f.type)) allowed.push("count");
|
|
3084
|
+
}
|
|
3085
|
+
if (f.schedule !== void 0) {
|
|
3086
|
+
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`);
|
|
3087
|
+
allowed.push("schedule");
|
|
1518
3088
|
}
|
|
1519
3089
|
if (Object.keys(f).some((k) => !allowed.includes(k))) invalid(`unknown fault field for ${f.type}`);
|
|
1520
3090
|
}
|
|
@@ -1594,9 +3164,12 @@ var init_spec = __esm({
|
|
|
1594
3164
|
"src/runtime/spec.ts"() {
|
|
1595
3165
|
"use strict";
|
|
1596
3166
|
init_postgres_clock();
|
|
3167
|
+
init_adapters();
|
|
1597
3168
|
init_application_clock();
|
|
3169
|
+
init_enterprise_twins();
|
|
1598
3170
|
ADAPTER_OPTIONAL_COLLECTIONS = {
|
|
1599
|
-
stripe: ["/v1/charges", "/v1/refunds", "/v1/events"]
|
|
3171
|
+
stripe: ["/v1/charges", "/v1/refunds", "/v1/events"],
|
|
3172
|
+
...ENTERPRISE_OPTIONAL_COLLECTIONS
|
|
1600
3173
|
};
|
|
1601
3174
|
ADAPTER_COLLECTIONS = {
|
|
1602
3175
|
slack: ["/messages", "/channels"],
|
|
@@ -1617,9 +3190,11 @@ var init_spec = __esm({
|
|
|
1617
3190
|
twilio: ["/2010-04-01/Messages", "/2010-04-01/Calls"],
|
|
1618
3191
|
composio: ["/connected_accounts", "/tools", "/messages"],
|
|
1619
3192
|
"google-oauth": ["/clients", "/grants", "/tokens"],
|
|
1620
|
-
zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"]
|
|
3193
|
+
zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"],
|
|
3194
|
+
// Enterprise twins: any subset of their optional collections; Snowflake tables are free-form.
|
|
3195
|
+
...Object.fromEntries(ENTERPRISE_ADAPTERS.filter((a) => !FREEFORM_COLLECTION_ADAPTERS.includes(a)).map((a) => [a, []]))
|
|
1621
3196
|
};
|
|
1622
|
-
FAULT_TYPES = ["timeout-after-write", "blackhole", "server-error", "duplicate-write"];
|
|
3197
|
+
FAULT_TYPES = ["timeout-after-write", "blackhole", "server-error", "duplicate-write", "slow-response"];
|
|
1623
3198
|
PROPERTY_KINDS = ["unique-per-act", "no-loss", "effect-count"];
|
|
1624
3199
|
object2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
1625
3200
|
namePattern = /^[a-z][a-z0-9_]{0,39}$/;
|
|
@@ -1630,8 +3205,9 @@ var init_spec = __esm({
|
|
|
1630
3205
|
// src/runtime/http-world.ts
|
|
1631
3206
|
import { createServer } from "http";
|
|
1632
3207
|
import { isDeepStrictEqual } from "util";
|
|
3208
|
+
import { createHash as createHash5 } from "crypto";
|
|
1633
3209
|
import { AsyncLocalStorage } from "async_hooks";
|
|
1634
|
-
var HttpWorld;
|
|
3210
|
+
var idempotencyKeyDigest, HttpWorld;
|
|
1635
3211
|
var init_http_world = __esm({
|
|
1636
3212
|
"src/runtime/http-world.ts"() {
|
|
1637
3213
|
"use strict";
|
|
@@ -1640,12 +3216,18 @@ var init_http_world = __esm({
|
|
|
1640
3216
|
init_rest_adapters();
|
|
1641
3217
|
init_seed();
|
|
1642
3218
|
init_spec();
|
|
3219
|
+
init_enterprise_twins();
|
|
3220
|
+
init_adapters();
|
|
3221
|
+
idempotencyKeyDigest = (key) => typeof key === "string" && key ? `sha256:${createHash5("sha256").update(key).digest("hex").slice(0, 16)}` : void 0;
|
|
1643
3222
|
HttpWorld = class {
|
|
1644
|
-
|
|
3223
|
+
/** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
|
|
3224
|
+
constructor(spec, seed, options = {}) {
|
|
1645
3225
|
this.spec = spec;
|
|
3226
|
+
this.options = options;
|
|
1646
3227
|
this.seed = normalizeSeed(seed);
|
|
1647
3228
|
}
|
|
1648
3229
|
spec;
|
|
3230
|
+
options;
|
|
1649
3231
|
events = [];
|
|
1650
3232
|
state = /* @__PURE__ */ Object.create(null);
|
|
1651
3233
|
credentials = /* @__PURE__ */ Object.create(null);
|
|
@@ -1665,6 +3247,11 @@ var init_http_world = __esm({
|
|
|
1665
3247
|
const source = this.sourceContext.getStore();
|
|
1666
3248
|
this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...record2 ? { record: structuredClone(record2) } : {}, ...source ? { source } : {} });
|
|
1667
3249
|
}
|
|
3250
|
+
/** Tags the event just recorded with the request's idempotency key digest. */
|
|
3251
|
+
keyed(key) {
|
|
3252
|
+
const digest2 = idempotencyKeyDigest(key), last = this.events[this.events.length - 1];
|
|
3253
|
+
if (digest2 && last) last.idempotencyKey = digest2;
|
|
3254
|
+
}
|
|
1668
3255
|
rejectUnsupported(service, method, path, detail) {
|
|
1669
3256
|
this.unsupported.push(`${service}: ${method} ${path}: ${detail}`);
|
|
1670
3257
|
this.record(service, "unsupported", path, detail);
|
|
@@ -1682,7 +3269,9 @@ var init_http_world = __esm({
|
|
|
1682
3269
|
const token = `at_world_${new SeedStream(this.seed, `credential:${service.name}`).nextHex(24)}`;
|
|
1683
3270
|
const faultOrdinalsFor = fault && fault.service === service.name ? faultOrdinals(fault, this.seed) : null;
|
|
1684
3271
|
const faultKey = `${fault?.type ?? ""}\0${service.name}\0${fault?.path ?? ""}`;
|
|
1685
|
-
const
|
|
3272
|
+
const enterprise = isEnterpriseAdapter(service.adapter) ? service.adapter : void 0;
|
|
3273
|
+
const generated = generatedAdapter(service.adapter);
|
|
3274
|
+
const adapterService = service.adapter === "stripe" || !!enterprise || !!generated || service.adapter && REST_ADAPTER_NAMES.includes(service.adapter);
|
|
1686
3275
|
const restAdapter = service.adapter && REST_ADAPTER_NAMES.includes(service.adapter) ? REST_ADAPTERS[service.adapter] : void 0;
|
|
1687
3276
|
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;
|
|
1688
3277
|
const data = /* @__PURE__ */ Object.create(null);
|
|
@@ -1695,26 +3284,27 @@ var init_http_world = __esm({
|
|
|
1695
3284
|
const latencyMs = () => latency && this.spec.latency ? this.spec.latency.minMs + latency.nextInt(this.spec.latency.maxMs - this.spec.latency.minMs + 1) : 0;
|
|
1696
3285
|
const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
|
|
1697
3286
|
const epoch = this.epoch;
|
|
1698
|
-
const send = (code, body) => {
|
|
3287
|
+
const send = (code, body, headers = {}) => {
|
|
1699
3288
|
if (!res.destroyed) {
|
|
1700
|
-
res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {} });
|
|
1701
|
-
res.end(JSON.stringify(body));
|
|
3289
|
+
res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
|
|
3290
|
+
res.end(code === 204 || code === 202 && body === null ? void 0 : typeof body === "string" && headers["content-type"] ? body : JSON.stringify(body));
|
|
1702
3291
|
}
|
|
1703
3292
|
};
|
|
1704
|
-
const respond = (code, body) => {
|
|
3293
|
+
const respond = (code, body, headers) => {
|
|
1705
3294
|
const ms = latencyMs();
|
|
1706
3295
|
if (ms <= 0) {
|
|
1707
|
-
send(code, body);
|
|
3296
|
+
send(code, body, headers);
|
|
1708
3297
|
return;
|
|
1709
3298
|
}
|
|
1710
3299
|
const timer = setTimeout(() => {
|
|
1711
3300
|
this.timers.delete(timer);
|
|
1712
|
-
if (epoch === this.epoch) send(code, body);
|
|
3301
|
+
if (epoch === this.epoch) send(code, body, headers);
|
|
1713
3302
|
}, ms);
|
|
1714
3303
|
this.timers.add(timer);
|
|
1715
3304
|
};
|
|
1716
3305
|
const normalPath = (url, method) => {
|
|
1717
3306
|
const parsed = new URL(url, "http://localhost");
|
|
3307
|
+
if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
|
|
1718
3308
|
if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
|
|
1719
3309
|
if (service.adapter === "composio") {
|
|
1720
3310
|
if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
|
|
@@ -1730,6 +3320,21 @@ var init_http_world = __esm({
|
|
|
1730
3320
|
return parsed.pathname;
|
|
1731
3321
|
};
|
|
1732
3322
|
const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
|
|
3323
|
+
const requestKey = req.headers["idempotency-key"];
|
|
3324
|
+
const respondSlowly = (target, operation, code, body, headers) => {
|
|
3325
|
+
if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
|
|
3326
|
+
respond(code, body, headers);
|
|
3327
|
+
return;
|
|
3328
|
+
}
|
|
3329
|
+
this.faultActions++;
|
|
3330
|
+
this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
|
|
3331
|
+
this.keyed(requestKey);
|
|
3332
|
+
const timer = setTimeout(() => {
|
|
3333
|
+
this.timers.delete(timer);
|
|
3334
|
+
if (epoch === this.epoch) respond(code, body, headers);
|
|
3335
|
+
}, fault.delayMs);
|
|
3336
|
+
this.timers.add(timer);
|
|
3337
|
+
};
|
|
1733
3338
|
const darkFault = () => {
|
|
1734
3339
|
if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
|
|
1735
3340
|
const target = normalPath(req.url ?? "/", req.method);
|
|
@@ -1740,8 +3345,9 @@ var init_http_world = __esm({
|
|
|
1740
3345
|
return fault.type;
|
|
1741
3346
|
};
|
|
1742
3347
|
try {
|
|
1743
|
-
|
|
1744
|
-
|
|
3348
|
+
const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
|
|
3349
|
+
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))) {
|
|
3350
|
+
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(", ")})`);
|
|
1745
3351
|
respond(401, { error: "invalid_test_credential" });
|
|
1746
3352
|
return;
|
|
1747
3353
|
}
|
|
@@ -1751,13 +3357,15 @@ var init_http_world = __esm({
|
|
|
1751
3357
|
}
|
|
1752
3358
|
const darkness = darkFault();
|
|
1753
3359
|
if (darkness === "blackhole") {
|
|
1754
|
-
this.record(service.name, "fault", fault.path, `blackhole: request dropped (matched ordinal ${this.candidateCounts.get(faultKey) - 1} of the seeded schedule); nothing committed`);
|
|
3360
|
+
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"})`);
|
|
3361
|
+
this.keyed(requestKey);
|
|
1755
3362
|
return;
|
|
1756
3363
|
}
|
|
1757
3364
|
if (darkness === "server-error") {
|
|
1758
3365
|
const windowMs = fault.windowMs ?? 0;
|
|
1759
3366
|
const delay = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
|
|
1760
|
-
this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed`);
|
|
3367
|
+
this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed (${req.method ?? "request"})`);
|
|
3368
|
+
this.keyed(requestKey);
|
|
1761
3369
|
const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
|
|
1762
3370
|
if (delay <= 0) {
|
|
1763
3371
|
respond500();
|
|
@@ -1784,7 +3392,7 @@ var init_http_world = __esm({
|
|
|
1784
3392
|
}
|
|
1785
3393
|
const slack = service.adapter === "slack";
|
|
1786
3394
|
const slackMethod = path.replace(/^\/api\//, "");
|
|
1787
|
-
let payload;
|
|
3395
|
+
let payload, rawBody;
|
|
1788
3396
|
if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
|
|
1789
3397
|
const chunks = [];
|
|
1790
3398
|
let bytes = 0;
|
|
@@ -1798,7 +3406,19 @@ var init_http_world = __esm({
|
|
|
1798
3406
|
}
|
|
1799
3407
|
const text = Buffer.concat(chunks).toString("utf8");
|
|
1800
3408
|
let parsed;
|
|
1801
|
-
|
|
3409
|
+
const mode = generated?.bodyMode(req.headers["content-type"]);
|
|
3410
|
+
if ((enterprise || generated) && !text.trim()) parsed = {};
|
|
3411
|
+
else if (mode === "form") {
|
|
3412
|
+
const form = new URLSearchParams(text);
|
|
3413
|
+
parsed = {};
|
|
3414
|
+
for (const key2 of new Set(form.keys())) {
|
|
3415
|
+
const all = form.getAll(key2);
|
|
3416
|
+
parsed[key2] = all.length > 1 ? all : all[0];
|
|
3417
|
+
}
|
|
3418
|
+
} else if (mode === "raw") {
|
|
3419
|
+
rawBody = text;
|
|
3420
|
+
parsed = {};
|
|
3421
|
+
} else if (service.adapter === "google-oauth") {
|
|
1802
3422
|
if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
|
|
1803
3423
|
respond(400, { error: "invalid_request" });
|
|
1804
3424
|
return;
|
|
@@ -1810,7 +3430,7 @@ var init_http_world = __esm({
|
|
|
1810
3430
|
}
|
|
1811
3431
|
parsed = Object.fromEntries(form);
|
|
1812
3432
|
} else try {
|
|
1813
|
-
parsed = (slack || service.adapter === "stripe") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text)) : JSON.parse(text);
|
|
3433
|
+
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);
|
|
1814
3434
|
} catch {
|
|
1815
3435
|
respond(400, { error: "expected_json_object" });
|
|
1816
3436
|
return;
|
|
@@ -1825,9 +3445,10 @@ var init_http_world = __esm({
|
|
|
1825
3445
|
respond(409, { error: "world_reset" });
|
|
1826
3446
|
return;
|
|
1827
3447
|
}
|
|
1828
|
-
if (
|
|
3448
|
+
if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
|
|
3449
|
+
if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
|
|
1829
3450
|
const params = payload ?? Object.fromEntries(url.searchParams);
|
|
1830
|
-
const keyHeader2 = req.headers["idempotency-key"];
|
|
3451
|
+
const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
|
|
1831
3452
|
const key2 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
|
|
1832
3453
|
const signature2 = JSON.stringify(params);
|
|
1833
3454
|
const previous2 = key2 ? keys.get(key2) : void 0;
|
|
@@ -1837,28 +3458,35 @@ var init_http_world = __esm({
|
|
|
1837
3458
|
return;
|
|
1838
3459
|
}
|
|
1839
3460
|
this.record(service.name, "replay", path, "same-key response replay", previous2.record);
|
|
1840
|
-
|
|
3461
|
+
this.keyed(keyHeader2);
|
|
3462
|
+
respondSlowly(path, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
|
|
1841
3463
|
return;
|
|
1842
3464
|
}
|
|
1843
|
-
const
|
|
3465
|
+
const query = Object.fromEntries(url.searchParams);
|
|
3466
|
+
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);
|
|
3467
|
+
const headers = (r) => "headers" in r ? r.headers : void 0;
|
|
3468
|
+
const result = invoke(this.events.length + 1);
|
|
1844
3469
|
if (!result) {
|
|
1845
3470
|
this.rejectUnsupported(service.name, req.method ?? "", path, `unsupported ${service.adapter} operation or parameters`);
|
|
1846
|
-
respond(501, restAdapter ? restUnsupportedBody(service.adapter) : { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the verified AgentTwin Stripe subset" }, forwardedToProduction: false });
|
|
3471
|
+
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 });
|
|
1847
3472
|
return;
|
|
1848
3473
|
}
|
|
1849
|
-
if (result.operation)
|
|
1850
|
-
|
|
3474
|
+
if (result.operation) {
|
|
3475
|
+
this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
|
|
3476
|
+
this.keyed(keyHeader2);
|
|
3477
|
+
}
|
|
3478
|
+
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) } : {} });
|
|
1851
3479
|
const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key2 && matchesFault(result.collection);
|
|
1852
3480
|
const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
|
|
1853
3481
|
if (duplicate2) {
|
|
1854
|
-
const second =
|
|
3482
|
+
const second = invoke(this.events.length + 1);
|
|
1855
3483
|
if (second?.operation === "write") {
|
|
1856
3484
|
this.record(service.name, second.operation, second.collection, path, "record" in second ? second.record : second.body);
|
|
1857
3485
|
this.faultActions++;
|
|
1858
3486
|
this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result.collection})`);
|
|
1859
3487
|
} else if (second) {
|
|
1860
3488
|
this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
|
|
1861
|
-
respond(second.status, second.body);
|
|
3489
|
+
respond(second.status, second.body, headers(second));
|
|
1862
3490
|
return;
|
|
1863
3491
|
}
|
|
1864
3492
|
}
|
|
@@ -1866,12 +3494,13 @@ var init_http_world = __esm({
|
|
|
1866
3494
|
this.fired = true;
|
|
1867
3495
|
this.faultActions++;
|
|
1868
3496
|
this.record(service.name, "fault", result.collection, `write committed; response delayed ${fault.delayMs}ms`);
|
|
3497
|
+
this.keyed(keyHeader2);
|
|
1869
3498
|
const timer = setTimeout(() => {
|
|
1870
3499
|
this.timers.delete(timer);
|
|
1871
|
-
respond(result.status, result.body);
|
|
3500
|
+
respond(result.status, result.body, headers(result));
|
|
1872
3501
|
}, fault.delayMs);
|
|
1873
3502
|
this.timers.add(timer);
|
|
1874
|
-
} else
|
|
3503
|
+
} else respondSlowly(result.collection, result.operation ?? "request", result.status, result.body, headers(result));
|
|
1875
3504
|
return;
|
|
1876
3505
|
}
|
|
1877
3506
|
if (slack) {
|
|
@@ -1898,12 +3527,12 @@ var init_http_world = __esm({
|
|
|
1898
3527
|
}
|
|
1899
3528
|
if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
|
|
1900
3529
|
this.record(service.name, "read", path, `${data[path].length} records`);
|
|
1901
|
-
if (slack && path === "/channels")
|
|
3530
|
+
if (slack && path === "/channels") respondSlowly(path, "read", 200, { ok: true, channels: data[path], response_metadata: { next_cursor: "" } });
|
|
1902
3531
|
else if (slack) {
|
|
1903
3532
|
const channel = payload?.channel ?? url.searchParams.get("channel");
|
|
1904
3533
|
if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
|
|
1905
|
-
else
|
|
1906
|
-
} else
|
|
3534
|
+
else respondSlowly(path, "read", 200, { ok: true, messages: data[path].filter((m) => m.channel === channel), has_more: false });
|
|
3535
|
+
} else respondSlowly(path, "read", 200, { data: data[path] });
|
|
1907
3536
|
return;
|
|
1908
3537
|
}
|
|
1909
3538
|
const body = payload;
|
|
@@ -1932,7 +3561,8 @@ var init_http_world = __esm({
|
|
|
1932
3561
|
return;
|
|
1933
3562
|
}
|
|
1934
3563
|
this.record(service.name, "replay", path, "same-key response replay", previous.record);
|
|
1935
|
-
|
|
3564
|
+
this.keyed(keyHeader);
|
|
3565
|
+
respondSlowly(path, "replay", 200, previous.record);
|
|
1936
3566
|
return;
|
|
1937
3567
|
}
|
|
1938
3568
|
const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
|
|
@@ -1945,6 +3575,7 @@ var init_http_world = __esm({
|
|
|
1945
3575
|
data[path].push(row);
|
|
1946
3576
|
if (key) keys.set(key, { body: signature, record: row });
|
|
1947
3577
|
this.record(service.name, "write", path, String(row.id), row);
|
|
3578
|
+
this.keyed(keyHeader);
|
|
1948
3579
|
if (duplicate) {
|
|
1949
3580
|
index++;
|
|
1950
3581
|
while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
|
|
@@ -1959,12 +3590,13 @@ var init_http_world = __esm({
|
|
|
1959
3590
|
this.fired = true;
|
|
1960
3591
|
this.faultActions++;
|
|
1961
3592
|
this.record(service.name, "fault", path, `write committed; response delayed ${fault.delayMs}ms`);
|
|
3593
|
+
this.keyed(keyHeader);
|
|
1962
3594
|
const timer = setTimeout(() => {
|
|
1963
3595
|
this.timers.delete(timer);
|
|
1964
3596
|
respond(faultResponse, reply);
|
|
1965
3597
|
}, fault.delayMs);
|
|
1966
3598
|
this.timers.add(timer);
|
|
1967
|
-
} else
|
|
3599
|
+
} else respondSlowly(path, "write", faultResponse, reply);
|
|
1968
3600
|
} catch {
|
|
1969
3601
|
respond(500, { error: "world_request_error" });
|
|
1970
3602
|
}
|
|
@@ -2237,7 +3869,7 @@ function operationMatrix(spec) {
|
|
|
2237
3869
|
name: s.name,
|
|
2238
3870
|
adapter: s.adapter ?? "json-collection",
|
|
2239
3871
|
version: CONTRACTS[s.adapter ?? "json-collection"].version,
|
|
2240
|
-
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((
|
|
3872
|
+
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 })))
|
|
2241
3873
|
})) ?? []
|
|
2242
3874
|
};
|
|
2243
3875
|
}
|
|
@@ -2245,6 +3877,7 @@ var CONTRACTS;
|
|
|
2245
3877
|
var init_contracts = __esm({
|
|
2246
3878
|
"src/runtime/contracts.ts"() {
|
|
2247
3879
|
"use strict";
|
|
3880
|
+
init_enterprise_twins();
|
|
2248
3881
|
CONTRACTS = {
|
|
2249
3882
|
composio: {
|
|
2250
3883
|
version: "1.0.0",
|
|
@@ -2491,14 +4124,678 @@ var init_contracts = __esm({
|
|
|
2491
4124
|
{ method: "GET", endpoint: "/api/v2/organizations.json", effect: "list seeded organizations", parameters: [], errors: [] }
|
|
2492
4125
|
],
|
|
2493
4126
|
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"]
|
|
4127
|
+
},
|
|
4128
|
+
...ENTERPRISE_CONTRACTS
|
|
4129
|
+
};
|
|
4130
|
+
}
|
|
4131
|
+
});
|
|
4132
|
+
|
|
4133
|
+
// src/runtime/run-summary.ts
|
|
4134
|
+
var formatMoney;
|
|
4135
|
+
var init_run_summary = __esm({
|
|
4136
|
+
"src/runtime/run-summary.ts"() {
|
|
4137
|
+
"use strict";
|
|
4138
|
+
formatMoney = (m) => new Intl.NumberFormat("en-US", { style: "currency", currency: m.currency.length === 3 ? m.currency : "USD" }).format(m.amount);
|
|
4139
|
+
}
|
|
4140
|
+
});
|
|
4141
|
+
|
|
4142
|
+
// src/runtime/generic-calls.ts
|
|
4143
|
+
import { createHash as createHash6 } from "crypto";
|
|
4144
|
+
function canonical2(value) {
|
|
4145
|
+
return Array.isArray(value) ? `[${value.map(canonical2).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical2(value[k])}`).join(",")}}` : JSON.stringify(value ?? null);
|
|
4146
|
+
}
|
|
4147
|
+
function resourceOf2(method, path) {
|
|
4148
|
+
const segments = path.split("?")[0].split("/").filter(Boolean).map((s) => {
|
|
4149
|
+
try {
|
|
4150
|
+
return decodeURIComponent(s);
|
|
4151
|
+
} catch {
|
|
4152
|
+
return s;
|
|
4153
|
+
}
|
|
4154
|
+
});
|
|
4155
|
+
let resourceId;
|
|
4156
|
+
const template = segments.map((s, i) => {
|
|
4157
|
+
const last = i === segments.length - 1, byMethod = last && ["PUT", "PATCH", "DELETE"].includes(method) && segments.length > 1;
|
|
4158
|
+
if (idLike(s) || byMethod) {
|
|
4159
|
+
if (last || !resourceId || idLike(s)) resourceId = s;
|
|
4160
|
+
return "{id}";
|
|
4161
|
+
}
|
|
4162
|
+
return s;
|
|
4163
|
+
});
|
|
4164
|
+
return { resourcePath: "/" + template.join("/"), ...resourceId ? { resourceId } : {} };
|
|
4165
|
+
}
|
|
4166
|
+
function keyFrom(headers, body) {
|
|
4167
|
+
for (const name of KEY_HEADERS) {
|
|
4168
|
+
const v = headers?.[name];
|
|
4169
|
+
if (typeof v === "string" && v) return digest(v);
|
|
4170
|
+
}
|
|
4171
|
+
if (body && typeof body === "object") {
|
|
4172
|
+
for (const [k, v] of Object.entries(body)) if (KEY_FIELDS.test(k) && typeof v === "string" && v) return digest(v);
|
|
4173
|
+
}
|
|
4174
|
+
}
|
|
4175
|
+
function normalizeCall(raw) {
|
|
4176
|
+
const method = raw.method.toUpperCase(), path = raw.path.split("?")[0] || "/", { resourcePath, resourceId } = resourceOf2(method, path);
|
|
4177
|
+
const graphqlRead = /graphql/i.test(path) && typeof raw.body?.query === "string" && !/^\s*mutation\b/.test(raw.body.query);
|
|
4178
|
+
const isWrite = WRITE_METHODS.has(method) && !READ_LIKE.test(path) && !MODEL_HOST.test(raw.host) && !String(raw.service ?? "").startsWith("model:") && !graphqlRead;
|
|
4179
|
+
const outcome = raw.outcome ?? outcomeOf(raw.status), key = keyFrom(raw.headers, raw.body), source = parseSource(raw.source);
|
|
4180
|
+
return {
|
|
4181
|
+
sequence: raw.sequence,
|
|
4182
|
+
service: raw.service ?? raw.host,
|
|
4183
|
+
host: raw.host,
|
|
4184
|
+
method,
|
|
4185
|
+
path,
|
|
4186
|
+
resourcePath,
|
|
4187
|
+
...method === "POST" && raw.createdId ? { resourceId: raw.createdId } : resourceId ? { resourceId } : {},
|
|
4188
|
+
isWrite,
|
|
4189
|
+
...key ? { idempotencyKey: key } : {},
|
|
4190
|
+
...raw.body !== void 0 ? { requestDigest: digest(stable(raw.body)), body: raw.body } : {},
|
|
4191
|
+
...raw.response !== void 0 ? { responseDigest: digest(stable(raw.response)) } : {},
|
|
4192
|
+
outcome,
|
|
4193
|
+
...raw.status !== void 0 ? { status: raw.status } : {},
|
|
4194
|
+
committed: raw.committed ?? (isWrite ? outcome === "ok" : void 0),
|
|
4195
|
+
...raw.duplicated ? { duplicated: true } : {},
|
|
4196
|
+
...raw.retryAfterMs !== void 0 ? { retryAfterMs: raw.retryAfterMs } : {},
|
|
4197
|
+
...raw.at !== void 0 ? { at: raw.at } : {},
|
|
4198
|
+
...source ? { source } : {},
|
|
4199
|
+
...raw.tier ? { tier: raw.tier } : {}
|
|
4200
|
+
};
|
|
4201
|
+
}
|
|
4202
|
+
function callsFromWorldEvents(events, tierOf = () => void 0) {
|
|
4203
|
+
const calls = [], seen = /* @__PURE__ */ new Set();
|
|
4204
|
+
const last = (service) => [...calls].reverse().find((c) => c.service === service && c.isWrite);
|
|
4205
|
+
for (const e of events) {
|
|
4206
|
+
const tier = tierOf(e.service), key = e.idempotencyKey;
|
|
4207
|
+
const base = (method, path, extra) => normalizeCall({ sequence: e.sequence, host: e.service, service: e.service, method, path, ...tier ? { tier } : {}, ...e.source ? { source: e.source } : {}, ...extra });
|
|
4208
|
+
const withKey = (c) => key ? { ...c, idempotencyKey: key } : c;
|
|
4209
|
+
if (e.operation === "write") {
|
|
4210
|
+
const id = e.record?.id === void 0 ? void 0 : String(e.record.id), path = e.path, recordKey = `${e.service}${path}:${id}`;
|
|
4211
|
+
const method = /^(POST|PUT|PATCH|DELETE)\b/.exec(e.detail)?.[1] ?? (id && seen.has(recordKey) ? "PATCH" : "POST");
|
|
4212
|
+
if (id) seen.add(recordKey);
|
|
4213
|
+
const c = base(method, method === "POST" ? path : `${path}/${id ?? ""}`, { body: e.record, committed: true, ...id ? { createdId: id } : {} });
|
|
4214
|
+
calls.push(withKey({ ...c, resourcePath: resourceOf2("GET", path).resourcePath, ...id ? { resourceId: id } : {} }));
|
|
4215
|
+
} else if (e.operation === "replay") calls.push(withKey(base("POST", e.path, { outcome: "replayed", committed: false })));
|
|
4216
|
+
else if (e.operation === "auth-denied") calls.push(base("POST", e.path.split("?")[0], { outcome: "unauthorized", committed: false }));
|
|
4217
|
+
else if (e.operation === "fault") {
|
|
4218
|
+
const prior = last(e.service), method = /\((POST|PUT|PATCH|DELETE|GET)\)\s*$/.exec(e.detail)?.[1];
|
|
4219
|
+
if (/^write committed|^slow-response: write/.test(e.detail) && prior) {
|
|
4220
|
+
prior.outcome = "timeout";
|
|
4221
|
+
prior.committed = true;
|
|
4222
|
+
} else if (/^duplicate-write: (one write committed as two|a single write was delivered twice)/.test(e.detail) && prior) prior.duplicated = true;
|
|
4223
|
+
else if (/^server-error/.test(e.detail)) calls.push(withKey(base(method ?? "POST", e.path, { outcome: "server-error", committed: false })));
|
|
4224
|
+
else if (/^blackhole/.test(e.detail)) calls.push(withKey(base(method ?? "POST", e.path, { outcome: "timeout", committed: false })));
|
|
4225
|
+
}
|
|
4226
|
+
}
|
|
4227
|
+
return calls;
|
|
4228
|
+
}
|
|
4229
|
+
function textOf(body, depth = 0) {
|
|
4230
|
+
if (!body || typeof body !== "object" || depth > 3) return "";
|
|
4231
|
+
return Object.entries(body).map(([k, v]) => typeof v === "string" && TEXT_FIELDS.test(k) ? v : v && typeof v === "object" ? textOf(v, depth + 1) : "").filter(Boolean).join(" ").trim();
|
|
4232
|
+
}
|
|
4233
|
+
function recipientsOf(body, depth = 0) {
|
|
4234
|
+
if (!body || typeof body !== "object" || depth > 3) return [];
|
|
4235
|
+
return Object.entries(body).flatMap(([k, v]) => RECIPIENT.test(k) ? (Array.isArray(v) ? v : [v]).filter((x) => typeof x === "string" && !!x) : v && typeof v === "object" ? recipientsOf(v, depth + 1) : []);
|
|
4236
|
+
}
|
|
4237
|
+
function claimsOf(calls, output = []) {
|
|
4238
|
+
const claims = calls.filter(isAnnouncement).map((c) => {
|
|
4239
|
+
const text = textOf(c.body);
|
|
4240
|
+
return { sequence: c.sequence, text, polarity: polarityOf(text), via: c.sequence, ...c.source ? { source: c.source } : {} };
|
|
4241
|
+
});
|
|
4242
|
+
const end = Math.max(0, ...calls.map((c) => c.sequence)) + 1;
|
|
4243
|
+
output.map((t) => t.trim()).filter(Boolean).slice(0, 50).forEach((text, i) => claims.push({ sequence: end + i, text: text.slice(0, 500), polarity: polarityOf(text) }));
|
|
4244
|
+
return claims;
|
|
4245
|
+
}
|
|
4246
|
+
function moneyOf(body, depth = 0) {
|
|
4247
|
+
if (!body || typeof body !== "object" || depth > 3) return;
|
|
4248
|
+
const row = body, currency = Object.entries(row).find(([k, v]) => /^currency(_code)?$/i.test(k) && typeof v === "string" && /^[a-z]{3}$/i.test(v))?.[1];
|
|
4249
|
+
for (const [k, v] of Object.entries(row)) {
|
|
4250
|
+
const n = typeof v === "number" ? v : typeof v === "string" && /^\d+(\.\d+)?$/.test(v) ? Number(v) : NaN;
|
|
4251
|
+
if (AMOUNT.test(k) && Number.isFinite(n) && n > 0 && currency) return { amount: /cents|minor/i.test(k) ? n / 100 : n, currency: currency.toUpperCase() };
|
|
4252
|
+
}
|
|
4253
|
+
for (const v of Object.values(row)) {
|
|
4254
|
+
const nested = v && typeof v === "object" ? moneyOf(v, depth + 1) : void 0;
|
|
4255
|
+
if (nested) return nested;
|
|
4256
|
+
}
|
|
4257
|
+
}
|
|
4258
|
+
function impactOf(calls, extra, fallback, hint) {
|
|
4259
|
+
const money2 = calls.map((c) => moneyOf(c.body)).find(Boolean), recipients = [...new Set(calls.flatMap((c) => recipientsOf(c.body)))];
|
|
4260
|
+
if (money2 && extra > 0) return { kind: "money", amount: money2.amount * extra, currency: money2.currency, count: extra, summary: `${formatMoney({ amount: money2.amount * extra, currency: money2.currency })} moved more than intended (${formatMoney(money2)} each)` };
|
|
4261
|
+
const messaging = calls.some((c) => MESSAGING.test(c.path.split("?")[0]));
|
|
4262
|
+
if (recipients.length && extra > 0 && !messaging) {
|
|
4263
|
+
const noun = (calls[0]?.path.split("?")[0].split("/").filter(Boolean).pop() ?? "record").replace(/\.json$/, "").replace(/ies$/, "y").replace(/s$/, "");
|
|
4264
|
+
return { kind: "data-integrity", recipients, count: extra, summary: `${extra + 1} ${noun} records would exist for ${recipients[0]} instead of 1` };
|
|
4265
|
+
}
|
|
4266
|
+
if (recipients.length && (extra > 0 && messaging || fallback === "customer-facing")) return { kind: "customer-facing", recipients, count: Math.max(1, extra), summary: `${recipients.slice(0, 3).join(", ")} ${extra > 0 ? `would have received ${extra + 1} copies` : "would have been told something untrue"}` };
|
|
4267
|
+
return { kind: fallback, count: Math.max(1, extra), summary: hint };
|
|
4268
|
+
}
|
|
4269
|
+
function faultWords(c) {
|
|
4270
|
+
const who = c.service;
|
|
4271
|
+
return c.outcome === "lost-response" ? `${who} saved the write but the reply was lost` : c.outcome === "timeout" ? `${who} ${c.committed ? "saved the write but answered after the client timeout" : "never answered"}` : c.outcome === "server-error" ? `${who} returned ${c.status ?? 500}` : c.outcome === "rate-limited" ? `${who} rate-limited the call (429)` : c.outcome === "unauthorized" ? `${who} rejected the credential (${c.status ?? 401})` : c.outcome === "client-error" ? `${who} rejected the request (${c.status ?? 400})` : `${who} failed`;
|
|
4272
|
+
}
|
|
4273
|
+
function genericChecks(calls, opts = {}) {
|
|
4274
|
+
const out = [], covered = opts.covered ?? (() => false);
|
|
4275
|
+
const ordered = [...calls].sort((a, b) => a.sequence - b.sequence), writes = ordered.filter((c) => c.isWrite && c.outcome !== "blocked");
|
|
4276
|
+
const claims = opts.claims ?? claimsOf(ordered, opts.output);
|
|
4277
|
+
const announcementSeqs = new Set(claims.map((c) => c.via).filter((v) => v !== void 0));
|
|
4278
|
+
for (const group of groupsOf(writes)) {
|
|
4279
|
+
if (group.length < 2 && !group[0].duplicated) continue;
|
|
4280
|
+
const first = group[0], made = group.reduce((n, c) => n + effects(c), 0), keys = new Set(group.map((c) => c.idempotencyKey));
|
|
4281
|
+
const fault = group.find((c, i) => AMBIGUOUS.includes(c.outcome) && i < group.length - 1);
|
|
4282
|
+
const keyed = keys.size === 1 && !keys.has(void 0);
|
|
4283
|
+
const announce = announcementSeqs.has(first.sequence) || isAnnouncement(first);
|
|
4284
|
+
const when = fault ? ` after ${faultWords(fault)}` : opts.duplicateDelivery ? " when the trigger was delivered twice" : first.duplicated ? ` when ${first.service} received the request twice` : "";
|
|
4285
|
+
if (made >= 2 && (first.method === "POST" || first.method === "DELETE" || announce) && !covered(first.service, "duplicate-write")) {
|
|
4286
|
+
const noun = first.method === "POST" ? "saved" : "applied";
|
|
4287
|
+
out.push({
|
|
4288
|
+
check: "duplicate-write",
|
|
4289
|
+
service: first.service,
|
|
4290
|
+
resource: `${first.method} ${first.path}`,
|
|
4291
|
+
calls: group.map((c) => c.sequence),
|
|
4292
|
+
finding: `${label(first)} was ${group.length > 1 ? `sent ${times(group.length)}` : "sent once"} and ${noun} ${times(made)}${when}${keyed ? " (the key was not honored)" : group.some((c) => c.idempotencyKey) ? " with different idempotency keys" : " without an idempotency key"}`,
|
|
4293
|
+
impact: impactOf(group, made - 1, "data-integrity", `the same ${first.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} exists ${times(made)} downstream`),
|
|
4294
|
+
...group[group.length - 1].source ? { source: group[group.length - 1].source } : {},
|
|
4295
|
+
writeSites: sites(group),
|
|
4296
|
+
fix: announce ? "check-before-resend" : "idempotency-key"
|
|
4297
|
+
});
|
|
4298
|
+
continue;
|
|
4299
|
+
}
|
|
4300
|
+
if (fault && !keyed && made >= 2 && !covered(first.service, "retry-without-key")) {
|
|
4301
|
+
const retry = group.find((c) => c.sequence > fault.sequence);
|
|
4302
|
+
out.push({
|
|
4303
|
+
check: "retry-without-key",
|
|
4304
|
+
service: first.service,
|
|
4305
|
+
resource: `${first.method} ${first.path}`,
|
|
4306
|
+
calls: group.map((c) => c.sequence),
|
|
4307
|
+
finding: `${label(first)} was sent ${times(group.length)}${when}, ${retry.idempotencyKey ? "with a new idempotency key" : "without an idempotency key"}`,
|
|
4308
|
+
impact: made >= 2 ? impactOf(group, made - 1, "data-integrity", "the write was applied more than once") : { kind: "reliability", count: 1, summary: `a retry without a stable key can apply ${first.method} ${first.resourcePath} twice when the first attempt was saved` },
|
|
4309
|
+
...retry.source ? { source: retry.source } : {},
|
|
4310
|
+
writeSites: sites(group),
|
|
4311
|
+
fix: announce ? "check-before-resend" : "idempotency-key"
|
|
4312
|
+
});
|
|
4313
|
+
}
|
|
4314
|
+
}
|
|
4315
|
+
for (const limited of ordered.filter((c) => c.outcome === "rate-limited" && c.retryAfterMs && c.at !== void 0)) {
|
|
4316
|
+
const next = ordered.find((c) => c.sequence > limited.sequence && c.service === limited.service && c.at !== void 0 && sameRequest(limited, c));
|
|
4317
|
+
if (next && next.at - limited.at < limited.retryAfterMs * 0.9 && !covered(limited.service, "retry-after-ignored"))
|
|
4318
|
+
out.push({
|
|
4319
|
+
check: "retry-after-ignored",
|
|
4320
|
+
service: limited.service,
|
|
4321
|
+
resource: `${limited.method} ${limited.path}`,
|
|
4322
|
+
calls: [limited.sequence, next.sequence],
|
|
4323
|
+
finding: `${label(limited)} was retried after ${next.at - limited.at}ms although ${limited.service} asked to wait ${Math.round(limited.retryAfterMs / 1e3)}s (Retry-After)`,
|
|
4324
|
+
impact: { kind: "reliability", count: 1, summary: "ignoring Retry-After prolongs rate limiting and can get the credential throttled or banned" },
|
|
4325
|
+
...next.source ? { source: next.source } : {},
|
|
4326
|
+
fix: "respect-retry-after"
|
|
4327
|
+
});
|
|
4328
|
+
}
|
|
4329
|
+
const unrecoveredBefore = (seq) => writes.filter((w) => w.sequence < seq && !announcementSeqs.has(w.sequence) && FAILED.includes(w.outcome) && w.outcome !== "lost-response" && !(w.outcome === "timeout" && w.committed) && !writes.some((r) => r.sequence > w.sequence && r.sequence < seq && sameRequest(w, r) && succeeded(r)));
|
|
4330
|
+
for (const claim of claims.filter((c) => c.polarity === "success")) {
|
|
4331
|
+
const failed = unrecoveredBefore(claim.sequence)[0], via = claim.via !== void 0 ? ordered.find((c) => c.sequence === claim.via) : void 0;
|
|
4332
|
+
if (!failed || covered(via?.service ?? failed.service, "announce-after-failed-write")) continue;
|
|
4333
|
+
out.push({
|
|
4334
|
+
check: "announce-after-failed-write",
|
|
4335
|
+
service: via?.service ?? failed.service,
|
|
4336
|
+
resource: via ? `${via.method} ${via.path}` : "agent output",
|
|
4337
|
+
calls: [failed.sequence, ...via ? [via.sequence] : []],
|
|
4338
|
+
finding: `Your agent said "${claim.text.slice(0, 80)}"${via ? ` (${label(via)})` : ""} after ${label(failed)} failed (${faultWords(failed)}) and never succeeded`,
|
|
4339
|
+
impact: impactOf(via ? [via] : [], 0, "customer-facing", "the agent reports work that never happened"),
|
|
4340
|
+
...claim.source ?? via?.source ? { source: claim.source ?? via?.source } : {},
|
|
4341
|
+
fix: "confirm-before-announce"
|
|
4342
|
+
});
|
|
4343
|
+
break;
|
|
4344
|
+
}
|
|
4345
|
+
for (const claim of claims.filter((c) => c.polarity === "failure")) {
|
|
4346
|
+
const later = writes.find((w) => w.sequence > claim.sequence && !announcementSeqs.has(w.sequence) && effects(w) > 0);
|
|
4347
|
+
if (!later || covered(later.service, "write-after-reported-failure")) continue;
|
|
4348
|
+
out.push({
|
|
4349
|
+
check: "write-after-reported-failure",
|
|
4350
|
+
service: later.service,
|
|
4351
|
+
resource: `${later.method} ${later.path}`,
|
|
4352
|
+
calls: [...claim.via ? [claim.via] : [], later.sequence],
|
|
4353
|
+
finding: `Your agent reported "${claim.text.slice(0, 80)}" and then still sent ${label(later)}`,
|
|
4354
|
+
impact: impactOf([later], 0, "data-integrity", "the system changed after the agent told someone it had not"),
|
|
4355
|
+
...later.source ? { source: later.source } : {}
|
|
4356
|
+
});
|
|
4357
|
+
break;
|
|
4358
|
+
}
|
|
4359
|
+
if (opts.readBack) for (const claim of claims.filter((c) => c.polarity === "success")) {
|
|
4360
|
+
for (const w of writes.filter((w2) => w2.sequence < claim.sequence && w2.resourceId && w2.method !== "POST" && new RegExp(`(^|[^\\w-])${w2.resourceId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^\\w-]|$)`).test(claim.text))) {
|
|
4361
|
+
const rb = opts.readBack(w);
|
|
4362
|
+
if (!rb || covered(w.service, "claimed-change-unchanged")) continue;
|
|
4363
|
+
const unchanged = w.method === "DELETE" ? rb.after !== void 0 : canonical2(stable(rb.before)) === canonical2(stable(rb.after));
|
|
4364
|
+
if (!unchanged) continue;
|
|
4365
|
+
out.push({
|
|
4366
|
+
check: "claimed-change-unchanged",
|
|
4367
|
+
service: w.service,
|
|
4368
|
+
resource: `${w.method} ${w.path}`,
|
|
4369
|
+
calls: [w.sequence, ...claim.via ? [claim.via] : []],
|
|
4370
|
+
finding: `Your agent said "${claim.text.slice(0, 80)}", but ${w.service} ${w.path} is unchanged at read-back`,
|
|
4371
|
+
impact: { kind: "data-integrity", count: 1, summary: `${w.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} ${w.resourceId} was reported changed but is not` },
|
|
4372
|
+
...claim.source ?? w.source ? { source: claim.source ?? w.source } : {},
|
|
4373
|
+
fix: "confirm-before-announce"
|
|
4374
|
+
});
|
|
4375
|
+
break;
|
|
4376
|
+
}
|
|
4377
|
+
}
|
|
4378
|
+
for (const failed of writes.filter((w) => FAILED.includes(w.outcome) && !(w.outcome === "timeout" && w.committed) && w.outcome !== "lost-response")) {
|
|
4379
|
+
if (writes.some((r) => r.sequence > failed.sequence && sameRequest(failed, r) && succeeded(r))) continue;
|
|
4380
|
+
const committed = writes.find((a) => a.sequence < failed.sequence && a.service !== failed.service && effects(a) > 0 && !announcementSeqs.has(a.sequence) && !isAnnouncement(a) && !writes.some((x) => x.sequence > failed.sequence && x.service === a.service && (x.resourceId ? x.resourceId === a.resourceId : x.resourcePath === a.resourcePath) && effects(x) > 0));
|
|
4381
|
+
if (!committed || covered(committed.service, "partial-commit")) continue;
|
|
4382
|
+
out.push({
|
|
4383
|
+
check: "partial-commit",
|
|
4384
|
+
service: committed.service,
|
|
4385
|
+
resource: `${committed.method} ${committed.path}`,
|
|
4386
|
+
calls: [committed.sequence, failed.sequence],
|
|
4387
|
+
finding: `${label(committed)} was saved, then ${label(failed)} failed (${faultWords(failed)}) and nothing undid the first write`,
|
|
4388
|
+
impact: impactOf([committed], 0, "data-integrity", `${committed.service} and ${failed.service} disagree: one recorded the change, the other did not`),
|
|
4389
|
+
...failed.source ? { source: failed.source } : {}
|
|
4390
|
+
});
|
|
4391
|
+
break;
|
|
4392
|
+
}
|
|
4393
|
+
return out;
|
|
4394
|
+
}
|
|
4395
|
+
function worldReadBack(ctx) {
|
|
4396
|
+
return (c) => {
|
|
4397
|
+
const find = (state) => (state?.[c.service]?.[c.resourcePath.replace(/\/\{id\}$/, "")] ?? []).find((r) => r && typeof r === "object" && String(r.id) === c.resourceId);
|
|
4398
|
+
return { before: find(ctx.initialState), after: find(ctx.finalState) };
|
|
4399
|
+
};
|
|
4400
|
+
}
|
|
4401
|
+
function genericWorldChecks(covers) {
|
|
4402
|
+
const rules = ["retry-without-key", "announce-after-failed-write", "write-after-reported-failure", "claimed-change-unchanged", "partial-commit"];
|
|
4403
|
+
return rules.map((rule) => ({
|
|
4404
|
+
id: `generic.${rule}`,
|
|
4405
|
+
title: GENERIC_TITLES[rule][0],
|
|
4406
|
+
expected: GENERIC_TITLES[rule][1],
|
|
4407
|
+
path: "/",
|
|
4408
|
+
impact: rule === "announce-after-failed-write" ? "customer-facing" : rule === "retry-without-key" ? "reliability" : "data-integrity",
|
|
4409
|
+
impactHint: GENERIC_TITLES[rule][1],
|
|
4410
|
+
run(ctx) {
|
|
4411
|
+
if (["openai", "anthropic", "google-oauth", "postgres"].includes(ctx.service.adapter ?? "")) return [];
|
|
4412
|
+
const adapterOf = (name) => ctx.services.find((s) => s.name === name)?.adapter;
|
|
4413
|
+
const calls = callsFromWorldEvents(ctx.events).filter((c) => !["openai", "anthropic", "google-oauth"].includes(adapterOf(c.service) ?? ""));
|
|
4414
|
+
return genericChecks(calls, { readBack: worldReadBack(ctx), duplicateDelivery: ctx.duplicateDelivery, covered: (service, check) => check !== rule || covers(adapterOf(service), check) }).filter((v) => v.check === rule && v.service === ctx.service.name).map((v) => ({ path: v.resource.split(" ")[1] ?? "/", actual: { resource: v.resource, calls: v.calls }, finding: v.finding, impact: { kind: v.impact.kind, count: v.impact.count, ...v.impact.amount ? { amount: Math.round(v.impact.amount * 100), currency: v.impact.currency } : {} }, evidence: v.calls }));
|
|
4415
|
+
}
|
|
4416
|
+
}));
|
|
4417
|
+
}
|
|
4418
|
+
var WRITE_METHODS, READ_LIKE, MODEL_HOST, VOLATILE, KEY_HEADERS, KEY_FIELDS, digest, stable, idLike, outcomeOf, parseSource, SUCCESS, FAILURE, TEXT_FIELDS, MESSAGING, polarityOf, RECIPIENT, isAnnouncement, AMOUNT, times, FAILED, AMBIGUOUS, label, sameRequest, succeeded, effects, sites, groupsOf, GENERIC_TITLES;
|
|
4419
|
+
var init_generic_calls = __esm({
|
|
4420
|
+
"src/runtime/generic-calls.ts"() {
|
|
4421
|
+
"use strict";
|
|
4422
|
+
init_run_summary();
|
|
4423
|
+
WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
4424
|
+
READ_LIKE = /\/(search|query|lookup|count|batch\/read|completions|embeddings|responses|count_tokens|graphql\/query)$/i;
|
|
4425
|
+
MODEL_HOST = /(^|\.)(openai\.com|anthropic\.com|generativelanguage\.googleapis\.com|mistral\.ai|groq\.com|cohere\.ai)$/i;
|
|
4426
|
+
VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
|
|
4427
|
+
KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
|
|
4428
|
+
KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
|
|
4429
|
+
digest = (value) => `sha256:${createHash6("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
|
|
4430
|
+
stable = (value) => Array.isArray(value) ? value.map(stable) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).filter(([k]) => !VOLATILE.test(k) && !KEY_FIELDS.test(k)).map(([k, v]) => [k, stable(v)])) : value;
|
|
4431
|
+
idLike = (segment) => /^\d+$/.test(segment) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || segment.length >= 3 && /\d/.test(segment) && /^[A-Za-z0-9_\-:.]+$/.test(segment) && !/^v\d+(\.\d+)*$/i.test(segment) && !/^\d{4}-\d{2}-\d{2}$/.test(segment) && !/^[A-Za-z]+\.(json|xml)$/.test(segment);
|
|
4432
|
+
outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
|
|
4433
|
+
parseSource = (s) => {
|
|
4434
|
+
if (!s) return;
|
|
4435
|
+
if (typeof s !== "string") return s;
|
|
4436
|
+
try {
|
|
4437
|
+
const v = JSON.parse(s);
|
|
4438
|
+
return typeof v?.file === "string" ? v : void 0;
|
|
4439
|
+
} catch {
|
|
4440
|
+
return;
|
|
4441
|
+
}
|
|
4442
|
+
};
|
|
4443
|
+
SUCCESS = /\b(done|complete[d]?|success(ful(ly)?)?|refunded|closed|created|updated|sent|processed|confirmed|welcome|paid|invoiced|won|approved|resolved|scheduled|saved|booked|cancell?ed|shipped|delivered)\b/i;
|
|
4444
|
+
FAILURE = /\b(fail(ed|ure)?|error|unable|could ?n[o']t|cannot|can't|did ?n[o']t|not (?:been )?(?:\w+ed)|retry(ing)?|escalat\w*|pending|try again|sorry)\b/i;
|
|
4445
|
+
TEXT_FIELDS = /^(text|body|message|content|subject|summary|description|Body|Message|html|markdown|note|comment)$/;
|
|
4446
|
+
MESSAGING = /(message|messages|sms|mail|email|emails|notification|notifications|notify|send|postMessage|comments?|reply|replies)(\.json)?$/i;
|
|
4447
|
+
polarityOf = (text) => FAILURE.test(text) ? "failure" : SUCCESS.test(text) ? "success" : "neutral";
|
|
4448
|
+
RECIPIENT = /^(to|recipient|recipients|email|phone|phone_number|channel|cc|bcc|To|chat_id|user_id)$/;
|
|
4449
|
+
isAnnouncement = (c) => c.isWrite && !!textOf(c.body) && (MESSAGING.test(c.path) || recipientsOf(c.body).length > 0);
|
|
4450
|
+
AMOUNT = /^(amount|total|price|unit_amount|amount_total|grand_total|subtotal|value|amount_cents|amount_minor|total_cents|price_cents)$/i;
|
|
4451
|
+
times = (n) => n === 2 ? "twice" : `${n} times`;
|
|
4452
|
+
FAILED = ["server-error", "lost-response", "timeout", "client-error", "unauthorized", "rate-limited"];
|
|
4453
|
+
AMBIGUOUS = ["server-error", "lost-response", "timeout"];
|
|
4454
|
+
label = (c) => `${c.method} ${c.path} on ${c.service}`;
|
|
4455
|
+
sameRequest = (a, b) => a.service === b.service && a.method === b.method && a.resourcePath === b.resourcePath && (a.method === "POST" || a.resourceId === b.resourceId) && (!a.requestDigest || !b.requestDigest || a.requestDigest === b.requestDigest);
|
|
4456
|
+
succeeded = (c) => c.outcome === "ok" || c.outcome === "replayed";
|
|
4457
|
+
effects = (c) => c.committed === false || c.outcome === "replayed" || c.outcome === "blocked" ? 0 : (c.committed || c.outcome === "ok" ? 1 : 0) * (c.duplicated ? 2 : 1);
|
|
4458
|
+
sites = (calls) => [...new Map(calls.filter((c) => c.source).map((c) => [`${c.source.file}:${c.source.line}`, c.source])).values()];
|
|
4459
|
+
groupsOf = (writes) => {
|
|
4460
|
+
const groups2 = [];
|
|
4461
|
+
for (const c of writes) {
|
|
4462
|
+
const g = groups2.find((g2) => sameRequest(g2[0], c));
|
|
4463
|
+
if (g) g.push(c);
|
|
4464
|
+
else groups2.push([c]);
|
|
2494
4465
|
}
|
|
4466
|
+
return groups2;
|
|
4467
|
+
};
|
|
4468
|
+
GENERIC_TITLES = {
|
|
4469
|
+
"duplicate-write": ["World-changing calls take effect once", "each create, charge or send is applied once, even under retries and redelivery"],
|
|
4470
|
+
"retry-without-key": ["Retries after a fault reuse the idempotency key", "a write retried after an ambiguous failure carries the same idempotency key"],
|
|
4471
|
+
"retry-after-ignored": ["Rate-limited calls wait for Retry-After", "a 429 is retried no sooner than its Retry-After"],
|
|
4472
|
+
"announce-after-failed-write": ["Success is announced only after the write succeeded", "the agent claims success only when every write it depends on succeeded"],
|
|
4473
|
+
"write-after-reported-failure": ["No writes after the agent reported failure", "after the agent reports a failure it changes nothing else"],
|
|
4474
|
+
"claimed-change-unchanged": ["Claimed changes are visible at read-back", "every resource the agent says it changed is changed when read back"],
|
|
4475
|
+
"partial-commit": ["Multi-service writes commit together or compensate", "when a later write fails, earlier writes in other services are undone"]
|
|
2495
4476
|
};
|
|
2496
4477
|
}
|
|
2497
4478
|
});
|
|
2498
4479
|
|
|
4480
|
+
// src/runtime/default-checks.ts
|
|
4481
|
+
function addedRows(initial, final) {
|
|
4482
|
+
const rows2 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
|
|
4483
|
+
const ids = new Set(rows2(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
|
|
4484
|
+
const seen = /* @__PURE__ */ new Map();
|
|
4485
|
+
for (const r of rows2(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
|
|
4486
|
+
return rows2(final).filter((r) => {
|
|
4487
|
+
if (r.id !== void 0 && r.id !== null) return !ids.has(r.id);
|
|
4488
|
+
const key = canonical3(r), left = seen.get(key) ?? 0;
|
|
4489
|
+
if (left > 0) {
|
|
4490
|
+
seen.set(key, left - 1);
|
|
4491
|
+
return false;
|
|
4492
|
+
}
|
|
4493
|
+
return true;
|
|
4494
|
+
});
|
|
4495
|
+
}
|
|
4496
|
+
function groups(items, key) {
|
|
4497
|
+
const out = /* @__PURE__ */ new Map();
|
|
4498
|
+
for (const item of items) {
|
|
4499
|
+
const k = key(item);
|
|
4500
|
+
if (k !== void 0) out.set(k, [...out.get(k) ?? [], item]);
|
|
4501
|
+
}
|
|
4502
|
+
return [...out.values()].filter((g) => g.length > 1);
|
|
4503
|
+
}
|
|
4504
|
+
function faultPhrase(ctx) {
|
|
4505
|
+
if (ctx.duplicateDelivery) return " when the triggering webhook was delivered twice";
|
|
4506
|
+
const f = ctx.fault;
|
|
4507
|
+
if (!f || f.triggered === false || !ctx.events.some((e) => e.operation === "fault")) return "";
|
|
4508
|
+
const who = displayName(ctx.services, f.service);
|
|
4509
|
+
return f.type === "timeout-after-write" ? ` when ${who} timed out after saving the write` : f.type === "server-error" ? ` when ${who} returned a 500` : f.type === "slow-response" ? ` when ${who} answered slower than your client timeout` : f.type === "blackhole" ? ` when ${who} dropped a request` : f.type === "duplicate-write" ? ` when ${who} received the same request twice` : ` when ${who} failed`;
|
|
4510
|
+
}
|
|
4511
|
+
function messageChecks(adapter, path) {
|
|
4512
|
+
const noun = adapter === "slack" ? "Slack message" : "email", name = PROVIDER[adapter];
|
|
4513
|
+
const signature = (r) => adapter === "slack" ? typeof r.text === "string" ? canonical3({ channel: r.channel, text: r.text }) : void 0 : Array.isArray(r.labelIds) && !r.labelIds.includes("SENT") ? void 0 : canonical3(gmailText(r));
|
|
4514
|
+
const text = (r) => adapter === "slack" ? String(r.text ?? "") : `${gmailText(r).subject} ${gmailText(r).body}`;
|
|
4515
|
+
const target = (r) => adapter === "slack" ? String(r.channel ?? "the channel") : gmailText(r).to || "the recipient";
|
|
4516
|
+
return [{
|
|
4517
|
+
id: `${adapter}.no-duplicate-message`,
|
|
4518
|
+
title: `No duplicate ${noun} for one action`,
|
|
4519
|
+
path,
|
|
4520
|
+
coversDuplicates: true,
|
|
4521
|
+
expected: `each ${noun} sent once per logical action`,
|
|
4522
|
+
impact: "customer-facing",
|
|
4523
|
+
impactHint: `duplicate ${noun}s are visible to ${adapter === "slack" ? "your team or customers" : "customers"}`,
|
|
4524
|
+
run(ctx) {
|
|
4525
|
+
const s = ctx.service.name;
|
|
4526
|
+
return groups(addedRows(rowsOf(ctx.initialState, s, path), rowsOf(ctx.finalState, s, path)), signature).map((group) => ({
|
|
4527
|
+
path,
|
|
4528
|
+
actual: { messages: group.map((r) => r.id), to: target(group[0]), text: text(group[0]).slice(0, 200) },
|
|
4529
|
+
finding: `Your agent sent the same ${noun} to ${target(group[0])} ${times2(group.length)}${faultPhrase(ctx)}`,
|
|
4530
|
+
impact: { count: group.length - 1 },
|
|
4531
|
+
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
4532
|
+
}));
|
|
4533
|
+
}
|
|
4534
|
+
}, {
|
|
4535
|
+
id: `${adapter}.announce-after-success`,
|
|
4536
|
+
title: `${name} announces only actions that succeeded`,
|
|
4537
|
+
path,
|
|
4538
|
+
expected: `a ${noun} is sent only after the action it announces succeeded`,
|
|
4539
|
+
impact: "customer-facing",
|
|
4540
|
+
impactHint: `the ${noun} reports work that never happened`,
|
|
4541
|
+
run(ctx) {
|
|
4542
|
+
const s = ctx.service.name, out = [];
|
|
4543
|
+
const sent = ctx.events.filter((e) => e.service === s && e.operation === "write" && e.path === path && e.record);
|
|
4544
|
+
const failed = ctx.events.filter((e) => e.service !== s && e.operation === "fault" && /^(server-error|blackhole)\b.*\((POST|PUT|PATCH|DELETE)\)$/.test(e.detail));
|
|
4545
|
+
for (const message of sent) {
|
|
4546
|
+
const words = text(message.record);
|
|
4547
|
+
if (NEGATIVE.test(words)) continue;
|
|
4548
|
+
const unrecovered = failed.find((f) => f.sequence < message.sequence && !ctx.events.some((e) => e.service === f.service && e.sequence > f.sequence && e.sequence < message.sequence && (e.operation === "write" || e.operation === "replay") && (e.path === f.path || e.path.startsWith(`${f.path}/`))));
|
|
4549
|
+
if (!unrecovered) continue;
|
|
4550
|
+
const who = displayName(ctx.services, unrecovered.service);
|
|
4551
|
+
out.push({
|
|
4552
|
+
path,
|
|
4553
|
+
actual: { message: message.record.id, text: words.slice(0, 200), failedService: unrecovered.service, failedPath: unrecovered.path },
|
|
4554
|
+
finding: `Your agent sent "${words.slice(0, 80)}" to ${target(message.record)} after ${who} ${unrecovered.path} failed and was never retried`,
|
|
4555
|
+
impact: { count: 1 },
|
|
4556
|
+
evidence: [unrecovered.sequence, message.sequence]
|
|
4557
|
+
});
|
|
4558
|
+
}
|
|
4559
|
+
return out;
|
|
4560
|
+
}
|
|
4561
|
+
}];
|
|
4562
|
+
}
|
|
4563
|
+
function defaultChecksFor(services, opts = {}) {
|
|
4564
|
+
const refs = services.map(refOf);
|
|
4565
|
+
if (opts.postgres && !refs.some((r) => r.adapter === "postgres")) refs.push({ name: "postgres", adapter: "postgres" });
|
|
4566
|
+
return refs.flatMap((service) => [...registryFor(service.adapter), ...service.adapter === "postgres" ? [] : DEFAULT_CHECKS["*"]].map((check) => ({ service, check })));
|
|
4567
|
+
}
|
|
4568
|
+
function runDefaultChecks(input) {
|
|
4569
|
+
const services = input.spec.services.map((s) => ({ name: s.name, adapter: s.adapter ?? "json-collection", collections: s.collections }));
|
|
4570
|
+
return defaultChecksFor(services, { postgres: !!input.database && !!input.spec.postgres }).map(({ service, check }) => {
|
|
4571
|
+
const violations = check.run({ service, services, initialState: input.initialState, finalState: input.finalState, events: input.events, fault: input.fault, database: input.database, duplicateDelivery: input.duplicateDelivery });
|
|
4572
|
+
const base = { id: `default.${check.id}.${service.name}`, kind: "default", check: check.id, title: check.title, service: service.name, expected: check.expected };
|
|
4573
|
+
if (!violations.length) return { ...base, path: check.path, passed: true, actual: "no violations" };
|
|
4574
|
+
const amounts = violations.filter((v) => typeof v.impact?.amount === "number" && v.impact.amount > 0);
|
|
4575
|
+
const currency = amounts[0]?.impact?.currency;
|
|
4576
|
+
const amount = amounts.filter((v) => v.impact?.currency === currency).reduce((sum, v) => sum + v.impact.amount, 0);
|
|
4577
|
+
const count = violations.reduce((sum, v) => sum + (v.impact?.count ?? 1), 0);
|
|
4578
|
+
const kind = violations.find((v) => v.impact?.kind)?.impact?.kind ?? check.impact;
|
|
4579
|
+
const summary = kind === "money" && amount && currency ? `${money(amount, currency)} paid out more than intended` : `${count} occurrence${count === 1 ? "" : "s"}: ${check.impactHint}`;
|
|
4580
|
+
return {
|
|
4581
|
+
...base,
|
|
4582
|
+
path: violations[0].path,
|
|
4583
|
+
passed: false,
|
|
4584
|
+
actual: violations.length === 1 ? violations[0].actual : violations.map((v) => v.actual),
|
|
4585
|
+
finding: violations[0].finding + (violations.length > 1 ? ` (+${violations.length - 1} more)` : ""),
|
|
4586
|
+
impact: { kind, summary, count, ...amount && currency ? { amount, currency } : {} },
|
|
4587
|
+
evidence: violations.flatMap((v) => v.evidence ?? [])
|
|
4588
|
+
};
|
|
4589
|
+
});
|
|
4590
|
+
}
|
|
4591
|
+
var PROVIDER, displayName, rowsOf, VOLATILE2, volatileKey, canonical3, contentSignature, writeSequences, times2, money, stripeRefundOnce, stripeNoDuplicatePayment, stripeIdempotentRetries, NEGATIVE, gmailText, postgresUpdateApplied, postgresNoDuplicateInsert, NOT_EFFECTS, genericRepeat, DEFAULT_CHECKS, VENDOR_COVERS, registryFor, refOf;
|
|
4592
|
+
var init_default_checks = __esm({
|
|
4593
|
+
"src/runtime/default-checks.ts"() {
|
|
4594
|
+
"use strict";
|
|
4595
|
+
init_run_summary();
|
|
4596
|
+
init_generic_calls();
|
|
4597
|
+
PROVIDER = { stripe: "Stripe", slack: "Slack", gmail: "Gmail", postgres: "Postgres" };
|
|
4598
|
+
displayName = (services, name) => {
|
|
4599
|
+
const s = services.find((x) => x.name === name);
|
|
4600
|
+
return PROVIDER[s?.adapter ?? name] ?? name;
|
|
4601
|
+
};
|
|
4602
|
+
rowsOf = (state, service, path) => (state?.[service]?.[path] ?? []).filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
|
|
4603
|
+
VOLATILE2 = /* @__PURE__ */ new Set(["id", "ts", "created", "created_at", "updated_at", "inserted_at", "createdAt", "updatedAt", "internalDate", "historyId", "threadId", "number", "iid", "latest_charge", "object", "sequence", "uuid"]);
|
|
4604
|
+
volatileKey = (key) => VOLATILE2.has(key) || /_at$|At$/.test(key);
|
|
4605
|
+
canonical3 = (value) => Array.isArray(value) ? `[${value.map(canonical3).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical3(value[k])}`).join(",")}}` : JSON.stringify(value ?? null);
|
|
4606
|
+
contentSignature = (row) => canonical3(Object.fromEntries(Object.entries(row).filter(([k]) => !volatileKey(k))));
|
|
4607
|
+
writeSequences = (ctx, service, ids) => ctx.events.filter((e) => e.service === service && e.operation === "write" && ids.includes(e.record?.id)).map((e) => e.sequence);
|
|
4608
|
+
times2 = (n) => n === 2 ? "twice" : `${n} times`;
|
|
4609
|
+
money = (amount, currency) => formatMoney({ amount: amount / 100, currency: currency.toUpperCase() });
|
|
4610
|
+
stripeRefundOnce = {
|
|
4611
|
+
id: "stripe.refund-once",
|
|
4612
|
+
title: "Each charge refunded at most once per request",
|
|
4613
|
+
path: "/v1/refunds",
|
|
4614
|
+
coversDuplicates: true,
|
|
4615
|
+
expected: "each charge refunded at most once for the same amount and reason; refund total \u2264 charge amount",
|
|
4616
|
+
impact: "money",
|
|
4617
|
+
impactHint: "duplicated refund amount is money paid out twice",
|
|
4618
|
+
run(ctx) {
|
|
4619
|
+
const s = ctx.service.name, out = [];
|
|
4620
|
+
const refunds = addedRows(rowsOf(ctx.initialState, s, "/v1/refunds"), rowsOf(ctx.finalState, s, "/v1/refunds"));
|
|
4621
|
+
for (const group of groups(refunds, (r) => typeof r.charge === "string" ? canonical3({ charge: r.charge, amount: r.amount, reason: r.reason ?? null, metadata: r.metadata ?? {} }) : void 0)) {
|
|
4622
|
+
const amount = Number(group[0].amount), currency = String(group[0].currency ?? "usd"), extra = amount * (group.length - 1);
|
|
4623
|
+
out.push({
|
|
4624
|
+
path: "/v1/refunds",
|
|
4625
|
+
actual: { charge: group[0].charge, refunds: group.map((r) => r.id), amount, currency },
|
|
4626
|
+
finding: `Your agent refunded ${String(group[0].charge)} ${times2(group.length)} (${money(amount, currency)} each)${faultPhrase(ctx)}`,
|
|
4627
|
+
impact: { amount: extra, currency, count: group.length - 1 },
|
|
4628
|
+
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
4629
|
+
});
|
|
4630
|
+
}
|
|
4631
|
+
const all = rowsOf(ctx.finalState, s, "/v1/refunds");
|
|
4632
|
+
for (const charge of rowsOf(ctx.finalState, s, "/v1/charges")) {
|
|
4633
|
+
const total = all.filter((r) => r.charge === charge.id && r.status !== "failed" && r.status !== "canceled").reduce((sum, r) => sum + Number(r.amount ?? 0), 0);
|
|
4634
|
+
if (typeof charge.amount === "number" && total > charge.amount) out.push({
|
|
4635
|
+
path: "/v1/refunds",
|
|
4636
|
+
actual: { charge: charge.id, refunded: total, amount: charge.amount },
|
|
4637
|
+
finding: `Your agent refunded ${money(total, String(charge.currency ?? "usd"))} on ${String(charge.id)}, more than its ${money(charge.amount, String(charge.currency ?? "usd"))} charge`,
|
|
4638
|
+
impact: { amount: total - charge.amount, currency: String(charge.currency ?? "usd") }
|
|
4639
|
+
});
|
|
4640
|
+
}
|
|
4641
|
+
return out;
|
|
4642
|
+
}
|
|
4643
|
+
};
|
|
4644
|
+
stripeNoDuplicatePayment = {
|
|
4645
|
+
id: "stripe.no-duplicate-payment",
|
|
4646
|
+
title: "No duplicate charges or customers for one request",
|
|
4647
|
+
path: "/v1/payment_intents",
|
|
4648
|
+
coversDuplicates: true,
|
|
4649
|
+
expected: "one payment intent per amount/currency/customer/payment method and one customer per email",
|
|
4650
|
+
impact: "money",
|
|
4651
|
+
impactHint: "a duplicated succeeded payment charges the customer twice",
|
|
4652
|
+
run(ctx) {
|
|
4653
|
+
const s = ctx.service.name, out = [];
|
|
4654
|
+
const intents = addedRows(rowsOf(ctx.initialState, s, "/v1/payment_intents"), rowsOf(ctx.finalState, s, "/v1/payment_intents"));
|
|
4655
|
+
for (const group of groups(intents, (r) => canonical3({ amount: r.amount, currency: r.currency, customer: r.customer ?? null, payment_method: r.payment_method ?? null }))) {
|
|
4656
|
+
const succeeded2 = group.filter((r) => r.status === "succeeded"), currency = String(group[0].currency ?? "usd"), amount = Number(group[0].amount);
|
|
4657
|
+
out.push({
|
|
4658
|
+
path: "/v1/payment_intents",
|
|
4659
|
+
actual: { paymentIntents: group.map((r) => r.id), amount, currency, succeeded: succeeded2.length },
|
|
4660
|
+
finding: `Your agent created ${times2(group.length)} the same ${money(amount, currency)} payment${group[0].customer ? ` for ${String(group[0].customer)}` : ""}${faultPhrase(ctx)}`,
|
|
4661
|
+
impact: { amount: amount * Math.max(0, succeeded2.length - 1), currency, count: group.length - 1 },
|
|
4662
|
+
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
4663
|
+
});
|
|
4664
|
+
}
|
|
4665
|
+
const customers = addedRows(rowsOf(ctx.initialState, s, "/v1/customers"), rowsOf(ctx.finalState, s, "/v1/customers"));
|
|
4666
|
+
for (const group of groups(customers, (r) => typeof r.email === "string" && r.email ? r.email.toLowerCase() : void 0))
|
|
4667
|
+
out.push({
|
|
4668
|
+
path: "/v1/customers",
|
|
4669
|
+
actual: { customers: group.map((r) => r.id), email: group[0].email },
|
|
4670
|
+
finding: `Your agent created ${times2(group.length)} the Stripe customer ${String(group[0].email)}${faultPhrase(ctx)}`,
|
|
4671
|
+
impact: { kind: "data-integrity", count: group.length - 1 },
|
|
4672
|
+
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
4673
|
+
});
|
|
4674
|
+
return out;
|
|
4675
|
+
}
|
|
4676
|
+
};
|
|
4677
|
+
stripeIdempotentRetries = {
|
|
4678
|
+
id: "stripe.idempotent-retries",
|
|
4679
|
+
title: "Retried POSTs reuse the idempotency key",
|
|
4680
|
+
path: "/v1",
|
|
4681
|
+
expected: "a POST retried after a fault carries the same Idempotency-Key as the attempt that failed",
|
|
4682
|
+
impact: "reliability",
|
|
4683
|
+
impactHint: "retries without a stable key can duplicate money movement",
|
|
4684
|
+
run(ctx) {
|
|
4685
|
+
const s = ctx.service.name, out = [], events = ctx.events.filter((e) => e.service === s);
|
|
4686
|
+
const writeFault = (e) => e.operation === "fault" && (e.detail.startsWith("write committed") || e.detail.startsWith("slow-response: write") || /^(server-error|blackhole)\b.*\((POST|PUT|PATCH|DELETE)\)$/.test(e.detail));
|
|
4687
|
+
for (const fault of events.filter(writeFault)) {
|
|
4688
|
+
const retry = events.find((e) => e.sequence > fault.sequence && (e.operation === "write" || e.operation === "replay") && (e.path === fault.path || e.path.startsWith(`${fault.path}/`)));
|
|
4689
|
+
if (!retry || retry.operation === "replay") continue;
|
|
4690
|
+
const committed = fault.detail.startsWith("write committed") ? events.filter((e) => e.sequence < fault.sequence && e.operation === "write" && e.path === fault.path).pop() : void 0;
|
|
4691
|
+
const original = committed ? committed.idempotencyKey : fault.idempotencyKey;
|
|
4692
|
+
if (retry.idempotencyKey && retry.idempotencyKey === original) continue;
|
|
4693
|
+
out.push({
|
|
4694
|
+
path: fault.path,
|
|
4695
|
+
actual: { faultEvent: fault.sequence, retryEvent: retry.sequence, retryKey: retry.idempotencyKey ?? null, originalKey: original ?? null },
|
|
4696
|
+
finding: `Your agent retried POST ${fault.path} ${retry.idempotencyKey ? "with a new" : "without an"} idempotency key${faultPhrase(ctx)}`,
|
|
4697
|
+
evidence: [fault.sequence, retry.sequence]
|
|
4698
|
+
});
|
|
4699
|
+
}
|
|
4700
|
+
return out;
|
|
4701
|
+
}
|
|
4702
|
+
};
|
|
4703
|
+
NEGATIVE = /\b(fail|failed|failure|error|unable|could ?n[o']t|cannot|can't|retry|retrying|escalat\w*|pending|not (?:been )?(?:refunded|created|processed|completed))\b/i;
|
|
4704
|
+
gmailText = (r) => {
|
|
4705
|
+
const headers = r.payload?.headers ?? [];
|
|
4706
|
+
const header3 = (name) => headers.find((h) => h.name?.toLowerCase() === name)?.value ?? "";
|
|
4707
|
+
return { to: header3("to"), subject: header3("subject"), body: String(r.payload?.body?.data ?? r.snippet ?? "") };
|
|
4708
|
+
};
|
|
4709
|
+
postgresUpdateApplied = {
|
|
4710
|
+
id: "postgres.update-applied",
|
|
4711
|
+
title: "Updates the agent ran actually changed rows",
|
|
4712
|
+
path: "/",
|
|
4713
|
+
expected: "every UPDATE/DELETE the agent ran matched at least one row",
|
|
4714
|
+
impact: "data-integrity",
|
|
4715
|
+
impactHint: "the agent believes a record changed when it did not",
|
|
4716
|
+
run(ctx) {
|
|
4717
|
+
return (ctx.database?.statements ?? []).filter((st) => /^(UPDATE|DELETE)$/i.test(st.command ?? "") && st.count === 0).map((st) => {
|
|
4718
|
+
const table2 = /^\s*(?:update|delete\s+from)\s+(?:only\s+)?"?([\w.]+)"?/i.exec(st.text)?.[1] ?? "a table";
|
|
4719
|
+
return {
|
|
4720
|
+
path: `/${table2}`,
|
|
4721
|
+
actual: { statement: st.text.slice(0, 200), rowsAffected: 0 },
|
|
4722
|
+
finding: `Your agent ran ${String(st.command).toUpperCase()} on ${table2} but it matched 0 rows, so nothing changed`,
|
|
4723
|
+
impact: { count: 1 }
|
|
4724
|
+
};
|
|
4725
|
+
});
|
|
4726
|
+
}
|
|
4727
|
+
};
|
|
4728
|
+
postgresNoDuplicateInsert = {
|
|
4729
|
+
id: "postgres.no-duplicate-insert",
|
|
4730
|
+
title: "No duplicate rows for one action",
|
|
4731
|
+
path: "/",
|
|
4732
|
+
coversDuplicates: true,
|
|
4733
|
+
expected: "no two rows added by the run are identical apart from ids and timestamps",
|
|
4734
|
+
impact: "data-integrity",
|
|
4735
|
+
impactHint: "duplicate rows double-count orders, refunds or audit entries",
|
|
4736
|
+
run(ctx) {
|
|
4737
|
+
const out = [];
|
|
4738
|
+
if (!ctx.database?.final) return out;
|
|
4739
|
+
for (const table2 of ctx.database.final.tables) {
|
|
4740
|
+
const before = ctx.database.initial.tables.find((t) => t.name === table2.name)?.rows ?? [];
|
|
4741
|
+
for (const group of groups(addedRows(before, table2.rows), contentSignature))
|
|
4742
|
+
out.push({
|
|
4743
|
+
path: `/${table2.name}`,
|
|
4744
|
+
actual: { table: table2.name, rows: group.length, row: group[0] },
|
|
4745
|
+
finding: `Your agent inserted the same ${table2.name} row ${times2(group.length)}${faultPhrase(ctx)}`,
|
|
4746
|
+
impact: { count: group.length - 1 }
|
|
4747
|
+
});
|
|
4748
|
+
}
|
|
4749
|
+
return out;
|
|
4750
|
+
}
|
|
4751
|
+
};
|
|
4752
|
+
NOT_EFFECTS = /* @__PURE__ */ new Set(["openai", "anthropic", "google-oauth"]);
|
|
4753
|
+
genericRepeat = {
|
|
4754
|
+
id: "generic.no-repeat-after-fault",
|
|
4755
|
+
title: "Writes are not repeated after a fault",
|
|
4756
|
+
path: "/",
|
|
4757
|
+
expected: "a write is applied once even when the service faults and the agent retries",
|
|
4758
|
+
impact: "data-integrity",
|
|
4759
|
+
impactHint: "the same record exists twice downstream",
|
|
4760
|
+
run(ctx) {
|
|
4761
|
+
const s = ctx.service.name, out = [];
|
|
4762
|
+
if (NOT_EFFECTS.has(ctx.service.adapter ?? "") || registryFor(ctx.service.adapter).some((c) => c.coversDuplicates)) return out;
|
|
4763
|
+
const faults = ctx.events.filter((e) => e.operation === "fault").map((e) => e.sequence);
|
|
4764
|
+
if (!faults.length && !ctx.duplicateDelivery) return out;
|
|
4765
|
+
for (const path of Object.keys(ctx.finalState?.[s] ?? {})) {
|
|
4766
|
+
for (const group of groups(addedRows(rowsOf(ctx.initialState, s, path), rowsOf(ctx.finalState, s, path)), contentSignature)) {
|
|
4767
|
+
const seq = writeSequences(ctx, s, group.map((r) => r.id));
|
|
4768
|
+
if (!ctx.duplicateDelivery && seq.length && !faults.some((f) => f < Math.max(...seq))) continue;
|
|
4769
|
+
const label2 = path.split("/").filter(Boolean).pop() ?? "record";
|
|
4770
|
+
out.push({
|
|
4771
|
+
path,
|
|
4772
|
+
actual: { records: group.map((r) => r.id ?? null), count: group.length },
|
|
4773
|
+
finding: `Your agent created the same ${s} ${label2.replace(/s$/, "")} ${times2(group.length)}${faultPhrase(ctx)}`,
|
|
4774
|
+
impact: { count: group.length - 1 },
|
|
4775
|
+
evidence: seq
|
|
4776
|
+
});
|
|
4777
|
+
}
|
|
4778
|
+
}
|
|
4779
|
+
return out;
|
|
4780
|
+
}
|
|
4781
|
+
};
|
|
4782
|
+
DEFAULT_CHECKS = {
|
|
4783
|
+
stripe: [stripeRefundOnce, stripeNoDuplicatePayment, stripeIdempotentRetries],
|
|
4784
|
+
slack: messageChecks("slack", "/messages"),
|
|
4785
|
+
gmail: messageChecks("gmail", "/gmail/v1/users/me/messages"),
|
|
4786
|
+
postgres: [postgresUpdateApplied, postgresNoDuplicateInsert],
|
|
4787
|
+
"*": [genericRepeat]
|
|
4788
|
+
};
|
|
4789
|
+
VENDOR_COVERS = { "retry-without-key": /\.idempotent-retries$/, "announce-after-failed-write": /\.announce-after-success$/ };
|
|
4790
|
+
DEFAULT_CHECKS["*"].push(...genericWorldChecks((adapter, rule) => !!VENDOR_COVERS[rule] && registryFor(adapter).some((c) => VENDOR_COVERS[rule].test(c.id))));
|
|
4791
|
+
registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? [];
|
|
4792
|
+
refOf = (s) => typeof s === "string" ? { name: s, adapter: s } : s;
|
|
4793
|
+
}
|
|
4794
|
+
});
|
|
4795
|
+
|
|
2499
4796
|
// src/runtime/local.ts
|
|
2500
4797
|
import { spawn } from "child_process";
|
|
2501
|
-
async function executeLocal(app, spec, signal, existingWorld, seed) {
|
|
4798
|
+
async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {}) {
|
|
2502
4799
|
if (spec.applicationClock) throw new Error("applicationClock requires the Docker runner; no application was executed.");
|
|
2503
4800
|
if (spec.postgres || spec.redis) throw new Error("This world needs PostgreSQL or Redis. Use --runtime hosted or --runtime e2b, or prepare a workflow using HTTP twins only. No local containers are started.");
|
|
2504
4801
|
signal?.throwIfAborted();
|
|
@@ -2506,7 +4803,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed) {
|
|
|
2506
4803
|
try {
|
|
2507
4804
|
const credentials = existingWorld ? world.credentials : await world.start();
|
|
2508
4805
|
const initialState = world.snapshot();
|
|
2509
|
-
const env = { PATH: process.env.PATH ?? "", NODE_ENV: "test" };
|
|
4806
|
+
const env = { ...extraEnv, PATH: process.env.PATH ?? "", NODE_ENV: "test" };
|
|
2510
4807
|
for (const [name, c] of Object.entries(credentials)) {
|
|
2511
4808
|
env[`AGENTTWIN_${name.toUpperCase()}_URL`] = c.endpoint;
|
|
2512
4809
|
env[`AGENTTWIN_${name.toUpperCase()}_TOKEN`] = c.token;
|
|
@@ -2583,8 +4880,9 @@ async function executeLocal(app, spec, signal, existingWorld, seed) {
|
|
|
2583
4880
|
}
|
|
2584
4881
|
const assertions = world.assertions();
|
|
2585
4882
|
const evaluation = evaluateState(spec, initialState, world.state, world.events);
|
|
2586
|
-
const
|
|
2587
|
-
|
|
4883
|
+
const defaultChecks = runDefaultChecks({ spec, initialState, finalState: world.state, events: world.events, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null });
|
|
4884
|
+
const status = blockedFetches.length || world.unsupported.length || spec.fault && !world.faultTriggered ? "incomplete" : timedOut || exitCode !== 0 ? "error" : background?.passed === false || browser?.passed === false ? "failed" : evaluation.outcome === "passed" && defaultChecks.every((c) => c.passed) ? "passed" : "failed";
|
|
4885
|
+
return { schema: "agenttwin/run-v1", name: spec.name, workflowId: spec.workflowId, status, browser, background, executionError, application: { command: spec.command, exitCode, timedOut, stdout, stderr }, assertions, evaluation, defaultChecks, contracts: operationMatrix(spec), scenario: spec.scenario, infrastructureAssertions: [], fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null, seed: world.seed, reproducibility: "Seed " + world.seed + " deterministically drives twin-side fault scheduling, latency jitter and test credentials. The seed does not control the application's own randomness, wall-clock behavior or threading; compare runs only over twin events and final state.", initialState, finalState: world.snapshot(), events: structuredClone(world.events), blockedFetches, unsupported: [...world.unsupported], durationMs: Date.now() - started, coverage: "CLI Node execution with fresh in-process HTTP collections and advertised provider subsets. Optional Chromium browser steps and bounded collection-state background completion. Not a VM or network/filesystem isolation boundary. No production environment variables inherited; reviewed code can still access the host filesystem and network.", isolation: { kind: "process", productionCredentialsInherited: false, network: "host network; not isolated", rootFilesystem: "host-accessible; explicit files staged in temporary directory" } };
|
|
2588
4886
|
} finally {
|
|
2589
4887
|
if (existingWorld) world.quiesce();
|
|
2590
4888
|
else await world.close();
|
|
@@ -2598,11 +4896,12 @@ var init_local = __esm({
|
|
|
2598
4896
|
init_http_world();
|
|
2599
4897
|
init_evaluation();
|
|
2600
4898
|
init_contracts();
|
|
4899
|
+
init_default_checks();
|
|
2601
4900
|
}
|
|
2602
4901
|
});
|
|
2603
4902
|
|
|
2604
4903
|
// src/runtime/scenarios.ts
|
|
2605
|
-
import { createHash as
|
|
4904
|
+
import { createHash as createHash7 } from "crypto";
|
|
2606
4905
|
import { mkdir, readFile as readFile2, readdir, writeFile as writeFile2 } from "fs/promises";
|
|
2607
4906
|
import { join as join2 } from "path";
|
|
2608
4907
|
import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
|
|
@@ -2651,8 +4950,8 @@ async function loadScenario(cwd, ref) {
|
|
|
2651
4950
|
return scenario;
|
|
2652
4951
|
}
|
|
2653
4952
|
function applyScenario(world, scenario) {
|
|
2654
|
-
const
|
|
2655
|
-
if (!isDeepStrictEqual4(
|
|
4953
|
+
const shape2 = (services) => services.map((s) => ({ name: s.name, adapter: s.adapter ?? "json-collection", paths: s.collections.map((c) => c.path).sort() })).sort((a, b) => a.name.localeCompare(b.name));
|
|
4954
|
+
if (!isDeepStrictEqual4(shape2(world.services), shape2(scenario.services))) throw new Error("Scenario services, adapters and collections must exactly match the world");
|
|
2656
4955
|
return parseWorld({ ...world, services: structuredClone(scenario.services), scenario: { id: scenario.id, version: scenario.version, digest: scenarioDigest(scenario) } });
|
|
2657
4956
|
}
|
|
2658
4957
|
var identifier, object3, sort, scenarioDigest;
|
|
@@ -2663,7 +4962,7 @@ var init_scenarios = __esm({
|
|
|
2663
4962
|
identifier = /^[a-z][a-z0-9_]{0,39}$/;
|
|
2664
4963
|
object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
2665
4964
|
sort = (v) => Array.isArray(v) ? v.map(sort) : object3(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])])) : v;
|
|
2666
|
-
scenarioDigest = (scenario) =>
|
|
4965
|
+
scenarioDigest = (scenario) => createHash7("sha256").update(JSON.stringify(sort(scenario))).digest("hex");
|
|
2667
4966
|
}
|
|
2668
4967
|
});
|
|
2669
4968
|
|
|
@@ -2764,6 +5063,7 @@ var init_docker = __esm({
|
|
|
2764
5063
|
init_http_world();
|
|
2765
5064
|
init_evaluation();
|
|
2766
5065
|
init_contracts();
|
|
5066
|
+
init_default_checks();
|
|
2767
5067
|
init_request_source();
|
|
2768
5068
|
init_docker_postgres();
|
|
2769
5069
|
init_stdio_fetch();
|
|
@@ -2806,7 +5106,6 @@ var init_git = __esm({
|
|
|
2806
5106
|
});
|
|
2807
5107
|
|
|
2808
5108
|
// src/runtime/e2b.ts
|
|
2809
|
-
import { Sandbox } from "e2b";
|
|
2810
5109
|
import { readFile as readFile6 } from "fs/promises";
|
|
2811
5110
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
2812
5111
|
import { homedir as homedir2 } from "os";
|
|
@@ -2819,7 +5118,7 @@ var init_e2b = __esm({
|
|
|
2819
5118
|
});
|
|
2820
5119
|
|
|
2821
5120
|
// src/runtime/matrix.ts
|
|
2822
|
-
import { createHash as
|
|
5121
|
+
import { createHash as createHash8 } from "crypto";
|
|
2823
5122
|
import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5 } from "fs/promises";
|
|
2824
5123
|
import { join as join7, relative, resolve as resolve2 } from "path";
|
|
2825
5124
|
var init_matrix = __esm({
|
|
@@ -2832,7 +5131,7 @@ var init_matrix = __esm({
|
|
|
2832
5131
|
});
|
|
2833
5132
|
|
|
2834
5133
|
// src/runtime/source-build.ts
|
|
2835
|
-
import { createHash as
|
|
5134
|
+
import { createHash as createHash9 } from "crypto";
|
|
2836
5135
|
import { lstat, readFile as readFile8, realpath as realpath2 } from "fs/promises";
|
|
2837
5136
|
import { isAbsolute, join as join8, relative as relative2, resolve as resolve3, sep } from "path";
|
|
2838
5137
|
import { isDeepStrictEqual as isDeepStrictEqual6 } from "util";
|
|
@@ -2848,7 +5147,7 @@ import { mkdtemp as mkdtemp3, mkdir as mkdir5, readFile as readFile9, writeFile
|
|
|
2848
5147
|
import { tmpdir as tmpdir3 } from "os";
|
|
2849
5148
|
import { basename, dirname, isAbsolute as isAbsolute2, join as join9, relative as relative3, resolve as resolve4, sep as sep2 } from "path";
|
|
2850
5149
|
import { fileURLToPath } from "url";
|
|
2851
|
-
import { createHash as
|
|
5150
|
+
import { createHash as createHash10, randomUUID as randomUUID3 } from "crypto";
|
|
2852
5151
|
async function stageApplication(root, files, destination) {
|
|
2853
5152
|
const canonicalRoot = await realpath3(root);
|
|
2854
5153
|
const digests = {};
|
|
@@ -2864,13 +5163,14 @@ async function stageApplication(root, files, destination) {
|
|
|
2864
5163
|
const target = join9(destination, file);
|
|
2865
5164
|
await mkdir5(dirname(target), { recursive: true });
|
|
2866
5165
|
await writeFile6(target, contents, { mode: 420 });
|
|
2867
|
-
digests[file] =
|
|
5166
|
+
digests[file] = createHash10("sha256").update(contents).digest("hex");
|
|
2868
5167
|
}
|
|
2869
5168
|
return digests;
|
|
2870
5169
|
}
|
|
2871
5170
|
var init_run = __esm({
|
|
2872
5171
|
"src/commands/run.ts"() {
|
|
2873
5172
|
"use strict";
|
|
5173
|
+
init_run_summary();
|
|
2874
5174
|
init_remote();
|
|
2875
5175
|
init_local();
|
|
2876
5176
|
init_docker();
|
|
@@ -2894,14 +5194,14 @@ init_contracts();
|
|
|
2894
5194
|
init_run();
|
|
2895
5195
|
init_git();
|
|
2896
5196
|
import { createServer as createServer2 } from "http";
|
|
2897
|
-
import { randomBytes as randomBytes4, randomUUID as randomUUID4, createHash as
|
|
5197
|
+
import { randomBytes as randomBytes4, randomUUID as randomUUID4, createHash as createHash11 } from "crypto";
|
|
2898
5198
|
import { mkdir as mkdir6, mkdtemp as mkdtemp4, readFile as readFile10, readdir as readdir2, rename, rm as rm5, writeFile as writeFile7 } from "fs/promises";
|
|
2899
5199
|
import { dirname as dirname2, join as join10, resolve as resolve5, relative as relative4, sep as sep3 } from "path";
|
|
2900
5200
|
import { tmpdir as tmpdir4 } from "os";
|
|
2901
5201
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2902
5202
|
import { spawn as spawn4 } from "child_process";
|
|
2903
5203
|
var uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
2904
|
-
var
|
|
5204
|
+
var hash2 = (spec) => createHash11("sha256").update(JSON.stringify(spec)).digest("hex");
|
|
2905
5205
|
function duration(value) {
|
|
2906
5206
|
if (!Number.isInteger(value) || value < 1 || value > 86400) throw new Error("ttlSeconds must be 1\u201386400");
|
|
2907
5207
|
return value;
|
|
@@ -3017,7 +5317,7 @@ async function serveWorldSession(directory2) {
|
|
|
3017
5317
|
}
|
|
3018
5318
|
let current = parseWorld(JSON.parse(await readFile10(session.file, "utf8")));
|
|
3019
5319
|
if (session.scenario) current = applyScenario(current, await loadScenario(session.cwd, session.scenario));
|
|
3020
|
-
if (
|
|
5320
|
+
if (hash2(current) !== hash2(spec)) throw new Error("World specification or scenario changed; provision a new world. Source patches are allowed.");
|
|
3021
5321
|
const stage = await mkdtemp4(join10(tmpdir4(), "agenttwin-session-run-"));
|
|
3022
5322
|
active = new AbortController();
|
|
3023
5323
|
let result;
|
|
@@ -3037,7 +5337,7 @@ async function serveWorldSession(directory2) {
|
|
|
3037
5337
|
project = JSON.parse(await readFile10(join10(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
|
|
3038
5338
|
} catch {
|
|
3039
5339
|
}
|
|
3040
|
-
const receipt = { ...report, sourceDirectory: relative4(session.cwd, dirname2(session.file)).split(sep3).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest:
|
|
5340
|
+
const receipt = { ...report, sourceDirectory: relative4(session.cwd, dirname2(session.file)).split(sep3).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: hash2(spec), provenance: "CLI-reported execution; not independently attested" };
|
|
3041
5341
|
const out = join10(session.cwd, ".agenttwin/runs", runId);
|
|
3042
5342
|
await mkdir6(out, { recursive: true, mode: 448 });
|
|
3043
5343
|
const evidencePath = join10(out, "run.json");
|