eutaxy 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -8
- package/dist/aws.mjs +5 -5
- package/dist/bin.mjs +1 -2
- package/dist/bin.mjs.map +1 -1
- package/dist/{checksum-DJbbDJA0.mjs → checksum-75EliDEr.mjs} +5 -5
- package/dist/{checksum-DJbbDJA0.mjs.map → checksum-75EliDEr.mjs.map} +1 -1
- package/dist/{src-DIG0_CjU.mjs → cli-BppjMaqL.mjs} +690 -4113
- package/dist/cli-BppjMaqL.mjs.map +1 -0
- package/dist/cli.mjs +1 -2
- package/dist/cloudflare.d.mts +245 -84
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +3 -3
- package/dist/{delivery-invariants-Br29H7Rg.mjs → delivery-invariants-_T9ZMwOJ.mjs} +2 -2
- package/dist/{delivery-invariants-Br29H7Rg.mjs.map → delivery-invariants-_T9ZMwOJ.mjs.map} +1 -1
- package/dist/{event-streams-eH6Jim9p.mjs → event-streams-lXGVdHFn.mjs} +2 -2
- package/dist/{event-streams-eH6Jim9p.mjs.map → event-streams-lXGVdHFn.mjs.map} +1 -1
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -1
- package/dist/provers-DS44OeEm.mjs +83 -0
- package/dist/provers-DS44OeEm.mjs.map +1 -0
- package/dist/{src-CWVQEhTr.mjs → src-ClXnIi6O.mjs} +3 -83
- package/dist/src-ClXnIi6O.mjs.map +1 -0
- package/dist/{src-DGh7w877.mjs → src-DPCF2XGv.mjs} +103 -16
- package/dist/src-DPCF2XGv.mjs.map +1 -0
- package/dist/workerd-DVJ8eCLI.mjs +5200 -0
- package/dist/workerd-DVJ8eCLI.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/cli-BFTyLLRF.mjs +0 -2
- package/dist/src-CWVQEhTr.mjs.map +0 -1
- package/dist/src-DGh7w877.mjs.map +0 -1
- package/dist/src-DIG0_CjU.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workerd-DVJ8eCLI.mjs","names":["retryDelayMs","coreAtLeastOncePerMessage","deliverMessage","deliverMessage"],"sources":["../../cli/src/regression.ts","../../cloudflare/src/background.ts","../../cloudflare/src/alarms.ts","../../cloudflare/src/durable-objects.ts","../../cloudflare/src/entrypoint.ts","../../cloudflare/src/caller.ts","../../cloudflare/src/cron.ts","../../cloudflare/src/scenario.ts","../../cloudflare/src/rpc.ts","../../cloudflare/src/services.ts","../../cloudflare/src/callees.ts","../../cloudflare/src/check.ts","../../cloudflare/src/d1.ts","../../cloudflare/src/r2.ts","../../cloudflare/src/workflows.ts","../../cloudflare/src/bindings.ts","../../cloudflare/src/http.ts","../../cloudflare/src/queues.ts","../../cloudflare/src/scheduled.ts","../../cloudflare/src/websocket.ts","../../cloudflare/src/platform.ts","../../cloudflare/src/differential.ts","../../cli/src/keys.ts","../../cli/src/workerd.ts"],"sourcesContent":["import type { Violated } from \"@eutaxy/core\";\nimport { emitRegressionTest } from \"@eutaxy/report\";\n\nexport interface CloudflareRegressionOptions {\n /** Import path of the scenario module, relative to the emitted file. */\n readonly scenarioPath: string;\n /** Import path of the Worker module. */\n readonly workerPath: string;\n /** D1 binding name to schema file path, imported with `?raw`. */\n readonly schemaPaths: Readonly<Record<string, string>>;\n /**\n * The time budget the check ran with, when it replaced the scenario's: the\n * replay gets the same, so I/O that finished within it does not time out.\n */\n readonly budgetMs?: number;\n /** The platform's retry limit, when the scenario was checked with a non-default one. */\n readonly maxRetries?: number;\n /** The scenario sets up Durable Objects: pass the Cloudflare test helpers to the platform. */\n readonly durableObjects?: boolean;\n /**\n * Pass the Worker module's exports to the platform: the scenario sets up\n * Workflows (their classes are among them) or drives a named entrypoint.\n */\n readonly exports?: boolean;\n /** @deprecated Use `exports`. */\n readonly workflows?: boolean;\n /**\n * The Workers behind service bindings the scenario names with `callee`, by\n * binding: each one's name from its wrangler config and the import path of\n * its module.\n */\n readonly callees?: Readonly<\n Record<\n string,\n {\n readonly name: string;\n readonly path: string;\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, unknown>>;\n }\n >\n >;\n /**\n * The qualified names the callees' bindings had in the check's isolate: the\n * replay needs them in its own, so the test says so at its top.\n */\n readonly calleeBindings?: readonly string[];\n /** Qualified binding names that are aliases of the caller's bindings, passed to the platform. */\n readonly aliases?: Readonly<Record<string, string>>;\n readonly expect?: \"holds\" | \"violates\";\n readonly engineModule?: string;\n /** Core modules to observe during the replay (import path, functions), for `refines`. */\n readonly specModules?: readonly {\n readonly path: string;\n readonly functions: readonly string[];\n }[];\n}\n\n/**\n * Identifiers for binding names: a qualified name (`orders/DB`) becomes\n * `orders_DB`, and a name whose identifier another already took gets a\n * count (`orders_DB_2`), so two imports never share a name.\n */\nfunction identifiers(names: readonly string[]): ReadonlyMap<string, string> {\n const taken = new Set<string>();\n const out = new Map<string, string>();\n for (const name of names) {\n const base = name.replace(/[^A-Za-z0-9_$]/g, \"_\");\n let id = base;\n for (let n = 2; taken.has(id); n++) id = `${base}_${n}`;\n taken.add(id);\n out.set(name, id);\n }\n return out;\n}\n/** A binding name as an object key: bare where it is an identifier, quoted otherwise. */\nconst key = (binding: string): string =>\n /^[A-Za-z_$][\\w$]*$/.test(binding) ? binding : JSON.stringify(binding);\n\n/** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */\nexport function cloudflareRegressionTest(\n verdict: Violated,\n options: CloudflareRegressionOptions,\n): string {\n const bindings = Object.keys(options.schemaPaths).sort();\n const callees = Object.keys(options.callees ?? {}).sort();\n const schemaIds = identifiers(bindings);\n const calleeIds = identifiers(callees);\n const ident = (binding: string): string =>\n schemaIds.get(binding) ?? calleeIds.get(binding) ?? binding;\n const withExports = options.exports === true || options.workflows === true;\n const note =\n callees.length === 0 || (options.calleeBindings ?? []).length === 0\n ? []\n : [\n `// Needs the callees' bindings in this test's isolate under their qualified names: ${(options.calleeBindings ?? []).join(\", \")}.`,\n \"// Declare them in the wrangler config, or run this test under the config eutaxy check --keep leaves in .eutaxy/.\",\n ];\n const imports = [\n ...note,\n 'import { createCloudflarePlatform } from \"eutaxy/cloudflare\";',\n 'import { env } from \"cloudflare:workers\";',\n ...(options.durableObjects ? ['import * as cloudflareTest from \"cloudflare:test\";'] : []),\n `import scenario from ${JSON.stringify(options.scenarioPath)};`,\n ...bindings.map(\n (b) => `import schema_${ident(b)} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`,\n ),\n ...callees.map(\n (b) =>\n `import * as callee_${calleeIds.get(b)} from ${JSON.stringify(options.callees?.[b]?.path)};`,\n ),\n withExports\n ? `import * as worker from ${JSON.stringify(options.workerPath)};`\n : `import handler from ${JSON.stringify(options.workerPath)};`,\n ...(options.specModules ?? []).map(\n (m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`,\n ),\n ];\n const schemas = `{ ${bindings.map((b) => `${key(b)}: schema_${ident(b)}`).join(\", \")} }`;\n const calleeOption =\n callees.length === 0\n ? \"\"\n : `, callees: { ${callees\n .map(\n (b) =>\n `${key(b)}: { name: ${JSON.stringify(options.callees?.[b]?.name)}, exports: callee_${calleeIds.get(b)}${options.callees?.[b]?.entrypoint === undefined ? \"\" : `, entrypoint: ${JSON.stringify(options.callees?.[b]?.entrypoint)}`}${options.callees?.[b]?.props === undefined ? \"\" : `, props: ${JSON.stringify(options.callees?.[b]?.props)}`} }`,\n )\n .join(\", \")} }`;\n const retries = options.maxRetries === undefined ? \"\" : `, maxRetries: ${options.maxRetries}`;\n const aliases =\n options.aliases === undefined || Object.keys(options.aliases).length === 0\n ? \"\"\n : `, aliases: ${JSON.stringify(options.aliases)}`;\n const objects = options.durableObjects ? \", durableObjects: cloudflareTest\" : \"\";\n const handler = withExports ? \"handler: worker.default\" : \"handler\";\n const exports = withExports ? \", exports: worker\" : \"\";\n return emitRegressionTest(verdict, {\n imports,\n platform: `createCloudflarePlatform({ env, ${handler}, schemas: ${schemas}${retries}${objects}${exports}${calleeOption}${aliases} })`,\n scenario:\n options.budgetMs === undefined\n ? \"scenario\"\n : `{ ...scenario, bounds: { ...scenario.bounds, budgetMs: ${options.budgetMs} } }`,\n ...(options.expect ? { expect: options.expect } : {}),\n ...(options.engineModule ? { engineModule: options.engineModule } : {}),\n ...(options.specModules && options.specModules.length > 0\n ? {\n observe: options.specModules.map((m, i) => ({\n namespace: `core_${i}`,\n functions: m.functions,\n })),\n }\n : {}),\n });\n}\n","/** What a delivery hands the Worker besides the event: its `ExecutionContext`, and the background work it collects. */\n\nimport type { FaultKind, RunHooks } from \"@eutaxy/core\";\nimport { CrashSignal } from \"@eutaxy/engine\";\nimport type { WorkerHandler } from \"./platform.ts\";\n\nconst CUT_OFF: readonly FaultKind[] = [\"cut_off\"];\n\n/** The Worker a delivery runs: its default export and the proxied bindings it sees. */\nexport interface RunningWorker {\n readonly handler: WorkerHandler;\n readonly env: object;\n}\n\n/**\n * The `ExecutionContext` handed to a handler; `waitUntil` work is collected to\n * run after it returns, and `props` is what the caller's binding carries\n * (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/, props). A rejection is kept in `failures` when given: a\n * scheduled invocation's status is that of its first failed `waitUntil`\n * (Cloudflare, Scheduled handler); a queue or HTTP delivery's is not.\n */\nexport function executionContext(\n background: Promise<unknown>[],\n failures?: unknown[],\n /** What `ctx.props` holds: for a callee, the `props` the caller's service binding carries (a copy). */\n props: object = {},\n): ExecutionContext {\n return {\n waitUntil: (promise: Promise<unknown>) => {\n background.push(\n promise.then(\n () => undefined,\n (error: unknown) => {\n failures?.push(error);\n },\n ),\n );\n },\n passThroughOnException: () => {},\n props: structuredClone(props),\n } as unknown as ExecutionContext;\n}\n\n/**\n * Background work extends the invocation but never changes the acknowledgement or the response.\n * A cut-off here is the isolate dying after them: work not yet started is lost.\n */\nexport async function drainBackground(\n hooks: RunHooks,\n inv: { isCrashed(): boolean; readonly crashed: Promise<void> },\n invocation: string,\n target: string,\n background: readonly Promise<unknown>[],\n): Promise<boolean> {\n if (background.length === 0 || inv.isCrashed()) return false;\n try {\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"background\",\n args: { pending: background.length },\n allowed: CUT_OFF,\n },\n () => null,\n () => null,\n );\n await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);\n return false;\n } catch (err) {\n if (!(err instanceof CrashSignal)) throw err;\n return true;\n }\n}\n","/**\n * Durable Object alarms in virtual time. Eutaxy takes over each object's\n * alarm methods (on its storage and inside transactions), so the runtime\n * never schedules an alarm on the real clock, whose time is far ahead of\n * the virtual one. A set alarm is kept per object, so it survives eviction\n * as a real one does, and becomes an event due at its virtual time; when\n * the run reaches it, the object's `alarm()` handler runs as one effect.\n *\n * Semantics, as Cloudflare documents them (developers.cloudflare.com/\n * durable-objects/api/base/#alarm): an object has one alarm, a later\n * `setAlarm` replaces it, execution is at least once, and a handler that\n * throws is retried with exponential backoff starting at two seconds, up to\n * six retries, with `{ retryCount, isRetry }`. `setAlarm` inside a\n * transaction takes effect only if the transaction commits.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n invocationOf,\n type JsonValue,\n type RunHooks,\n readFaults,\n redelivery,\n} from \"@eutaxy/core\";\nimport { runInvocation } from \"@eutaxy/engine\";\n\n/** `EventRef.source` of an alarm event. */\nexport const alarmSource = \"durable_object_alarm\";\n\n/** Cloudflare retries a failed alarm handler up to six times, after 2 s, 4 s, 8 s, ... */\nconst maxRetries = 6;\nconst firstRetryMs = 2_000;\n\n/** One object's alarm, kept across its instances for the run. */\ninterface AlarmEntry {\n time: number | null;\n /** Alarm changes for this object so far, for unique event ids. */\n seq: number;\n /**\n * The current alarm's generation: every setAlarm or deleteAlarm starts a\n * new one, and an event or retry of an older generation is superseded.\n */\n gen: number;\n /** Times the alarm fired this run (retries not counted). */\n firings: number;\n}\n\n/** What an alarm event carries. */\ninterface AlarmData {\n readonly binding: string;\n readonly gen: number;\n readonly id: string;\n readonly object: string;\n readonly time: number;\n readonly retryCount: number;\n}\n\n/** The alarms of one namespace's objects; the platform clears it before each run. */\nexport class AlarmBook {\n private readonly entries = new Map<string, AlarmEntry>();\n\n clear(): void {\n this.entries.clear();\n }\n\n entry(id: string): AlarmEntry {\n let e = this.entries.get(id);\n if (!e) {\n e = { time: null, seq: 0, gen: 0, firings: 0 };\n this.entries.set(id, e);\n }\n return e;\n }\n}\n\n/** The alarm of one object, as its taken-over methods see it. */\nexport interface AlarmControl {\n get(): number | null;\n set(time: number): void;\n delete(): void;\n /** Report something about the object's alarms that Eutaxy cannot model faithfully. */\n unsupported(reason: string): void;\n}\n\n/** One alarm control per object: setting schedules an event at the alarm's virtual time. */\nexport function alarmControl(\n book: AlarmBook,\n binding: string,\n id: string,\n object: string,\n hooks: () => RunHooks,\n): AlarmControl {\n const entry = book.entry(id);\n return {\n get: () => entry.time,\n set: (time) => {\n entry.time = time;\n entry.seq++;\n entry.gen = entry.seq;\n const data: AlarmData = { binding, gen: entry.gen, id, object, time, retryCount: 0 };\n const now = Date.now();\n hooks().enqueue({\n id: `alarm:${binding}:${object}:${entry.seq}`,\n attempt: 1,\n source: alarmSource,\n data: data as unknown as JsonValue,\n ...(time > now ? { at: time } : {}),\n });\n },\n delete: () => {\n entry.time = null;\n // Supersedes the pending event and any retry of it.\n entry.seq++;\n entry.gen = entry.seq;\n },\n unsupported: (reason) => hooks().unsupported(`Durable Object ${binding} ${object}: ${reason}`),\n };\n}\n\n/** Storage objects whose alarm methods Eutaxy has taken over (one per live instance). */\nexport const takenOver = new WeakSet<object>();\n\nconst timeOf = (time: number | Date) => (typeof time === \"number\" ? time : time.getTime());\n\n/** Storage objects whose alarm was read before Eutaxy took them over (in a constructor). */\nconst readBeforeTakeover = new WeakSet<object>();\n/** Storage prototypes whose getAlarm records such reads. */\nconst watched = new WeakSet<object>();\n\n/**\n * Record reads of the native alarm on storage not yet taken over: a rebuilt\n * object's constructor reads native storage, where Eutaxy's pending alarm is\n * not. The wrapper only records; it returns what the native method returns.\n */\nfunction watchReads(storage: DurableObjectStorage): void {\n const proto = Object.getPrototypeOf(storage) as { getAlarm?: (...a: unknown[]) => unknown };\n if (!proto || watched.has(proto) || typeof proto.getAlarm !== \"function\") return;\n watched.add(proto);\n const native = proto.getAlarm;\n proto.getAlarm = function (this: object, ...args: unknown[]) {\n if (!takenOver.has(this)) readBeforeTakeover.add(this);\n return native.apply(this, args);\n };\n}\n\n/**\n * Replace an object's alarm methods so no real alarm is ever scheduled. An\n * alarm the object set before the takeover (in its constructor) is moved\n * over: deleted from the runtime and set on the control, unless an alarm is\n * still pending, which the constructor could not see in native storage\n * (Eutaxy keeps it): then the pending one stays and the run is UNSUPPORTED.\n */\nexport async function takeOverAlarms(\n storage: DurableObjectStorage,\n alarm: AlarmControl,\n): Promise<void> {\n if (takenOver.has(storage)) return;\n // From the first takeover on, later instances' constructor reads are recorded.\n watchReads(storage);\n takenOver.add(storage);\n if (readBeforeTakeover.has(storage) && alarm.get() !== null) {\n alarm.unsupported(\n \"its constructor read the alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled\",\n );\n }\n const existing = await storage.getAlarm();\n if (existing !== null) {\n await storage.deleteAlarm();\n if (alarm.get() === null) alarm.set(existing);\n else\n alarm.unsupported(\n \"its constructor set an alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled\",\n );\n }\n const s = storage as unknown as Record<string, unknown>;\n // Inside transactionSync an alarm change would have to roll back with it: not modelled.\n let inSync = false;\n const outsideSync = (op: string) => {\n if (inSync) alarm.unsupported(`${op} inside transactionSync() is not modelled`);\n };\n Object.assign(s, {\n setAlarm: async (time: number | Date) => {\n outsideSync(\"setAlarm\");\n alarm.set(timeOf(time));\n },\n getAlarm: async () => alarm.get(),\n deleteAlarm: async () => {\n outsideSync(\"deleteAlarm\");\n alarm.delete();\n },\n });\n if (typeof s[\"transactionSync\"] === \"function\") {\n const transactionSync = (s[\"transactionSync\"] as (cb: () => unknown) => unknown).bind(storage);\n s[\"transactionSync\"] = (callback: () => unknown) => {\n inSync = true;\n try {\n return transactionSync(callback);\n } finally {\n inSync = false;\n }\n };\n }\n const transaction = (\n s[\"transaction\"] as (cb: (txn: unknown) => unknown) => Promise<unknown>\n ).bind(storage);\n // Inside a transaction an alarm change is held until the transaction commits.\n s[\"transaction\"] = async (callback: (txn: unknown) => unknown) => {\n // Per attempt: the runtime may run the callback again after a conflict, discarding the first.\n let pending: { time: number | null } | undefined;\n let rolledBack = false;\n const held = {\n setAlarm: async (time: number | Date) => {\n pending = { time: timeOf(time) };\n },\n getAlarm: async () => (pending ? pending.time : alarm.get()),\n deleteAlarm: async () => {\n pending = { time: null };\n },\n };\n const result = await transaction((txn) => {\n pending = undefined;\n rolledBack = false;\n return callback(\n new Proxy(txn as Record<string, unknown>, {\n get(target, prop) {\n if (typeof prop === \"string\" && prop in held) return held[prop as keyof typeof held];\n const value = target[prop as string];\n if (prop === \"rollback\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n rolledBack = true;\n return (value as (...a: unknown[]) => unknown).apply(target, args);\n };\n }\n // Native methods check their receiver: call them on the real transaction.\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n }),\n );\n });\n if (pending && !rolledBack) {\n if (pending.time === null) alarm.delete();\n else alarm.set(pending.time);\n }\n return result;\n };\n}\n\nexport interface AlarmDelivery {\n readonly binding: string;\n readonly book: AlarmBook;\n /** Alarm firings allowed per object per run; later ones are recorded and not fired. */\n readonly limit: number;\n /** Run the handler inside the object, after taking over its alarms. */\n readonly runAlarm: (\n id: string,\n object: string,\n info: { readonly retryCount: number; readonly isRetry: boolean },\n gen: number,\n ) => Promise<void>;\n /** Record a platform action (an alarm not fired, a handler given up on). */\n readonly bookkeep: (op: string, args: JsonValue) => void;\n /** Reset the object, when the alarm's invocation crashes inside its handler. */\n readonly abort: (id: string) => void;\n /** Whether an effect the handler makes may wait for a turn (not inside blockConcurrencyWhile). */\n readonly mayPark: (id: string) => boolean;\n /** Drop the object's instance, when its alarm invocation crashed around the handler. */\n readonly evict: (id: string) => Promise<void>;\n}\n\n/**\n * Fire an alarm event: skip it when the object's alarm has since moved or\n * been deleted, run `alarm()` as one effect otherwise, and schedule a retry\n * with backoff when the handler fails, crashes, or a fault says it did.\n */\nexport async function deliverAlarm(\n event: EventRef,\n hooks: RunHooks,\n maxRedeliveries: number,\n d: AlarmDelivery,\n): Promise<DeliveryResult> {\n const a = event.data as unknown as AlarmData;\n const entry = d.book.entry(a.id);\n // Superseded by a later setAlarm or deleteAlarm: dropped before anything, faults included.\n if (entry.gen !== a.gen) return { status: \"completed\", followUps: [] };\n if (a.retryCount === 0) {\n if (entry.time !== a.time) return { status: \"completed\", followUps: [] };\n // It stays set until the handler starts (runAlarm clears it after the takeover), as natively.\n if (entry.firings >= d.limit) {\n entry.time = null;\n d.bookkeep(\"alarm_not_fired\", { object: a.object, firings: entry.firings });\n return { status: \"completed\", followUps: [] };\n }\n entry.firings++;\n }\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const info = { retryCount: a.retryCount, isRetry: a.retryCount > 0 };\n const { status } = await runInvocation(hooks, inv, () =>\n hooks.effect(\n {\n invocation,\n target: `DO:${d.binding}`,\n op: \"alarm\",\n args: { object: a.object, retryCount: a.retryCount },\n // Crash before: the handler never ran. Crash after: it ran and committed, but counts as failed.\n allowed: readFaults,\n hostsEffects: true,\n },\n async () => {\n await d.runAlarm(a.id, a.object, info, a.gen);\n return null;\n },\n () => null,\n { onAbandon: () => d.abort(a.id), mayPark: () => d.mayPark(a.id) },\n ),\n );\n // A crash is the object's: its in-memory state goes with the instance, whatever the handler did.\n if (status === \"crashed\") await d.evict(a.id);\n if (status !== \"completed\") {\n // The retries so far are the attempt less one: retryCount counts them too.\n const next = redelivery(event, maxRetries, { maxRedeliveries });\n if (next) {\n const retryAt = Date.now() + firstRetryMs * 2 ** a.retryCount;\n const data: AlarmData = { ...a, retryCount: a.retryCount + 1 };\n // The alarm stays set, for its retry, until a later change supersedes it.\n if (entry.gen === a.gen) entry.time = retryAt;\n hooks.enqueue({ ...next, data: data as unknown as JsonValue, at: retryAt });\n } else {\n // Given up on: no longer pending, unless a newer alarm replaced it meanwhile.\n if (entry.gen === a.gen) entry.time = null;\n d.bookkeep(\"alarm_gave_up\", { object: a.object, retries: a.retryCount });\n }\n }\n return { status, followUps: [] };\n}\n","/**\n * The Durable Object namespace proxy. The objects are the real ones workerd\n * runs: storage, transactions and the input and output gates are the\n * runtime's own. Eutaxy proxies the boundary a Worker crosses to reach them:\n * every call on a stub is an effect point, so a call can fail before it\n * reaches the object (`crash_before`, `error`), or reach it, commit, and\n * lose its answer (`ambiguous`) or its caller (`crash_after`).\n *\n * Between runs every object is cleared, seeded from the scenario's setup\n * and evicted, so it starts from storage alone; after a run its storage is\n * snapshotted for state invariants. Both go through the Cloudflare Vitest\n * plugin's test helpers. Alarms are taken over on each object's storage and\n * fire in virtual time (see alarms.ts).\n */\n\nimport { canonicalJson, type JsonValue, toJson, writeFaults } from \"@eutaxy/core\";\nimport { withoutNetwork } from \"@eutaxy/engine\";\nimport { AlarmBook, alarmControl, takenOver, takeOverAlarms } from \"./alarms.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\nimport type { DurableObjectSqlSeed } from \"./scenario.ts\";\n\n/** Seeds by object name: key-value entries, and SQL for SQLite-backed objects. */\ntype Seeds = { readonly [name: string]: { readonly [key: string]: JsonValue } };\ntype SqlSeeds = { readonly [name: string]: DurableObjectSqlSeed };\n\n/** The SQL surface the seed and the snapshot use, as workerd's `ctx.storage.sql` offers it. */\ninterface SqlSurface {\n exec(query: string, ...bindings: unknown[]): { toArray(): Record<string, unknown>[] };\n}\n\n/** A storage's SQL surface, when the object is SQLite-backed; a key-value object has none that works. */\nfunction sqlOf(storage: unknown): SqlSurface | undefined {\n const sql = (storage as { sql?: unknown }).sql;\n if (typeof sql !== \"object\" || sql === null || typeof (sql as SqlSurface).exec !== \"function\")\n return undefined;\n try {\n (sql as SqlSurface).exec(\"SELECT 1\");\n return sql as SqlSurface;\n } catch {\n return undefined;\n }\n}\n\n/** A JSON value as SQLite stores it: booleans as 0 and 1, objects and arrays as their JSON text. */\nfunction sqlValue(v: JsonValue): unknown {\n if (typeof v === \"boolean\") return v ? 1 : 0;\n if (typeof v === \"object\" && v !== null) return JSON.stringify(v);\n return v;\n}\n\nconst quoted = (name: string): string => `\"${name.replaceAll('\"', '\"\"')}\"`;\n\n/** Run a seed: the schema, then one insert per row. */\nfunction seedSql(sql: SqlSurface, seed: DurableObjectSqlSeed): void {\n sql.exec(seed.schema);\n for (const [table, rows] of Object.entries(seed.rows ?? {}))\n for (const row of rows) {\n const columns = Object.keys(row);\n if (columns.length === 0) {\n // Every column defaulted or generated: still one row.\n sql.exec(`INSERT INTO ${quoted(table)} DEFAULT VALUES`);\n continue;\n }\n sql.exec(\n `INSERT INTO ${quoted(table)} (${columns.map(quoted).join(\", \")}) VALUES (${columns.map(() => \"?\").join(\", \")})`,\n ...columns.map((c) => sqlValue(row[c] as JsonValue)),\n );\n }\n}\n\n/** The user tables of a SQLite-backed object: not SQLite's own, not the runtime's (`_cf_*`, the key-value API's among them). */\nfunction userTables(sql: SqlSurface): string[] {\n return sql\n .exec(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\\\_%' ESCAPE '\\\\' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\' ORDER BY name\",\n )\n .toArray()\n .map((r) => String(r[\"name\"]));\n}\n\n/** Each user table of a SQLite-backed object with its rows, as the storage holds them. */\nfunction readSqlTables(sql: SqlSurface): [string, JsonValue[]][] {\n return userTables(sql).map((t) => [\n t,\n sortedRows(sql.exec(`SELECT * FROM ${quoted(t)}`).toArray()),\n ]);\n}\n\n/** The SQL tables each seeded object held right after its seed, as the snapshot of an object the run never reached. */\nexport type SeededSql = Map<string, [string, JsonValue[]][]>;\n\n/** A table's rows in a fixed order: a table has none of its own, so the canonical JSON of each row decides. */\nfunction sortedRows(rows: readonly Record<string, unknown>[]): JsonValue[] {\n return rows\n .map((r) => toJson(r))\n .sort((a, b) => {\n const x = canonicalJson(a);\n const y = canonicalJson(b);\n return x < y ? -1 : x > y ? 1 : 0;\n });\n}\n\n/**\n * The Cloudflare Vitest plugin's test helpers, as exported by\n * `cloudflare:test` (pass the module namespace). Typed loosely on purpose:\n * the plugin's generic overloads are too deep to check against an interface.\n */\nexport interface DurableObjectTestHelpers {\n readonly runInDurableObject: unknown;\n readonly evictDurableObject: unknown;\n readonly listDurableObjectIds: unknown;\n}\n\n/** The helpers with the signatures this module calls them with. */\ninterface Helpers {\n runInDurableObject<R>(\n stub: DurableObjectStub,\n callback: (instance: unknown, state: DurableObjectState) => R | Promise<R>,\n ): Promise<R>;\n evictDurableObject(stub: DurableObjectStub): Promise<void>;\n listDurableObjectIds(namespace: DurableObjectNamespace): Promise<DurableObjectId[]>;\n}\n\nconst typed = (helpers: DurableObjectTestHelpers): Helpers => helpers as unknown as Helpers;\n\nexport function isDurableObjectNamespace(value: unknown): value is DurableObjectNamespace {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { idFromName?: unknown }).idFromName === \"function\" &&\n typeof (value as { get?: unknown }).get === \"function\"\n );\n}\n\n/** Object names by id, so snapshots and the log name objects as the Worker does. */\nexport type ObjectNames = Map<string, string>;\n\n/** How deep each object state is inside blockConcurrencyWhile, while it is. */\nconst gateDepth = new WeakMap<object, number>();\n/** Object-state prototypes whose blockConcurrencyWhile records that depth. */\nconst gateWatched = new WeakSet<object>();\n\n/**\n * Record when an object holds its input gate with blockConcurrencyWhile,\n * on the state prototype so constructors are covered too; the wrapper only\n * records and calls the native method.\n */\nfunction watchGate(state: DurableObjectState): void {\n const proto = Object.getPrototypeOf(state) as {\n blockConcurrencyWhile?: (cb: () => Promise<unknown>) => Promise<unknown>;\n };\n if (!proto || gateWatched.has(proto) || typeof proto.blockConcurrencyWhile !== \"function\") return;\n gateWatched.add(proto);\n const native = proto.blockConcurrencyWhile;\n proto.blockConcurrencyWhile = function (this: object, callback: () => Promise<unknown>) {\n return native.call(this, async () => {\n gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);\n try {\n return await callback();\n } finally {\n gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);\n }\n });\n };\n}\n\n/** Whether the object is inside blockConcurrencyWhile now. */\nfunction gateHeld(state: DurableObjectState | undefined): boolean {\n return state !== undefined && (gateDepth.get(state) ?? 0) > 0;\n}\n\n/** What Eutaxy keeps about one namespace during a run; the platform clears it before each run. */\nexport class BindingState {\n /** Names learned this run (seeded ones come back with the setup), so traces never depend on earlier runs. */\n readonly names: ObjectNames = new Map();\n /** Ids of the objects a call or an alarm reached this run. */\n readonly touched = new Set<string>();\n /** The objects' alarms in virtual time. */\n readonly alarms = new AlarmBook();\n /** Each reached object's live state, so an invocation that crashes inside it can reset it. */\n readonly states = new Map<string, DurableObjectState>();\n /** The SQL tables the seed left in each seeded object, materialized, for the snapshot of one never reached. */\n seededSql: SeededSql = new Map();\n\n /** Whether the object's own effects may wait for a turn: not while it holds its input gate. */\n mayPark(id: string): boolean {\n return !gateHeld(this.states.get(id));\n }\n\n clear(): void {\n this.names.clear();\n this.touched.clear();\n this.alarms.clear();\n this.states.clear();\n this.seededSql = new Map();\n }\n\n /**\n * Reset an object the way a crash does, with `ctx.abort()`, which\n * application code cannot catch: the runtime ends the requests inside it.\n * Called where an injected crash happens inside the object's own work,\n * which is the one place abort() works (from outside, workerd refuses).\n */\n abort(id: string): void {\n const state = this.states.get(id);\n this.states.delete(id);\n try {\n state?.abort(\"Eutaxy: the invocation crashed inside this object\");\n } catch {\n // abort() throws to unwind the object's code; the reset has happened.\n }\n }\n}\n\n/** The storage's own alarm deletion, even after Eutaxy replaced the method on it. */\nasync function deleteRealAlarm(storage: DurableObjectStorage): Promise<void> {\n const proto = Object.getPrototypeOf(storage) as { deleteAlarm?: () => Promise<void> };\n const own = Object.hasOwn(storage, \"deleteAlarm\");\n const deleteAlarm = own ? proto.deleteAlarm : storage.deleteAlarm;\n await deleteAlarm?.call(storage);\n}\n\n/** An RPC argument as effect-log data; a Request becomes its method and URL. */\nfunction argument(value: unknown): JsonValue {\n if (value instanceof Request) return { method: value.method, url: value.url };\n return toJson(value);\n}\n\n/**\n * Whether a result is data the caller holds by value. Anything else (an RPC\n * capability, an object with methods) would let later calls bypass the\n * proxy, so it makes the run UNSUPPORTED.\n */\nexport function isPlainData(value: unknown, depth = 0): boolean {\n if (value === null || value === undefined) return true;\n if (typeof value === \"function\") return false;\n if (typeof value !== \"object\") return true;\n // Too deep to inspect: not certified as data.\n if (depth > 8) return false;\n if (value instanceof Response || value instanceof Date) return true;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;\n const proto = Object.getPrototypeOf(value);\n if (Array.isArray(value)) return value.every((v) => isPlainData(v, depth + 1));\n if (proto !== Object.prototype && proto !== null) return false;\n return Object.values(value).every((v) => isPlainData(v, depth + 1));\n}\n\n/** An RPC result as effect-log data; a Response becomes its status. */\nfunction summarize(result: unknown): JsonValue {\n if (result instanceof Response) return { status: result.status, ok: result.ok };\n return toJson(result);\n}\n\nexport function proxyNamespace(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n state: BindingState,\n helpers: DurableObjectTestHelpers | undefined,\n /** Whether the running scenario resets this namespace (has a `durableObject` setup for it). */\n isReset: () => boolean,\n): DurableObjectNamespace {\n const target = `DO:${binding}`;\n const { names, touched, alarms: book } = state;\n const nameOf = (id: DurableObjectId) => names.get(id.toString()) ?? id.toString();\n\n function stubFor(stub: DurableObjectStub, id: string, object: string): DurableObjectStub {\n /** Make sure the call may reach the object, and take over its alarms first. */\n async function reach(real: DurableObjectStub): Promise<void> {\n if (!helpers) {\n ctx.hooks.unsupported(\n `Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`,\n );\n } else if (!isReset()) {\n ctx.hooks.unsupported(\n `Durable Object binding ${binding} has no durableObject setup, so its objects are not reset between runs; add durableObject(${JSON.stringify(binding)}) to the scenario's setup`,\n );\n } else {\n touched.add(id);\n await typed(helpers).runInDurableObject(real, (_instance, live) => {\n watchGate(live);\n state.states.set(id, live);\n return takeOverAlarms(\n live.storage,\n alarmControl(book, binding, id, object, () => ctx.hooks),\n );\n });\n }\n }\n\n /** A result passed back to the Worker; one that is not plain data cannot be followed. */\n function plain<T>(result: T): T {\n if (!isPlainData(result)) {\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object} returned something that is not plain data (an RPC capability or an object with methods); calls on it would bypass Eutaxy`,\n );\n }\n return result;\n }\n\n /**\n * The promise a call returns. On a real stub it is an RPC promise that\n * pipelines property reads (`stub.getData().value`); this one is not, so\n * a read on it makes the run UNSUPPORTED instead of yielding undefined.\n */\n function pipelineGuard<T>(promise: Promise<T>): Promise<T> {\n return new Proxy(promise, {\n get(target, prop) {\n if (\n typeof prop === \"symbol\" ||\n prop === \"then\" ||\n prop === \"catch\" ||\n prop === \"finally\"\n ) {\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop} on a call's promise) is not supported; await the call first`,\n );\n return undefined;\n },\n });\n }\n\n /** One effect on the object: a method call, or awaiting an RPC property. */\n function onObject(op: string, args: JsonValue, perform: () => Promise<unknown>) {\n return ctx.hooks.effect(\n // The object's own effects during the call (its fetch) belong to this call's turn.\n {\n invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed: writeFaults,\n hostsEffects: true,\n },\n perform,\n summarize,\n {\n // A crash inside the object's own work leaves its request pending: reset the object.\n onAbandon: () => state.abort(id),\n // Inside blockConcurrencyWhile nothing else enters the object: its effects run at once.\n mayPark: () => state.mayPark(id),\n },\n );\n }\n\n return new Proxy(stub, {\n get(real, prop, receiver) {\n // A stub is not a promise; `id` and `name` are not calls.\n if (prop === \"then\") return undefined;\n if (typeof prop !== \"string\" || prop === \"id\" || prop === \"name\")\n return Reflect.get(real, prop, receiver);\n // `stub.method(...)` calls it; `await stub.property` reads an RPC getter. Both are one effect.\n const call = (...args: unknown[]) =>\n pipelineGuard(\n onObject(prop, { object, args: args.map(argument) }, async () => {\n await reach(real);\n // Reflect.apply, not method.apply: an RPC stub's methods are proxies, `.apply` would be a call.\n const method = (real as unknown as Record<string, (...a: unknown[]) => unknown>)[\n prop\n ];\n if (typeof method !== \"function\")\n throw new TypeError(`${binding} stub has no ${prop}`);\n const result = await Reflect.apply(method, real, args);\n // A 101 from the object's fetch: a WebSocket connection now reaches this object.\n if (\n prop === \"fetch\" &&\n result instanceof Response &&\n result.status === 101 &&\n result.webSocket\n )\n ctx.onUpgrade?.({\n binding,\n id,\n object,\n invocation: ctx.currentInvocation(),\n client: result.webSocket,\n });\n return plain(result);\n }),\n );\n const read = () =>\n onObject(prop, { object, property: true }, async () => {\n await reach(real);\n return plain(await (real as unknown as Record<string, unknown>)[prop]);\n });\n const awaitable = (\n onFulfilled?: (v: unknown) => unknown,\n onRejected?: (e: unknown) => unknown,\n ) => read().then(onFulfilled, onRejected);\n // Callable and awaitable; any other property read is pipelining, which is not modelled.\n return new Proxy(call, {\n get(target, key) {\n if (key === \"then\") return awaitable;\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop}.${key}) is not supported; await .${prop} first`,\n );\n return undefined;\n },\n });\n },\n });\n }\n\n function idFromName(name: string): DurableObjectId {\n const id = real.idFromName(name);\n names.set(id.toString(), name);\n return id;\n }\n\n return new Proxy(real, {\n get(target, prop, receiver) {\n switch (prop) {\n case \"idFromName\":\n return idFromName;\n case \"idFromString\":\n return (hex: string) => target.idFromString(hex);\n case \"newUniqueId\":\n return (options?: DurableObjectNamespaceNewUniqueIdOptions) => {\n ctx.hooks.unsupported(\n `${binding}.newUniqueId() is random and differs on replay; use idFromName`,\n );\n return target.newUniqueId(options);\n };\n case \"get\":\n return (id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions) =>\n stubFor(target.get(id, options), id.toString(), nameOf(id));\n case \"getByName\":\n return (name: string) => {\n const id = idFromName(name);\n return stubFor(target.get(id), id.toString(), name);\n };\n case \"jurisdiction\":\n return (jurisdiction: DurableObjectJurisdiction) => {\n ctx.hooks.unsupported(\n `${binding}.jurisdiction() namespaces are not proxied or reset; use the namespace itself`,\n );\n return target.jurisdiction(jurisdiction);\n };\n default: {\n // Native methods check their receiver: call them on the real namespace.\n const value = Reflect.get(target, prop, receiver);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n }\n },\n });\n}\n\n/** Drop an object's instance from outside it; one that is not running has nothing to drop. */\nexport async function evictObject(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers | undefined,\n id: string,\n): Promise<void> {\n if (!helpers) return;\n await typed(helpers)\n .evictDurableObject(real.get(real.idFromString(id)))\n .catch(() => {});\n}\n\n/**\n * Run code inside an object as one of its own events does (an alarm, a\n * WebSocket message): the object is marked reached, its gate watched, its\n * alarms taken over, then `fn` runs with the instance and its state.\n */\nexport async function runInObject<T>(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n helpers: DurableObjectTestHelpers | undefined,\n state: BindingState,\n id: string,\n object: string,\n fn: (instance: unknown, live: DurableObjectState) => Promise<T>,\n): Promise<T | undefined> {\n if (!helpers) {\n ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);\n return undefined;\n }\n state.touched.add(id);\n return typed(helpers).runInDurableObject(\n real.get(real.idFromString(id)),\n async (instance, live) => {\n watchGate(live);\n state.states.set(id, live);\n await takeOverAlarms(\n live.storage,\n alarmControl(state.alarms, binding, id, object, () => ctx.hooks),\n );\n return fn(instance, live);\n },\n );\n}\n\n/**\n * Run an object's `alarm()` handler inside it, after taking over its alarms\n * (the instance may be new since the alarm was set).\n */\nexport function alarmRunner(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n helpers: DurableObjectTestHelpers | undefined,\n state: BindingState,\n): (\n id: string,\n object: string,\n info: { readonly retryCount: number; readonly isRetry: boolean },\n gen: number,\n) => Promise<void> {\n return async (id, object, info, gen) => {\n await runInObject(real, binding, ctx, helpers, state, id, object, async (instance) => {\n // Superseded while the effect waited for its turn: the handler of a cancelled alarm never runs.\n const entry = state.alarms.entry(id);\n if (entry.gen !== gen) return;\n // The alarm is consumed as its handler starts: from here getAlarm() returns null.\n entry.time = null;\n const handler = (instance as { alarm?: (info: unknown) => unknown }).alarm;\n if (typeof handler !== \"function\") {\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object} set an alarm but has no alarm() handler`,\n );\n return;\n }\n await handler.call(instance, info);\n });\n };\n}\n\n/** The objects to reset: every id the namespace has created, plus the setup's named ones. */\nasync function objectIds(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n seeded: readonly string[],\n): Promise<DurableObjectId[]> {\n const ids = new Map<string, DurableObjectId>();\n for (const id of await typed(helpers).listDurableObjectIds(real)) ids.set(id.toString(), id);\n for (const name of seeded) {\n const id = real.idFromName(name);\n names.set(id.toString(), name);\n ids.set(id.toString(), id);\n }\n return [...ids.values()].sort((a, b) => (a.toString() < b.toString() ? -1 : 1));\n}\n\n/**\n * Clear every object of the namespace, write the seeded entries, and evict\n * them all, so each run's first call constructs the object from storage.\n */\nexport async function resetNamespace(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n objects: Seeds,\n sql: SqlSeeds = {},\n): Promise<SeededSql> {\n // Clearing an object constructs it, outside the simulation: its constructor must not reach the network.\n const { value, requested } = await withoutNetwork(() =>\n clearAndSeed(real, helpers, names, objects, sql),\n );\n if (requested) {\n throw new Error(\n \"a Durable Object constructor made a request during reset; constructors run outside the simulation there, so objects whose constructor does I/O are not supported\",\n );\n }\n return value;\n}\n\n/** The names a setup seeds: those with key-value entries and those with SQL. */\nconst seededNames = (objects: Seeds, sql: SqlSeeds): string[] => [\n ...new Set([...Object.keys(objects), ...Object.keys(sql)]),\n];\n\nasync function clearAndSeed(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n objects: Seeds,\n sql: SqlSeeds,\n): Promise<SeededSql> {\n const seededSql: SeededSql = new Map();\n const ids = await objectIds(real, helpers, names, seededNames(objects, sql));\n for (const id of ids) {\n const stub = real.get(id);\n const name = names.get(id.toString());\n // Own entries only, and only for a known name: an object may be named \"\" or \"__proto__\".\n const entries = name !== undefined && Object.hasOwn(objects, name) ? objects[name] : undefined;\n const seed = name !== undefined && Object.hasOwn(sql, name) ? sql[name] : undefined;\n await typed(helpers).runInDurableObject(stub, async (_instance, state) => {\n // Before any constructor of this run: so its blockConcurrencyWhile is seen too.\n watchGate(state);\n // deleteAll drops SQL and key-value data alike (Cloudflare, Storage API).\n await state.storage.deleteAll();\n await deleteRealAlarm(state.storage);\n if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);\n if (seed) {\n const surface = sqlOf(state.storage);\n if (!surface)\n throw new Error(\n `Durable Object ${name} has a sql seed but is not SQLite-backed (no working ctx.storage.sql); add its class to new_sqlite_classes in the wrangler migrations`,\n );\n seedSql(surface, seed);\n // What the seed left, as SQLite holds it (defaults, generated ids, affinities), for the snapshot\n // of this object when no call reaches it.\n seededSql.set(name as string, readSqlTables(surface));\n }\n });\n // The object just ran, so eviction can only fail for a real reason: let it fail the reset.\n await typed(helpers).evictDurableObject(stub);\n }\n return seededSql;\n}\n\n/**\n * Each object's storage as rows `{ key, value }`, sorted by key, one table\n * per object name. An object no call reached this run still holds exactly\n * its seed (reset left it evicted), so its rows come from the seed and it is\n * not constructed: its constructor would run outside the simulation. Such an\n * object that is running anyway was reached some other way (through another\n * object's own binding): `onIndirect` is told, and the seed is not its state.\n * The tables are the seeded objects and those a call reached, never objects\n * only earlier runs created, so a snapshot depends on this run alone.\n */\nexport async function snapshotNamespace(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n touched: ReadonlySet<string>,\n objects: Seeds,\n sql: SqlSeeds,\n seededSql: SeededSql,\n onIndirect: (object: string) => void,\n onUnsupported: (reason: string) => void,\n): Promise<{ readonly [object: string]: readonly JsonValue[] }> {\n // Reading an object that is no longer running reconstructs it, outside the simulation.\n const { value, requested } = await withoutNetwork(() =>\n readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported),\n );\n if (requested)\n onUnsupported(\"a Durable Object made a request while its storage was being snapshotted\");\n return value;\n}\n\nasync function readTables(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n touched: ReadonlySet<string>,\n objects: Seeds,\n sql: SqlSeeds,\n seededSql: SeededSql,\n onIndirect: (object: string) => void,\n onUnsupported: (reason: string) => void,\n): Promise<{ readonly [object: string]: readonly JsonValue[] }> {\n const out: Record<string, JsonValue[]> = {};\n // Defined, not assigned: an object may be named \"__proto__\". Names may not hold \"/\", so a table's\n // key never collides with an object's; a collision anyway is a bug, never a silent overwrite.\n const define = (table: string, rows: JsonValue[]) => {\n if (Object.hasOwn(out, table)) throw new Error(`snapshot key ${table} named twice`);\n Object.defineProperty(out, table, {\n value: rows,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n };\n const seeded = seededNames(objects, sql);\n for (const id of await objectIds(real, helpers, names, seeded)) {\n const name = names.get(id.toString()) ?? id.toString();\n if (!touched.has(id.toString())) {\n // Eviction only succeeds on a running object, and reset left every object evicted.\n const running = await typed(helpers)\n .evictDurableObject(real.get(id))\n .then(\n () => true,\n () => false,\n );\n if (running) onIndirect(name);\n // Objects earlier runs created stay in the namespace's list: only the seed and this run count.\n if (!seeded.includes(name)) continue;\n }\n let entries: [string, unknown][];\n const tables: [string, JsonValue[]][] = [];\n if (touched.has(id.toString())) {\n const read = await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {\n // Storage Eutaxy never took over belongs to an instance built after the run's calls.\n if (!takenOver.has(state.storage))\n onUnsupported(\n `Durable Object ${name} was reset during the run and reconstructed for the snapshot; its constructor ran outside the simulation`,\n );\n const surface = sqlOf(state.storage);\n const sqlTables: [string, JsonValue[]][] = surface ? readSqlTables(surface) : [];\n return Promise.resolve(state.storage.list()).then((kv) => ({ kv: [...kv], sqlTables }));\n });\n entries = read.kv;\n tables.push(...read.sqlTables);\n } else {\n // Untouched: exactly the seed, the key-value entries as given and the SQL tables as the reset\n // read them back after seeding.\n entries = Object.entries(Object.hasOwn(objects, name) ? (objects[name] ?? {}) : {});\n tables.push(...(seededSql.get(name) ?? []));\n }\n define(\n name,\n entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, value]) => ({ key, value: toJson(value) })),\n );\n for (const [table, rows] of tables) define(`${name}/${table}`, rows);\n }\n return out;\n}\n","/**\n * Constructing an entrypoint class (`WorkerEntrypoint`, `WorkflowEntrypoint`)\n * outside the runtime, for the one `new` per call or instance run that the\n * models make themselves.\n */\n\n/** Sets `ctx` and `env` as the runtime's base classes do, for the one `new` workerd would refuse. */\nclass StandInEntrypoint {\n readonly ctx: unknown;\n readonly env: unknown;\n constructor(ctx: unknown, env: unknown) {\n this.ctx = ctx;\n this.env = env;\n }\n}\n\n/**\n * Construct a subclass of the entrypoint base class named `base`. workerd's\n * base constructors accept only a native ExecutionContext, so for this one\n * synchronous `new` the class that extends the base directly extends a\n * stand-in instead; its own constructor and field initialisers run as\n * written, and the base is put back before anything else can run.\n */\nexport function constructEntrypoint(\n cls: unknown,\n base: \"WorkerEntrypoint\" | \"WorkflowEntrypoint\",\n ctx: unknown,\n env: unknown,\n): object {\n if (typeof cls !== \"function\") throw new TypeError(\"not a class\");\n let direct = cls as object;\n for (;;) {\n const parent = Object.getPrototypeOf(direct) as unknown;\n if (typeof parent !== \"function\" || parent === Function.prototype)\n throw new TypeError(`${(cls as { name: string }).name} does not extend ${base}`);\n if ((parent as { name: string }).name === base) break;\n direct = parent;\n }\n const original = Object.getPrototypeOf(direct) as object;\n Object.setPrototypeOf(direct, StandInEntrypoint);\n try {\n return Reflect.construct(cls as new (...a: unknown[]) => object, [ctx, env]);\n } finally {\n Object.setPrototypeOf(direct, original);\n }\n}\n","/**\n * The caller of an inbound request or RPC call. Cloudflare retries neither,\n * so resends follow the policy the drive declares for the caller: how many\n * times it resends, the virtual delay before each resend, and how long it\n * waits for an answer. The decision is the caller's and is made once per\n * attempt: at the response point, or at its deadline if the handler has\n * not answered by then.\n */\n\nimport {\n type EventRef,\n type FaultKind,\n type JsonValue,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\n\n/** The response point: a crash before it is a response the caller never saw. */\nconst RESPOND: readonly FaultKind[] = [\"crash_before\"];\n/**\n * With a caller deadline the answer can also arrive too late: `ambiguous`\n * here means it was sent, the caller counted it as failed, and the handler\n * carried on.\n */\nconst RESPOND_WITH_DEADLINE: readonly FaultKind[] = [\"crash_before\", \"ambiguous\"];\n\n/** What a drive declares about its caller. */\nexport interface CallerPolicy {\n /** Resends after the first attempt. */\n readonly retries: number;\n /** Virtual time the caller waits before resend number i + 1; the last entry repeats, none means at once. */\n readonly delaysMs?: readonly number[];\n /** How long the caller waits for an answer; one that comes later counts as failed. */\n readonly deadlineMs?: number;\n}\n\n/** The virtual delay before resend number `resend` (1 for the first), per the policy. */\nexport function retryDelayMs(policy: Pick<CallerPolicy, \"delaysMs\">, resend: number): number {\n const delays = policy.delaysMs ?? [];\n return delays[Math.min(resend, delays.length) - 1] ?? 0;\n}\n\n/** One attempt's caller, waiting for its answer. */\nexport interface Caller {\n /** The faults the response point admits: with a deadline, also the answer that comes too late. */\n readonly responseFaults: readonly FaultKind[];\n /** Whether the virtual clock is past the caller's deadline now. */\n isLate(): boolean;\n /**\n * The caller's decision once the attempt has an answer or none: it accepts\n * the answer, or gives up, now or at its deadline when the answer was\n * late, and resends or stops.\n */\n settle(accepted: boolean, late: boolean): void;\n}\n\n/**\n * Start waiting for the attempt's answer. With a deadline, a virtual timer\n * makes the caller give up at it whatever the handler is doing, so a resend\n * can start while the first attempt still runs. `gaveUp` is what the\n * `gave_up` effect records when the retries are spent.\n */\nexport function startCaller(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n policy: CallerPolicy,\n target: string,\n gaveUp: JsonValue,\n): Caller {\n // Virtual time: when the caller sent this attempt, for its deadline.\n const started = Date.now();\n const deadline = policy.deadlineMs;\n // The caller gives up at its deadline even when the answer comes later still.\n const lateAt = deadline === undefined ? undefined : started + deadline;\n\n /** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */\n let decided = false;\n const giveUp = (at: number): void => {\n if (decided) return;\n decided = true;\n const next = redelivery(event, policy.retries, spec.bounds);\n if (next) {\n const resendAt = Math.max(at + retryDelayMs(policy, event.attempt), Date.now());\n hooks.enqueue({ ...next, ...(resendAt > Date.now() ? { at: resendAt } : {}) });\n } else {\n hooks.effectSync(\n { invocation: hooks.bookkeeping(), target, op: \"gave_up\", args: gaveUp, allowed: [] },\n () => null,\n () => null,\n );\n }\n };\n // A virtual timer: at the deadline the caller gives up, whatever the handler is doing.\n const deadlineTimer =\n lateAt === undefined ? undefined : setTimeout(() => giveUp(lateAt), deadline);\n\n return {\n responseFaults: deadline === undefined ? RESPOND : RESPOND_WITH_DEADLINE,\n isLate: () => lateAt !== undefined && Date.now() > lateAt,\n settle(accepted, late) {\n // The caller decides as soon as it has an answer or gives up, before background work ends.\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n if (accepted) decided = true;\n else giveUp(late && lateAt !== undefined ? lateAt : Date.now());\n },\n };\n}\n","/**\n * Cloudflare's cron expressions (Workers, Cron Triggers): five fields,\n * minute, hour, day of month, month and weekday, in UTC, with `*`, lists,\n * ranges, steps and names; weekdays run 1 = Sunday to 7 = Saturday. The\n * tick times a scenario drives are the expression's matches from the\n * virtual epoch on, so `scheduledTime` is what the trigger would have set.\n * `L`, `W` and `#` are not modelled: a scenario using them is refused.\n */\n\nconst monthNames = [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\",\n];\nconst dayNames = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"];\n\ninterface Field {\n readonly name: string;\n readonly min: number;\n readonly max: number;\n readonly names?: readonly string[];\n /** The number the first name stands for (months start at 1, Cloudflare's weekdays at 1 = Sunday). */\n readonly firstName?: number;\n}\n\nconst fields: readonly Field[] = [\n { name: \"minute\", min: 0, max: 59 },\n { name: \"hour\", min: 0, max: 23 },\n { name: \"day of month\", min: 1, max: 31 },\n { name: \"month\", min: 1, max: 12, names: monthNames, firstName: 1 },\n { name: \"weekday\", min: 1, max: 7, names: dayNames, firstName: 1 },\n];\n\n/** A parsed expression: the values each field admits. */\nexport interface CronSchedule {\n readonly minutes: ReadonlySet<number>;\n readonly hours: ReadonlySet<number>;\n readonly daysOfMonth: ReadonlySet<number>;\n readonly months: ReadonlySet<number>;\n /** 1 = Sunday to 7 = Saturday, as Cloudflare numbers them. */\n readonly weekdays: ReadonlySet<number>;\n /** Whether the day fields were both given: then a day matches either, as cron has it. */\n readonly anyDayOfMonth: boolean;\n readonly anyWeekday: boolean;\n}\n\nfunction value(token: string, field: Field): number {\n const lower = token.toLowerCase();\n if (field.names) {\n const i = field.names.indexOf(lower);\n if (i >= 0) return (field.firstName ?? 0) + i;\n }\n if (!/^\\d+$/.test(token))\n throw new Error(`${field.name}: ${JSON.stringify(token)} is not a value`);\n const n = Number(token);\n if (n < field.min || n > field.max)\n throw new Error(`${field.name}: ${n} is outside ${field.min}-${field.max}`);\n return n;\n}\n\nfunction parseField(text: string, field: Field): Set<number> {\n if (/[LW#]/i.test(text) && !field.names?.some((n) => text.toLowerCase().includes(n)))\n throw new Error(`${field.name}: L, W and # are not modelled`);\n const out = new Set<number>();\n for (const part of text.split(\",\")) {\n const pieces = part.split(\"/\");\n if (pieces.length > 2 || part === \"\")\n throw new Error(`${field.name}: ${JSON.stringify(part)} is not a value, range or step`);\n const [rangeText, stepText] = pieces as [string, string?];\n let step = 1;\n if (stepText !== undefined) {\n if (!/^\\d+$/.test(stepText) || Number(stepText) < 1)\n throw new Error(`${field.name}: step ${JSON.stringify(stepText)} is not a positive number`);\n step = Number(stepText);\n }\n let from: number;\n let to: number;\n if (rangeText === \"*\") {\n from = field.min;\n to = field.max;\n } else if (rangeText.includes(\"-\")) {\n const ends = rangeText.split(\"-\");\n if (ends.length !== 2)\n throw new Error(`${field.name}: ${JSON.stringify(rangeText)} is not a range`);\n const [a, b] = ends as [string, string];\n from = value(a, field);\n to = value(b, field);\n if (from > to) throw new Error(`${field.name}: range ${rangeText} runs backwards`);\n } else {\n from = value(rangeText, field);\n to = stepText === undefined ? from : field.max;\n }\n for (let v = from; v <= to; v += step) out.add(v);\n }\n return out;\n}\n\n/** Parse an expression; throws with the field and the problem when it is not one Cloudflare accepts. */\nexport function parseCron(expression: string): CronSchedule {\n const parts = expression.trim().split(/\\s+/);\n if (parts.length !== 5)\n throw new Error(\n `a cron expression has five fields, got ${parts.length}: ${JSON.stringify(expression)}`,\n );\n const [minute, hour, dom, month, weekday] = parts as [string, string, string, string, string];\n return {\n minutes: parseField(minute, fields[0] as Field),\n hours: parseField(hour, fields[1] as Field),\n daysOfMonth: parseField(dom, fields[2] as Field),\n months: parseField(month, fields[3] as Field),\n weekdays: parseField(weekday, fields[4] as Field),\n anyDayOfMonth: dom === \"*\",\n anyWeekday: weekday === \"*\",\n };\n}\n\n/** Whether the minute starting at `time` (ms since the epoch, UTC) matches. */\nexport function cronMatches(schedule: CronSchedule, time: number): boolean {\n const d = new Date(time);\n if (!schedule.minutes.has(d.getUTCMinutes()) || !schedule.hours.has(d.getUTCHours()))\n return false;\n if (!schedule.months.has(d.getUTCMonth() + 1)) return false;\n const dayOk = schedule.daysOfMonth.has(d.getUTCDate());\n const weekdayOk = schedule.weekdays.has(d.getUTCDay() + 1);\n // Both day fields restricted: either may match (standard cron); one restricted: it must.\n if (!schedule.anyDayOfMonth && !schedule.anyWeekday) return dayOk || weekdayOk;\n return dayOk && weekdayOk;\n}\n\nconst minuteMs = 60_000;\n/**\n * Between two matches of any expression Cloudflare accepts lie at most eight\n * years (the 29th of February across a century's missing leap year); an\n * expression with no match in that span never fires.\n */\nconst longestGapMs = 9 * 366 * 24 * 60 * minuteMs;\n\n/** The first `count` tick times at or after `from`, each the start of a matching minute. */\nexport function cronTicks(expression: string, from: number, count: number): number[] {\n const schedule = parseCron(expression);\n const out: number[] = [];\n let t = Math.ceil(from / minuteMs) * minuteMs;\n let horizon = t + longestGapMs;\n while (out.length < count) {\n if (t > horizon) throw new Error(`${JSON.stringify(expression)} never fires`);\n if (cronMatches(schedule, t)) {\n out.push(t);\n horizon = t + longestGapMs;\n }\n t += minuteMs;\n }\n return out;\n}\n","/**\n * Typed construction of scenario specs for Cloudflare Workers. Everything here\n * produces the plain-data `ScenarioSpec` from core; this module only knows the\n * Cloudflare shapes (queues, D1 bindings) and the effect conventions the\n * proxies follow.\n */\n\nimport {\n type AtLeastOnce,\n type Bounds,\n atLeastOncePerMessage as coreAtLeastOncePerMessage,\n defaultBounds,\n type EffectSelector,\n type EventRef,\n type EveryRow,\n type ExternalDecl,\n type Implies,\n type Invariant,\n type JsonValue,\n type PlatformData,\n type References,\n type Refines,\n type RowCondition,\n type ScenarioSpec,\n type ScriptedResponse,\n type StateQuery,\n type Unique,\n validateScenario,\n type WorkerRef,\n} from \"@eutaxy/core\";\nimport { virtualEpoch } from \"@eutaxy/engine\";\nimport { cronTicks, parseCron } from \"./cron.ts\";\nimport type { R2Seed } from \"./r2.ts\";\n\n/** One queue message to deliver; `id` defaults to its position. */\nexport interface QueueMessage {\n readonly id?: string;\n readonly body: JsonValue;\n}\n\n/** Drive the Worker's `queue()` handler with these messages. */\nexport interface QueueDrive extends PlatformData {\n readonly kind: \"queue\";\n readonly queue: string;\n readonly messages: readonly { readonly id: string; readonly body: JsonValue }[];\n}\n\n/** One inbound request; `id` defaults to its position, `method` to POST with a body and GET without. */\nexport interface HttpRequestInput {\n readonly id?: string;\n readonly method?: string;\n readonly path: string;\n readonly headers?: { readonly [name: string]: string };\n /** JSON body (sent as application/json) or a string body. */\n readonly body?: JsonValue;\n}\n\n/** A type alias, not an interface, so it is assignable to the JSON shape of `PlatformData`. */\nexport type HttpRequestSpec = {\n readonly id: string;\n readonly method: string;\n readonly path: string;\n readonly headers: { readonly [name: string]: string };\n /** Absent: no body at all. `null` is a JSON body, sent as `null`. */\n readonly body?: JsonValue;\n};\n\n/**\n * Drive the Worker's `fetch()` handler with these requests. The caller's\n * retry policy decides redelivery: a webhook provider resends a request it\n * got no 2xx for (`retryOn: \"non-2xx\"`, the default) or only on 5xx and\n * failures (`\"5xx\"`), up to `retries` times; a browser-like caller has\n * `retries: 0`. `delaysMs[i]` is the virtual time the caller waits before\n * its resend number i + 1 (the last entry repeats; none means at once).\n * `deadlineMs` is how long the caller waits for an answer: one that comes\n * later counts as failed and is resent while the handler may still run.\n */\nexport interface HttpDrive extends PlatformData {\n readonly kind: \"http\";\n readonly requests: readonly HttpRequestSpec[];\n readonly retries: number;\n readonly retryOn: \"non-2xx\" | \"5xx\";\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\nexport interface HttpCallerOptions {\n readonly retries?: number;\n readonly retryOn?: \"non-2xx\" | \"5xx\";\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\nexport function http(\n requests: readonly HttpRequestInput[],\n options: HttpCallerOptions = {},\n): HttpDrive {\n return {\n kind: \"http\",\n requests: requests.map((r, i) => ({\n id: r.id ?? `req-${i + 1}`,\n method: (r.method ?? (r.body === undefined ? \"GET\" : \"POST\")).toUpperCase(),\n path: r.path,\n headers: r.headers ?? {},\n ...(r.body === undefined ? {} : { body: r.body }),\n })),\n retries: options.retries ?? 3,\n retryOn: options.retryOn ?? \"non-2xx\",\n ...(options.delaysMs === undefined ? {} : { delaysMs: [...options.delaysMs] }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n };\n}\n\n/** One message the scenario sends on a connection: text, or a JSON value sent as its text (plain data, as drives are). */\nexport type WebSocketMessageSpec = {\n readonly id: string;\n readonly data: JsonValue;\n};\n\n/** One WebSocket connection the scenario opens to the Worker, and the messages it sends on it, in order. */\nexport type WebSocketConnectionSpec = {\n readonly id: string;\n readonly path: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly messages: readonly WebSocketMessageSpec[];\n};\n\n/**\n * Drive the Worker over WebSocket connections: each connection is opened\n * with an upgrade request to its path (one event) and its messages are sent\n * in order (one event each, after its connection opened and its previous\n * message was handled); every connection closes at the end of the run.\n * Events of different connections interleave as concurrency allows.\n */\nexport interface WebSocketDrive extends PlatformData {\n readonly kind: \"websocket\";\n readonly connections: readonly WebSocketConnectionSpec[];\n}\n\nexport interface WebSocketMessageInput {\n readonly id?: string;\n readonly data: JsonValue;\n}\n\nexport interface WebSocketConnectionInput {\n /** Defaults to its position: `conn-1`, `conn-2`, … */\n readonly id?: string;\n readonly path: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Message ids default to `<connection>:1`, `<connection>:2`, … */\n readonly messages?: readonly WebSocketMessageInput[];\n}\n\nexport function websocket(connections: readonly WebSocketConnectionInput[]): WebSocketDrive {\n return {\n kind: \"websocket\",\n connections: connections.map((c, i) => {\n const id = c.id ?? `conn-${i + 1}`;\n return {\n id,\n path: c.path,\n headers: c.headers ?? {},\n messages: (c.messages ?? []).map((m, j) => ({\n id: m.id ?? `${id}:${j + 1}`,\n data: m.data,\n })),\n };\n }),\n };\n}\n\n/** One RPC call; `id` defaults to its position, `args` to none. */\nexport interface RpcCallInput {\n readonly id?: string;\n readonly method: string;\n readonly args?: readonly JsonValue[];\n}\n\n/** A type alias, not an interface, so it is assignable to the JSON shape of `PlatformData`. */\nexport type RpcCallSpec = {\n readonly id: string;\n readonly method: string;\n readonly args: readonly JsonValue[];\n};\n\n/**\n * Drive a `WorkerEntrypoint` of the Worker with these method calls, one\n * invocation per attempt, the entrypoint constructed anew for each. The\n * entrypoint is the Worker's default export, or the named export\n * `entrypoint`. Cloudflare does not retry an RPC call; the caller resends\n * a call that threw or got no answer up to `retries` times (default 0: a\n * calling Worker resends only when written to), after `delaysMs` of\n * virtual time, and gives up waiting at `deadlineMs`, as the HTTP drive's\n * caller does.\n */\nexport interface RpcDrive extends PlatformData {\n readonly kind: \"rpc\";\n readonly entrypoint?: string;\n readonly calls: readonly RpcCallSpec[];\n readonly retries: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\nexport interface RpcCallerOptions {\n readonly entrypoint?: string;\n readonly retries?: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\nexport function rpc(calls: readonly RpcCallInput[], options: RpcCallerOptions = {}): RpcDrive {\n return {\n kind: \"rpc\",\n ...(options.entrypoint === undefined ? {} : { entrypoint: options.entrypoint }),\n calls: calls.map((c, i) => ({\n id: c.id ?? `call-${i + 1}`,\n method: c.method,\n args: [...(c.args ?? [])],\n })),\n retries: options.retries ?? 0,\n ...(options.delaysMs === undefined ? {} : { delaysMs: [...options.delaysMs] }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n };\n}\n\n/** The target of a call's effects: the method, under the entrypoint's name when the drive names one. */\nexport function rpcTarget(drive: Pick<RpcDrive, \"entrypoint\">, method: string): string {\n return `Rpc:${drive.entrypoint === undefined ? method : `${drive.entrypoint}.${method}`}`;\n}\n\n/** One tick of a Cron Trigger: its id and the virtual time it fires, which the handler sees as `scheduledTime`. */\nexport type CronTickSpec = { readonly id: string; readonly at: number };\n\n/**\n * Drive the Worker's `scheduled()` handler with the ticks of a Cron Trigger:\n * the expression's first `ticks` matches from the virtual epoch on, in UTC,\n * each an event delivered at its virtual time. Cloudflare documents\n * `noRetry()` but no retry count, so the drive declares how many times a\n * tick whose handler failed is re-run (`retries`, default 0); a handler that\n * called `noRetry()` is not re-run.\n */\nexport interface CronDrive extends PlatformData {\n readonly kind: \"cron\";\n readonly cron: string;\n readonly ticks: readonly CronTickSpec[];\n readonly retries: number;\n}\n\nexport interface CronOptions {\n /** How many ticks to drive, from the first match on (default 1). */\n readonly ticks?: number;\n readonly retries?: number;\n}\n\nexport function cron(expression: string, options: CronOptions = {}): CronDrive {\n const count = options.ticks ?? 1;\n const times =\n Number.isInteger(count) && count >= 1 ? cronTicks(expression, virtualEpoch, count) : [];\n return {\n kind: \"cron\",\n cron: expression,\n ticks: times.map((at, i) => ({ id: `tick-${i + 1}`, at })),\n retries: options.retries ?? 0,\n };\n}\n\n/** The drives a Cloudflare scenario can have. */\nexport type Drive = QueueDrive | HttpDrive | RpcDrive | CronDrive | WebSocketDrive;\n\n/** What a WebSocket drive's events carry: an open, or a message with its position on its connection. */\nexport type WebSocketEventData =\n | {\n readonly kind: \"open\";\n readonly connection: string;\n readonly path: string;\n readonly headers: Readonly<Record<string, string>>;\n }\n | {\n readonly kind: \"message\";\n readonly connection: string;\n readonly message: string;\n readonly index: number;\n readonly data: JsonValue;\n };\n\n/** The drive's events as they are first delivered: one per message, request or call, attempt 1. */\nexport function driveEvents(drive: Drive): readonly EventRef[] {\n switch (drive.kind) {\n case \"queue\":\n return drive.messages.map((m) => ({ id: m.id, attempt: 1, data: m.body }));\n case \"http\":\n return drive.requests.map((r) => ({ id: r.id, attempt: 1, data: r as unknown as JsonValue }));\n case \"rpc\":\n return drive.calls.map((c) => ({ id: c.id, attempt: 1, data: c as unknown as JsonValue }));\n case \"cron\":\n // Delivered at its virtual time: the clock moves there once nothing else can.\n return drive.ticks.map((t) => ({\n id: t.id,\n attempt: 1,\n data: { cron: drive.cron, scheduledTime: t.at },\n at: t.at,\n }));\n case \"websocket\": {\n // The opens first, then the messages a round at a time (every connection's first, then every\n // second, …), so the scheduler can interleave connections; each message waits for its connection\n // to be open and for the message before it on that connection.\n const opens: EventRef[] = drive.connections.map((c) => ({\n id: c.id,\n attempt: 1,\n data: {\n kind: \"open\",\n connection: c.id,\n path: c.path,\n headers: c.headers,\n } satisfies WebSocketEventData as unknown as JsonValue,\n }));\n const rounds = Math.max(0, ...drive.connections.map((c) => c.messages.length));\n const messages: EventRef[] = [];\n for (let i = 0; i < rounds; i++)\n for (const c of drive.connections) {\n const m = c.messages[i];\n if (m)\n messages.push({\n id: m.id,\n attempt: 1,\n data: {\n kind: \"message\",\n connection: c.id,\n message: m.id,\n index: i,\n data: m.data,\n } satisfies WebSocketEventData as unknown as JsonValue,\n });\n }\n return [...opens, ...messages];\n }\n }\n}\n\n/** The drive with only the named events kept, for shrinking. */\nexport function restrictDrive(drive: Drive, keepIds: readonly string[]): Drive {\n const keep = (id: string): boolean => keepIds.includes(id);\n switch (drive.kind) {\n case \"queue\":\n return { ...drive, messages: drive.messages.filter((m) => keep(m.id)) };\n case \"http\":\n return { ...drive, requests: drive.requests.filter((r) => keep(r.id)) };\n case \"rpc\":\n return { ...drive, calls: drive.calls.filter((c) => keep(c.id)) };\n case \"cron\":\n return { ...drive, ticks: drive.ticks.filter((t) => keep(t.id)) };\n case \"websocket\":\n // A connection whose open is dropped goes with its messages; a dropped message leaves its\n // connection's others in order.\n return {\n ...drive,\n connections: drive.connections\n .filter((c) => keep(c.id))\n .map((c) => ({ ...c, messages: c.messages.filter((m) => keep(m.id)) })),\n };\n }\n}\n\n/** Apply a SQL file to a D1 binding before each run. */\nexport interface D1Setup extends PlatformData {\n readonly kind: \"d1\";\n readonly binding: string;\n readonly schemaFile: string;\n}\n\n/**\n * Clear a Durable Object namespace before each run and seed the named\n * objects' storage with these entries; its storage is snapshotted after the\n * run for state invariants (see `durableObjectRows`).\n */\nexport interface DurableObjectSetup extends PlatformData {\n readonly kind: \"durable_object\";\n readonly binding: string;\n readonly objects: { readonly [name: string]: { readonly [key: string]: JsonValue } };\n /**\n * How many times each object's alarm may fire in one run (retries not\n * counted); an object that keeps re-arming stops there. Default 3.\n */\n readonly alarmsPerObject?: number;\n /** For SQLite-backed objects, by name: the tables to create and the rows to insert after the clear. */\n readonly sql?: { readonly [name: string]: DurableObjectSqlSeed };\n}\n\n/** A SQLite-backed object's starting storage: its `CREATE TABLE` statements, and rows per table (plain data, as setup steps are). */\nexport type DurableObjectSqlSeed = {\n /** SQL run after the clear: the schema, `CREATE TABLE` statements and the like. */\n readonly schema: string;\n readonly rows?: { readonly [table: string]: readonly SqlRow[] };\n};\n\n/** One row to insert, or one row snapshotted: column name to value (booleans and objects as SQLite stores them). */\nexport type SqlRow = { readonly [column: string]: JsonValue };\n\nexport function durableObject(\n binding: string,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } } = {},\n options: {\n readonly alarmsPerObject?: number;\n readonly sql?: { readonly [name: string]: DurableObjectSqlSeed };\n } = {},\n): DurableObjectSetup {\n return {\n kind: \"durable_object\",\n binding,\n objects,\n ...(options.alarmsPerObject === undefined ? {} : { alarmsPerObject: options.alarmsPerObject }),\n ...(options.sql === undefined ? {} : { sql: options.sql }),\n };\n}\n\n/** An R2 bucket the scenario uses: emptied, then seeded with these objects, before each run. */\nexport interface R2Setup extends PlatformData {\n readonly kind: \"r2\";\n readonly binding: string;\n readonly objects: Readonly<Record<string, R2Seed>>;\n}\n\nexport function r2Bucket(binding: string, objects: Readonly<Record<string, R2Seed>> = {}): R2Setup {\n return { kind: \"r2\", binding, objects };\n}\n\n/**\n * Selects an R2 bucket's operations that completed, a `put` by default; a\n * put whose `onlyIf` failed stored nothing and is not selected, as a D1\n * write that changed no row is not.\n */\nexport function r2Op(\n binding: string,\n op: \"put\" | \"delete\" | \"get\" | \"head\" | \"list\" = \"put\",\n): EffectSelector {\n const target = `R2:${binding}`;\n return op === \"put\"\n ? { target, op, kind: \"result\", where: { \"result.stored\": true } }\n : { target, op, kind: \"result\" };\n}\n\n/** A bucket's objects at the end of the run as rows `{ key, size, etag, customMetadata, httpMetadata, text? }`. */\nexport function r2Rows(binding: string, where?: readonly RowCondition[]): StateQuery {\n const target = `R2:${binding}`;\n return where ? { target, table: \"objects\", where } : { target, table: \"objects\" };\n}\n\n/**\n * Every row the query returns is named by some row of `in` (its `column`\n * equals the row's value at `path`), as with a foreign key.\n */\nexport function references(\n name: string,\n query: StateQuery,\n path: string,\n inQuery: StateQuery,\n column: string,\n): References {\n return { kind: \"references\", name, query, path, in: inQuery, column };\n}\n\n/** A Workflow binding, and the class (an export of the Worker module) its instances run. */\nexport interface WorkflowSetup extends PlatformData {\n readonly kind: \"workflow\";\n readonly binding: string;\n readonly className: string;\n /** The Workflow's `name` in the wrangler config, which instances see as `event.workflowName`. */\n readonly name?: string;\n}\n\nexport function workflow(\n binding: string,\n className: string,\n options: { readonly name?: string } = {},\n): WorkflowSetup {\n return {\n kind: \"workflow\",\n binding,\n className,\n ...(options.name === undefined ? {} : { name: options.name }),\n };\n}\n\n/** A scripted method's reply: a value returned to the caller, or an error (`\"<Name>: <message>\"`) thrown to it. */\nexport type ScriptedReply = { readonly returns: JsonValue } | { readonly throws: string };\n\n/** A reply to `fetch()` through a service binding; a type alias of core's `ScriptedResponse`, for the JSON shape. */\nexport type ServiceResponse = {\n readonly method?: string;\n readonly path?: string;\n readonly status: number;\n readonly headers?: { readonly [name: string]: string };\n readonly body?: JsonValue;\n};\n\n/**\n * Script the Worker another Worker reaches through a service binding: its\n * RPC methods answer from `methods` (every method returns `null` when\n * omitted; a method missing from a present `methods` makes the run\n * UNSUPPORTED) and its `fetch()` from `fetch`, matched by method and path\n * as an external's responses are (200 with an empty body when omitted).\n * The real binding is never called. Each call is one effect,\n * `Service:<binding>`, with the faults of a Durable Object stub call.\n */\nexport interface ServiceSetup extends PlatformData {\n readonly kind: \"service\";\n readonly binding: string;\n readonly methods?: { readonly [method: string]: ScriptedReply };\n readonly fetch?: readonly ServiceResponse[];\n}\n\nexport function service(\n binding: string,\n options: {\n readonly methods?: { readonly [method: string]: ScriptedReply };\n readonly fetch?: readonly ServiceResponse[];\n } = {},\n): ServiceSetup {\n return {\n kind: \"service\",\n binding,\n ...(options.methods === undefined ? {} : { methods: options.methods }),\n ...(options.fetch === undefined ? {} : { fetch: [...options.fetch] }),\n };\n}\n\n/**\n * The Worker behind a service binding, run for real: its module and wrangler\n * config, relative to the scenario, in place of a script. The `name` in that\n * config qualifies the callee's bindings (`orders/DB`) in effect targets,\n * setup steps, state queries and snapshots. Each call is one effect,\n * `Service:<binding>`, hosting the callee's invocation\n * (`<caller invocation>/<binding>.<method>`), with the faults of a call in\n * the network: `crash_before`, `ambiguous` and `crash_after`; what the\n * callee throws is real.\n */\nexport interface CalleeSetup extends PlatformData {\n readonly kind: \"callee\";\n readonly binding: string;\n /** The callee's module, relative to the scenario. */\n readonly entry: string;\n /** Its wrangler config, relative to the scenario; its `name` qualifies the callee's bindings. */\n readonly config: string;\n /** The named export the binding reaches; the default export otherwise. */\n readonly entrypoint?: string;\n}\n\nexport function callee(\n binding: string,\n worker: { readonly entry: string; readonly config: string; readonly entrypoint?: string },\n): CalleeSetup {\n return {\n kind: \"callee\",\n binding,\n entry: worker.entry,\n config: worker.config,\n ...(worker.entrypoint === undefined ? {} : { entrypoint: worker.entrypoint }),\n };\n}\n\n/** A callee and a script for one binding would contradict each other; a callee needs both files named. */\nfunction validateCalleeSetups(setup: ScenarioSpec[\"setup\"]): string[] {\n const errors: string[] = [];\n const scripted = new Set(\n setup.filter((s) => s.kind === \"service\").map((s) => String(s[\"binding\"])),\n );\n const seen = new Set<string>();\n for (const step of setup) {\n if (step.kind !== \"callee\") continue;\n const binding = String(step[\"binding\"]);\n if (!step[\"binding\"]) errors.push(\"callee() needs a binding name\");\n if (!step[\"entry\"]) errors.push(`callee(${JSON.stringify(binding)}) needs the callee's entry`);\n if (!step[\"config\"])\n errors.push(`callee(${JSON.stringify(binding)}) needs the callee's wrangler config`);\n if (scripted.has(binding))\n errors.push(\n `service binding ${JSON.stringify(binding)} has both a service() script and a callee(); keep one`,\n );\n if (seen.has(binding))\n errors.push(`service binding ${JSON.stringify(binding)} has two callee() steps`);\n seen.add(binding);\n }\n return errors;\n}\n\n/** Selects the calls through a service binding that completed (scripted or a callee's), one method's or all. */\nexport function serviceCall(binding: string, method?: string): EffectSelector {\n return {\n target: `Service:${binding}`,\n ...(method === undefined ? {} : { op: method }),\n kind: \"result\",\n };\n}\n\n/** Selects a Workflow's step attempts, optionally of one step; a failed attempt's result carries its error. */\nexport function workflowStep(binding: string, step?: string): EffectSelector {\n return {\n target: `Workflow:${binding}`,\n op: \"step_result\",\n kind: \"result\",\n ...(step === undefined ? {} : { where: { \"args.step\": step } }),\n };\n}\n\n/** A Workflow's instances at the end of the run as rows `{ id, status, params, output?, error? }`. */\nexport function workflowRows(binding: string, where?: readonly RowCondition[]): StateQuery {\n const target = `Workflow:${binding}`;\n return where ? { target, table: \"instances\", where } : { target, table: \"instances\" };\n}\n\n/** Alarm firings per object per run when the setup does not say. */\nexport const defaultAlarmsPerObject = 3;\n\n/**\n * The storage of one object (by the name its id was made from) as rows\n * `{ key, value }`, for state invariants.\n */\nexport function durableObjectRows(\n binding: string,\n object: string,\n where?: readonly RowCondition[],\n): StateQuery {\n const target = `DO:${binding}`;\n return where ? { target, table: object, where } : { target, table: object };\n}\n\n/**\n * One SQL table of a SQLite-backed object (by the name its id was made\n * from) at the end of the run, its rows as the table holds them, for state\n * invariants. The snapshot names it `<object>/<table>`.\n */\nexport function durableObjectTable(\n binding: string,\n object: string,\n table: string,\n where?: readonly RowCondition[],\n): StateQuery {\n const target = `DO:${binding}`;\n const name = `${object}/${table}`;\n return where ? { target, table: name, where } : { target, table: name };\n}\n\nexport interface CloudflareScenarioInput {\n readonly name: string;\n readonly worker: WorkerRef;\n readonly drive:\n | QueueDrive\n | HttpDrive\n | RpcDrive\n | CronDrive\n | WebSocketDrive\n | {\n readonly kind: \"queue\";\n readonly queue: string;\n readonly messages: readonly QueueMessage[];\n };\n readonly setup?: readonly (\n | CalleeSetup\n | D1Setup\n | DurableObjectSetup\n | R2Setup\n | WorkflowSetup\n | ServiceSetup\n )[];\n readonly externals?: readonly ExternalDecl[];\n readonly invariants: readonly Invariant[];\n readonly bounds?: Partial<Bounds>;\n /** Modules of pure core functions with spec files beside them, relative to the scenario (see ScenarioSpec.specs). */\n readonly specs?: readonly string[];\n}\n\nexport function queue(name: string, messages: readonly QueueMessage[]): QueueDrive {\n return {\n kind: \"queue\",\n queue: name,\n messages: messages.map((m, i) => ({ id: m.id ?? `msg-${i + 1}`, body: m.body })),\n };\n}\n\nexport function d1Schema(binding: string, schemaFile: string): D1Setup {\n return { kind: \"d1\", binding, schemaFile };\n}\n\n/**\n * Effect conventions for D1 (what the proxies record):\n * call payload { args: { sql, params } }\n * result payload { args: { sql, params }, result: { changes, lastRowId } }\n * A committed write is a `result` whose `result.changes` is at least 1.\n */\nexport function d1Write(binding: string, op: \"run\" | \"batch\" = \"run\"): EffectSelector {\n return { target: `D1:${binding}`, op, kind: \"result\", atLeast: { \"result.changes\": 1 } };\n}\n\n/** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */\nexport function d1Read(binding: string, op: \"first\" | \"all\" | \"raw\" = \"first\"): EffectSelector {\n return { target: `D1:${binding}`, op, kind: \"result\" };\n}\n\n/** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */\nexport function d1Param(index: number): string {\n return `args.params.${index}`;\n}\n\n/**\n * The shell follows the core function `decision` (see the `refines`\n * invariant): every selected effect carries out the latest decision of its\n * invocation, agrees with it on `follows`, and, with `state`, was not made\n * stale by another invocation's write between the read it rests on and the\n * effect. The core function's module must be listed in the scenario's\n * `specs`, which is what records its calls.\n */\nexport function refines(\n name: string,\n decision: string,\n effect: EffectSelector,\n options: Pick<Refines, \"follows\" | \"state\"> = {},\n): Refines {\n return { kind: \"refines\", name, decision, effect, ...options };\n}\n\n/**\n * Every message's (or request's, or call's) `bodyKey` value must appear at\n * least once as `key` in a selected effect: nothing the drive delivered may\n * be lost. For an RPC drive `bodyKey` is a path into the call's arguments\n * (`\"0.orderId\"`).\n */\nexport function atLeastOncePerMessage(\n name: string,\n drive: Drive,\n effect: EffectSelector,\n key: string,\n bodyKey: string,\n): AtLeastOnce {\n if (drive.kind === \"queue\")\n return coreAtLeastOncePerMessage(name, drive.messages, effect, key, bodyKey);\n if (drive.kind === \"cron\") {\n const ticks = drive.ticks.map((t) => ({\n id: t.id,\n body: { cron: drive.cron, scheduledTime: t.at },\n }));\n return coreAtLeastOncePerMessage(name, ticks, effect, key, bodyKey);\n }\n if (drive.kind === \"rpc\") {\n const calls = drive.calls.map((c) => ({ id: c.id, body: c.args }));\n const inv = coreAtLeastOncePerMessage(name, calls, effect, key, bodyKey);\n // An RPC event's data is the whole call, so the path to re-derive from starts at its arguments.\n return { ...inv, perMessage: { bodyKey: bodyKey === \"\" ? \"args\" : `args.${bodyKey}` } };\n }\n if (drive.kind === \"websocket\") {\n // Per connection, keyed by its path: the one thing its open event carries that a key can come from\n // (a message event has no path, so re-deriving from the remaining events counts opens alone).\n if (bodyKey !== \"\")\n throw new Error(\n `atLeastOncePerMessage ${JSON.stringify(name)}: a websocket drive keys each connection by its path; bodyKey must be \"\"`,\n );\n const conns = drive.connections.map((c) => ({ id: c.id, body: c.path }));\n const inv = coreAtLeastOncePerMessage(name, conns, effect, key, \"\");\n return { ...inv, perMessage: { bodyKey: \"path\" } };\n }\n const requests = drive.requests.map((r) => ({ id: r.id, body: r.body ?? null }));\n const inv = coreAtLeastOncePerMessage(name, requests, effect, key, bodyKey);\n // An HTTP event's data is the whole request, so the path to re-derive from starts at its body.\n return { ...inv, perMessage: { bodyKey: bodyKey === \"\" ? \"body\" : `body.${bodyKey}` } };\n}\n\n/**\n * Selects the frames the Worker sent on a connection (`WebSocket:<connection>`,\n * op `message`), each recorded at the end of the run, in arrival order, with\n * its data (JSON where it parses, text otherwise).\n */\nexport function webSocketReceived(connection: string): EffectSelector {\n return { target: `WebSocket:${connection}`, op: \"message\", kind: \"result\" };\n}\n\n/**\n * Selects the responses the Worker returned for a path (`ok` narrows to 2xx\n * or to everything else). One `result` per attempt: a crash before the\n * response leaves none, a thrown error records status 500.\n */\nexport function httpResponse(\n path: string,\n options: { readonly ok?: boolean } = {},\n): EffectSelector {\n return {\n target: `Http:${path}`,\n op: \"response\",\n kind: \"result\",\n ...(options.ok === undefined ? {} : { where: { \"result.ok\": options.ok } }),\n };\n}\n\n/**\n * Selects the answers an RPC method gave (`ok` narrows to values returned\n * or to errors thrown). One `result` per attempt: a crash before the\n * response leaves none.\n */\nexport function rpcResponse(\n method: string,\n options: { readonly ok?: boolean; readonly entrypoint?: string } = {},\n): EffectSelector {\n return {\n target: rpcTarget(options, method),\n op: \"response\",\n kind: \"result\",\n ...(options.ok === undefined ? {} : { where: { \"result.ok\": options.ok } }),\n };\n}\n\n/** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */\nexport function d1Rows(\n binding: string,\n table: string,\n where?: readonly RowCondition[],\n): StateQuery {\n return where ? { target: `D1:${binding}`, table, where } : { target: `D1:${binding}`, table };\n}\n\n/** Every row the query selects satisfies all conditions. */\nexport function everyRow(\n name: string,\n query: StateQuery,\n holds: readonly RowCondition[],\n): EveryRow {\n return { kind: \"everyRow\", name, query, holds };\n}\n\n/** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */\nexport function unique(name: string, query: StateQuery, path: string): Unique {\n return { kind: \"unique\", name, query, path };\n}\n\n/** Every selected effect has a row whose column equals the effect's key. */\nexport function implies(\n name: string,\n when: EffectSelector,\n key: string,\n state: StateQuery,\n column: string,\n): Implies {\n return { kind: \"implies\", name, when, key, state, column };\n}\n\n/** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */\nexport function queueAck(queueName: string): EffectSelector {\n return {\n target: `Queue:${queueName}`,\n op: \"ack\",\n kind: \"result\",\n where: { \"result.effective\": true },\n };\n}\n\n/**\n * Declare an external service: requests to `host` are answered from\n * `responses` (every request gets 200 and an empty body when omitted), and\n * `dedupeBy` names the header whose value makes repeated requests\n * idempotent at that service.\n */\nexport function external(\n name: string,\n host: string,\n options: { readonly dedupeBy?: string; readonly responses?: readonly ScriptedResponse[] } = {},\n): ExternalDecl {\n return {\n name,\n host,\n guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},\n ...(options.responses ? { responses: options.responses } : {}),\n };\n}\n\n/**\n * Selects the requests to an external that took effect: a request replayed\n * under a dedupe key the external had already seen is not counted.\n */\nexport function fetchCall(externalName: string, method?: string): EffectSelector {\n return {\n target: `Fetch:${externalName}`,\n ...(method ? { op: method.toUpperCase() } : {}),\n kind: \"result\",\n where: { \"result.effective\": true },\n };\n}\n\nfunction validateWebSocketDrive(drive: WebSocketDrive): readonly string[] {\n const errors: string[] = [];\n if (drive.connections.length === 0) errors.push(\"websocket drive needs at least one connection\");\n const ids = new Set<string>();\n drive.connections.forEach((c, i) => {\n if (!c.path.startsWith(\"/\")) errors.push(`connections[${i}].path must start with \"/\"`);\n if (ids.has(c.id)) errors.push(`duplicate connection id ${JSON.stringify(c.id)}`);\n ids.add(c.id);\n for (const m of c.messages) {\n if (ids.has(m.id)) errors.push(`duplicate message id ${JSON.stringify(m.id)}`);\n ids.add(m.id);\n }\n });\n return errors;\n}\n\nfunction validateHttpDrive(drive: HttpDrive): readonly string[] {\n const errors: string[] = [];\n if (drive.requests.length === 0) errors.push(\"http drive needs at least one request\");\n const ids = new Set<string>();\n drive.requests.forEach((r, i) => {\n if (!r.path.startsWith(\"/\")) errors.push(`requests[${i}].path must start with \"/\"`);\n if (!r.method) errors.push(`requests[${i}].method must not be empty`);\n if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);\n ids.add(r.id);\n if ((r.method === \"GET\" || r.method === \"HEAD\") && r.body !== undefined)\n errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);\n });\n errors.push(...validateCaller(\"http\", drive));\n return errors;\n}\n\n/** The caller's policy, as both drives a caller resends declare it. */\nfunction validateCaller(\n kind: string,\n drive: {\n readonly retries: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n },\n): readonly string[] {\n const errors: string[] = [];\n if (!(Number.isInteger(drive.retries) && drive.retries >= 0))\n errors.push(`${kind} drive retries must be a non-negative integer`);\n (drive.delaysMs ?? []).forEach((d, i) => {\n if (!(Number.isInteger(d) && d >= 0))\n errors.push(`${kind} drive delaysMs[${i}] must be a non-negative integer`);\n });\n if (\n drive.deadlineMs !== undefined &&\n !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)\n )\n errors.push(`${kind} drive deadlineMs must be a positive integer`);\n return errors;\n}\n\nfunction validateCronDrive(drive: CronDrive): readonly string[] {\n const errors: string[] = [];\n try {\n parseCron(drive.cron);\n } catch (err) {\n errors.push(`cron drive: ${(err as Error).message}`);\n }\n if (drive.ticks.length === 0) errors.push(\"cron drive ticks must be a positive integer\");\n const ids = new Set<string>();\n drive.ticks.forEach((t, i) => {\n if (ids.has(t.id)) errors.push(`duplicate tick id ${JSON.stringify(t.id)}`);\n ids.add(t.id);\n const previous = drive.ticks[i - 1];\n if (previous && !(t.at > previous.at))\n errors.push(`ticks[${i}] does not come after ticks[${i - 1}]`);\n });\n if (!(Number.isInteger(drive.retries) && drive.retries >= 0))\n errors.push(\"cron drive retries must be a non-negative integer\");\n return errors;\n}\n\n/** A method name the entrypoint can have: an identifier that is not the constructor. */\nconst methodName = /^[A-Za-z_$][\\w$]*$/;\n\nfunction validateRpcDrive(drive: RpcDrive): readonly string[] {\n const errors: string[] = [];\n if (drive.entrypoint !== undefined && !methodName.test(drive.entrypoint))\n errors.push(\"rpc drive entrypoint must be an exported class name\");\n const ids = new Set<string>();\n drive.calls.forEach((c, i) => {\n if (!methodName.test(c.method) || c.method === \"constructor\")\n errors.push(`calls[${i}].method must be a method name`);\n if (!Array.isArray(c.args)) errors.push(`calls[${i}].args must be an array`);\n if (ids.has(c.id)) errors.push(`duplicate call id ${JSON.stringify(c.id)}`);\n ids.add(c.id);\n });\n errors.push(...validateCaller(\"rpc\", drive));\n return errors;\n}\n\n/**\n * Durable Object setups: an object's or a SQL table's name may not hold\n * \"/\", since the snapshot names a table `<object>/<table>` and a selector\n * must read back to one place.\n */\nfunction validateDurableObjectSetups(setup: readonly PlatformData[]): readonly string[] {\n const errors: string[] = [];\n for (const step of setup) {\n if (step[\"kind\"] !== \"durable_object\") continue;\n const s = step as unknown as DurableObjectSetup;\n for (const name of [...Object.keys(s.objects), ...Object.keys(s.sql ?? {})])\n if (name.includes(\"/\"))\n errors.push(\n `durableObject ${s.binding}: object name ${JSON.stringify(name)} holds \"/\", which the snapshot uses between an object and its table`,\n );\n for (const [name, seed] of Object.entries(s.sql ?? {})) {\n if (typeof seed.schema !== \"string\" || seed.schema.trim() === \"\")\n errors.push(\n `durableObject ${s.binding}: object ${JSON.stringify(name)} has a sql seed without a schema`,\n );\n for (const [table, rows] of Object.entries(seed.rows ?? {})) {\n if (table.includes(\"/\"))\n errors.push(\n `durableObject ${s.binding}: table name ${JSON.stringify(table)} of ${JSON.stringify(name)} holds \"/\"`,\n );\n if (\n !Array.isArray(rows) ||\n rows.some((r) => typeof r !== \"object\" || r === null || Array.isArray(r))\n )\n errors.push(\n `durableObject ${s.binding}: rows of ${JSON.stringify(name)}.${table} must be an array of objects`,\n );\n }\n }\n }\n return errors;\n}\n\n/** Build and validate a scenario spec; throws with every problem listed. */\nexport function defineScenario(input: CloudflareScenarioInput): ScenarioSpec {\n // queue() keeps the ids a QueueDrive already has, so it serves both forms.\n const drive: Drive =\n input.drive.kind === \"queue\" ? queue(input.drive.queue, input.drive.messages) : input.drive;\n const spec: ScenarioSpec = {\n version: 1,\n name: input.name,\n platform: \"cloudflare\",\n worker: input.worker,\n drive,\n setup: input.setup ?? [],\n externals: input.externals ?? [],\n invariants: input.invariants,\n bounds: { ...defaultBounds, ...input.bounds },\n ...(input.specs ? { specs: input.specs } : {}),\n };\n const errors = [\n ...validateScenario(spec),\n ...validateDurableObjectSetups(spec.setup),\n ...validateCalleeSetups(spec.setup),\n ...(drive.kind === \"http\" ? validateHttpDrive(drive) : []),\n ...(drive.kind === \"rpc\" ? validateRpcDrive(drive) : []),\n ...(drive.kind === \"cron\" ? validateCronDrive(drive) : []),\n ...(drive.kind === \"websocket\" ? validateWebSocketDrive(drive) : []),\n ];\n if (errors.length > 0) {\n throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\\n- ${errors.join(\"\\n- \")}`);\n }\n return spec;\n}\n","/**\n * Inbound RPC delivery: one invocation per attempt of a `WorkerEntrypoint`\n * method call the drive's caller makes. The entrypoint is constructed anew\n * for each call, as the runtime does (Cloudflare, Workers RPC: a new\n * instance of the class for every call), and its return value or the error\n * it threw is the response the caller sees.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n type JsonValue,\n type RunHooks,\n type ScenarioSpec,\n toJson,\n} from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport { startCaller } from \"./caller.ts\";\nimport { isPlainData } from \"./durable-objects.ts\";\nimport { constructEntrypoint } from \"./entrypoint.ts\";\nimport { type RpcCallSpec, type RpcDrive, rpcTarget } from \"./scenario.ts\";\n\n/**\n * An error as the caller sees it over RPC: a new error object with the\n * name and message (Cloudflare, RPC error handling), nothing of its class.\n */\nexport function describeError(error: unknown): string {\n if (error instanceof Error) return `${error.name}: ${error.message}`;\n return typeof error === \"string\" ? error : JSON.stringify(toJson(error));\n}\n\n/** One attempt of a call, under the caller's retry policy and deadline. */\nexport async function deliverCall(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: RpcDrive,\n invocation: string,\n cls: unknown,\n env: object,\n): Promise<DeliveryResult> {\n const call = event.data as unknown as RpcCallSpec;\n const target = rpcTarget(drive, call.method);\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n const args: JsonValue = { callId: event.id, method: call.method, args: call.args };\n const caller = startCaller(event, hooks, spec, drive, target, {\n callId: event.id,\n attempts: event.attempt,\n });\n\n const ran = await runInvocation(hooks, inv, () =>\n callMethod(cls, call, executionContext(background), env),\n );\n let status: DeliveryResult[\"status\"] = ran.status;\n let late = caller.isLate();\n let answer: { readonly ok: boolean } | null = null;\n if (ran.status === \"completed\") {\n // Data travels by copy; a stub, a function or a stream would let later calls bypass the run.\n if (!isPlainData(ran.value))\n hooks.unsupported(\n `Rpc ${call.method}: the result is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`,\n );\n const s = { ok: true, value: toJson(ran.value) };\n try {\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed: caller.responseFaults },\n () => s,\n (v) => v,\n );\n answer = s;\n } catch (err) {\n if (err instanceof CrashSignal) status = \"crashed\";\n else if (err instanceof InjectedEffectError) {\n // Answered, but after the caller's deadline: the handler carries on, the caller resends.\n answer = s;\n late = true;\n } else throw err;\n }\n } else if (ran.status === \"errored\") {\n // The exception reaches the caller as a new error with its name and message; the caller saw an answer.\n const s = { ok: false, error: describeError(ran.error) };\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed: [] },\n () => s,\n (v) => v,\n );\n answer = s;\n }\n\n caller.settle(answer !== null && !late && answer.ok, late);\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\n}\n\n/**\n * The class an RPC drive calls: the named export, or the Worker's default\n * export (the class passed as the handler, or `exports.default`). Not\n * necessarily a class: the platform reports what it found instead.\n */\nexport function entrypointClass(\n handler: unknown,\n exports: Readonly<Record<string, unknown>> | undefined,\n entrypoint: string | undefined,\n): unknown {\n if (entrypoint !== undefined) return exports?.[entrypoint];\n return typeof handler === \"function\" ? handler : exports?.[\"default\"];\n}\n\n/**\n * The method RPC exposes under a name: one the class or a superclass defines\n * on its prototype. An instance property, even a function, and Object's own\n * methods are not callable (workerd: \"The RPC receiver does not implement the\n * method\").\n */\nexport function rpcMethod(\n instance: object,\n name: string,\n): ((...a: unknown[]) => unknown) | undefined {\n for (\n let proto = Object.getPrototypeOf(instance) as object | null;\n proto !== null && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto) as object | null\n ) {\n const own = Object.getOwnPropertyDescriptor(proto, name);\n if (!own) continue;\n return typeof own.value === \"function\" && name !== \"constructor\"\n ? (own.value as (...a: unknown[]) => unknown)\n : undefined;\n }\n return undefined;\n}\n\n/**\n * Construct the entrypoint for one call and invoke the method, as the\n * runtime does per call. The arguments are copied, as RPC copies them: a\n * method that mutates one changes neither the scenario nor a later attempt.\n */\nexport function callMethod(cls: unknown, call: RpcCallSpec, ctx: unknown, env: object): unknown {\n const instance = constructEntrypoint(cls, \"WorkerEntrypoint\", ctx, env);\n const method = rpcMethod(instance, call.method);\n if (!method)\n throw new TypeError(`The RPC receiver does not implement the method \"${call.method}\".`);\n return method.apply(instance, structuredClone(call.args) as unknown[]);\n}\n","/**\n * Service bindings with the callee scripted. A Worker reaches a peer through\n * `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on\n * the same thread and retries nothing (Workers, service bindings). The real\n * binding is never called here: the scenario's `service()` setup scripts the\n * replies, and each call is one effect with the faults of a Durable Object\n * stub call, where `crash_before` and `error` mean the call never reached\n * the callee, `ambiguous` that it acted and the answer was lost, and\n * `crash_after` that the caller died after it. The stub itself (callable\n * methods, awaited properties, `fetch`, the pipelining guards) is shared\n * with the callee that runs for real (`callees.ts`).\n */\n\nimport { type EffectPoint, type JsonValue, toJson, writeFaults } from \"@eutaxy/core\";\nimport { findResponse, isRedirect, parseBody, replyOf, toResponse } from \"@eutaxy/engine\";\nimport type { ProxyContext } from \"./d1.ts\";\nimport type { ScriptedReply, ServiceSetup } from \"./scenario.ts\";\n\n/** Marks of the other kinds of binding, which a service binding's duck type must not carry. */\nconst otherKinds = [\"prepare\", \"idFromName\", \"head\", \"createBatch\"];\n\n/**\n * Whether an env value is a service binding (the runtime's `Fetcher`). In\n * workerd it is an RPC stub whose every property read yields a callable, so\n * duck typing alone would take it for any other kind: the runtime's class is\n * checked first, and the duck type (fetch and connect, none of the other\n * kinds' marks) serves test doubles.\n */\nexport function isServiceBinding(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n const fetcher = (globalThis as { Fetcher?: unknown }).Fetcher;\n if (typeof fetcher === \"function\" && value instanceof fetcher) return true;\n const ctor = Object.getPrototypeOf(value)?.constructor as { name?: string } | undefined;\n if (ctor?.name === \"Fetcher\") return true;\n const v = value as Record<string, unknown>;\n return (\n typeof v[\"fetch\"] === \"function\" &&\n typeof v[\"connect\"] === \"function\" &&\n otherKinds.every((k) => typeof v[k] !== \"function\")\n );\n}\n\n/** The built-in error classes RPC carries across as themselves (workerd keeps the type). */\nconst builtInErrors: { readonly [name: string]: new (message: string) => Error } = {\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n};\n\n/**\n * The error the caller sees for a `throws` reply, `\"<Name>: <message>\"`: a\n * built-in error class is that class, so `instanceof` holds as it does over\n * RPC; any other name is an `Error` carrying the name.\n */\nexport function scriptedError(spec: string): Error {\n const at = spec.indexOf(\": \");\n if (at < 0) return new Error(spec);\n const name = spec.slice(0, at);\n const message = spec.slice(at + 2);\n const builtIn = builtInErrors[name];\n if (builtIn) return new builtIn(message);\n const error = new Error(message);\n error.name = name;\n return error;\n}\n\n/** A request through the binding as the effect log records it. */\nexport interface RequestRecord {\n readonly url: string;\n readonly method: string;\n readonly headers: Record<string, string>;\n readonly body: JsonValue;\n}\n\n/** Read a request for the log without consuming it: the callee may still read the body. */\nexport async function recordRequest(request: Request): Promise<RequestRecord> {\n const method = request.method.toUpperCase();\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const body = parseBody(await request.clone().text());\n return { url: request.url, method, headers, body };\n}\n\n/** What answers the calls a stub receives; each answer performs its own effect. */\nexport interface ServiceAnswers {\n /** `stub.method(...args)`. */\n call(method: string, args: readonly unknown[]): Promise<unknown>;\n /** `await stub.property` (an RPC getter). */\n property(method: string): Promise<unknown>;\n /** `stub.fetch(...)`. */\n fetch(request: Request): Promise<Response>;\n}\n\n/**\n * The stub a Worker sees under a service binding's name: methods callable\n * and awaitable, `fetch`, and the guards against what is not modelled\n * (promise pipelining, `connect()`), with the answers supplied.\n */\nexport function serviceStub(binding: string, ctx: ProxyContext, answers: ServiceAnswers): object {\n const unsupported = (what: string): never => {\n const reason = `service binding ${binding}: ${what}`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n\n /**\n * The promise a call returns. On the real stub it is an RPC promise that\n * pipelines property reads (`stub.charge().id`); this one is not, so a read\n * on it makes the run UNSUPPORTED instead of yielding undefined.\n */\n const pipelineGuard = <T>(promise: Promise<T>, method: string): Promise<T> =>\n new Proxy(promise, {\n get(target, prop) {\n if (typeof prop === \"symbol\" || prop === \"then\" || prop === \"catch\" || prop === \"finally\") {\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n ctx.hooks.unsupported(\n `service binding ${binding}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`,\n );\n return undefined;\n },\n });\n\n /** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */\n const call = (method: string) => {\n const invoke = (...args: unknown[]) => pipelineGuard(answers.call(method, args), method);\n const awaitable = (\n onFulfilled?: (v: unknown) => unknown,\n onRejected?: (e: unknown) => unknown,\n ) => answers.property(method).then(onFulfilled, onRejected);\n // Callable and awaitable; any other property read is pipelining, which is not modelled.\n return new Proxy(invoke, {\n get(fn, key) {\n if (key === \"then\") return awaitable;\n if (typeof key === \"symbol\") return Reflect.get(fn, key);\n ctx.hooks.unsupported(\n `service binding ${binding}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`,\n );\n return undefined;\n },\n });\n };\n\n // Async, so a request that cannot be built (an invalid URL) rejects as fetch() does, never throws.\n const fetchThrough = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> =>\n answers.fetch(new Request(input, init));\n\n return new Proxy(\n {},\n {\n get(_stub, prop) {\n // The stub is not a promise.\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n if (prop === \"fetch\") return fetchThrough;\n if (prop === \"connect\")\n return () => unsupported(\"connect() (a raw TCP socket) is not modelled\");\n return call(prop);\n },\n },\n );\n}\n\n/** The scripted stub a Worker sees under a service binding's name. */\nexport function proxyService(binding: string, ctx: ProxyContext, script: ServiceSetup): object {\n const target = `Service:${binding}`;\n const point = (op: string, args: JsonValue): EffectPoint => ({\n invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed: writeFaults,\n });\n const unsupported = (what: string): never => {\n const reason = `service binding ${binding}: ${what}`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */\n const replyTo = (method: string): ScriptedReply => {\n if (script.methods === undefined) return { returns: null };\n if (!Object.hasOwn(script.methods, method))\n return unsupported(\n `no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`,\n );\n return script.methods[method] as ScriptedReply;\n };\n const answer = (method: string): unknown => {\n const reply = replyTo(method);\n if (\"throws\" in reply) throw scriptedError(reply.throws);\n // Copied, as RPC copies values: the Worker cannot change the script.\n return structuredClone(reply.returns);\n };\n const summarize = (value: unknown): JsonValue => ({ value: toJson(value) });\n\n return serviceStub(binding, ctx, {\n call: (method, args) =>\n ctx.hooks.effect(\n point(method, { args: args.map((a) => toJson(a)) }),\n async () => answer(method),\n summarize,\n ),\n property: (method) =>\n ctx.hooks.effect(point(method, { property: true }), async () => answer(method), summarize),\n async fetch(request) {\n const url = new URL(request.url);\n const { method, headers, body } = await recordRequest(request);\n const reply = await ctx.hooks.effect(\n point(method, { url: request.url, method, headers, body }),\n async () => {\n // The matcher is the externals'; a service binding takes any host, so none is matched.\n const found = findResponse(\n {\n name: binding,\n host: url.host,\n guarantees: {},\n ...(script.fetch === undefined ? {} : { responses: script.fetch }),\n },\n method,\n url.pathname,\n );\n if (found === undefined)\n return unsupported(\n `no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`,\n );\n const reply = replyOf(found);\n // workerd follows a redirect from the callee as fetch does; the script holds only the first reply.\n if (isRedirect(reply.status) && request.redirect !== \"manual\")\n return unsupported(\n `the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: \"manual\"`,\n );\n return reply;\n },\n (r) => ({ status: r.status }),\n );\n return toResponse(reply);\n },\n });\n}\n","/**\n * Service bindings with the callee real. A scenario names the Worker behind a\n * binding (`callee(binding, { entry, config })`), and the test gives the\n * platform its module and the name from its wrangler config; the callee's\n * code then runs in the same simulation as the caller's, in the same\n * isolate, as Cloudflare runs both Workers on one thread (Workers, service\n * bindings). Each RPC method call or `fetch()` through the binding is one\n * effect, `Service:<binding>`, with the faults of a call in the network\n * (`crash_before`: it never reached the callee; `ambiguous`: the callee\n * acted and the answer was lost; `crash_after`: the caller died after it);\n * `error` is not among them, since what the callee throws is real. The\n * effect hosts the callee's invocation (`<caller invocation>/<binding>.<method>`,\n * `#<n>` for the n-th call of that method from the same caller invocation):\n * the entrypoint is constructed anew with a fresh `ExecutionContext` and the\n * callee's `env`, a view of the scenario's env under the callee's own names\n * (`DB` for `orders/DB`), so its code runs unchanged while its effects are\n * recorded under its own invocation, interleave as turns and take faults by\n * their position within it. What the callee throws reaches the caller as a\n * new error with its name, message and serializable own properties, a\n * built-in class as itself (Workers RPC, error handling); a fault that\n * crashes the callee ends its invocation and the caller sees an `Error`\n * thrown from the call. The callee's `waitUntil` work finishes before its\n * answer crosses: one of the orders the runtime allows.\n */\n\nimport { type FaultKind, type JsonValue, toJson } from \"@eutaxy/core\";\nimport { hostInvocation, isRedirect, type Outcome, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\nimport { isPlainData } from \"./durable-objects.ts\";\nimport { constructEntrypoint } from \"./entrypoint.ts\";\nimport { describeError, entrypointClass, rpcMethod } from \"./rpc.ts\";\nimport type { CalleeSetup } from \"./scenario.ts\";\nimport { recordRequest, scriptedError, serviceStub } from \"./services.ts\";\n\n/**\n * The callee's module as the test gives it: the Worker's name from its\n * wrangler config, which qualifies its bindings, its exports, and what the\n * caller's service binding carries in its own config: the `entrypoint` the\n * binding reaches (the scenario's `callee()` may name one too, and wins)\n * and the `props` the callee reads from `ctx.props`.\n */\nexport interface CalleeModule {\n readonly name: string;\n readonly exports: Readonly<Record<string, unknown>>;\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, JsonValue>>;\n}\n\n/** The faults a call to a real callee admits; `error` is the callee's own to throw. */\nexport const callFaults: readonly FaultKind[] = [\"crash_before\", \"ambiguous\", \"crash_after\"];\n\n/** What the platform keeps per run about its callees; cleared before each run. */\nexport class CalleeState {\n /** Calls so far per caller invocation, binding and method, to name each hosted invocation. */\n readonly counts = new Map<string, number>();\n clear(): void {\n this.counts.clear();\n }\n}\n\n/**\n * The callee's `env`: the scenario's env seen under the callee's own names,\n * each mapped onto `<name>/<key>`. Over the platform's proxied env the\n * entries are the proxies, so the callee's effects are recorded under their\n * qualified targets, and an alias (`<name>/STOCK` for the caller's `STOCK`)\n * is already resolved; over workerd's raw env (a callee's Durable Object,\n * which the runtime constructs with the main Worker's env) the aliases are\n * given here, so the shared binding is there under the callee's name too.\n */\nexport function calleeEnv(\n name: string,\n env: object,\n aliases: Readonly<Record<string, string>> = {},\n): object {\n const prefix = `${name}/`;\n const source = env as Record<string, unknown>;\n /** The key of `env` a property of the view reads: the qualified name, or the binding it is an alias of. */\n const keyOf = (prop: string | symbol): string | undefined => {\n if (typeof prop !== \"string\") return undefined;\n const qualified = `${prefix}${prop}`;\n return qualified in source ? qualified : (aliases[qualified] ?? qualified);\n };\n const aliasKeys = Object.keys(aliases).filter(\n (a) => a.startsWith(prefix) && (aliases[a] ?? \"\") in source,\n );\n return new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_t, prop) {\n const key = keyOf(prop);\n return key === undefined ? undefined : source[key];\n },\n has(_t, prop) {\n const key = keyOf(prop);\n return key !== undefined && key in source;\n },\n ownKeys: () => [\n ...new Set(\n [...Reflect.ownKeys(source).filter((k): k is string => typeof k === \"string\"), ...aliasKeys]\n .filter((k) => k.startsWith(prefix))\n .map((k) => k.slice(prefix.length)),\n ),\n ],\n getOwnPropertyDescriptor(_t, prop) {\n const key = keyOf(prop);\n if (key === undefined || !(key in source)) return undefined;\n return { value: source[key], enumerable: true, configurable: true, writable: false };\n },\n });\n}\n\n/**\n * The error the caller sees for what the callee threw: a new error with the\n * name and message, a built-in class as itself, and the serializable own\n * properties the thrown error carried (Workers RPC, error handling, enhanced\n * error serialization). Nothing of the original's identity or stack.\n */\nexport function crossingError(error: unknown): Error {\n const crossed = scriptedError(describeError(error));\n if (error instanceof Error) {\n for (const key of Object.keys(error)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n try {\n Object.defineProperty(crossed, key, {\n value: structuredClone((error as unknown as Record<string, unknown>)[key]),\n enumerable: true,\n configurable: true,\n writable: true,\n });\n } catch {\n // Not serializable: it does not cross.\n }\n }\n }\n return crossed;\n}\n\n/**\n * The fetch handler the binding reaches: the named entrypoint's method when\n * the setup names one, else the default export's (a handler object's `fetch`,\n * or an entrypoint class's method).\n */\nfunction fetchHandlerOf(\n exports: Readonly<Record<string, unknown>>,\n entrypoint: string | undefined,\n ctx: ExecutionContext,\n env: object,\n): ((request: Request) => unknown) | undefined {\n const def = entrypoint === undefined ? exports[\"default\"] : exports[entrypoint];\n if (typeof def === \"function\") {\n const instance = constructEntrypoint(def, \"WorkerEntrypoint\", ctx, env) as {\n fetch?: (request: Request) => unknown;\n };\n return typeof instance.fetch === \"function\" ? instance.fetch.bind(instance) : undefined;\n }\n if (typeof def === \"object\" && def !== null) {\n const handler = def as {\n fetch?: (request: Request, env: object, ctx: ExecutionContext) => unknown;\n };\n return typeof handler.fetch === \"function\"\n ? (request) => handler.fetch?.call(handler, request, env, ctx)\n : undefined;\n }\n return undefined;\n}\n\n/**\n * The getter RPC exposes under a name: one the class or a superclass defines\n * on its prototype. An instance field is not reachable over RPC (workerd:\n * \"The RPC receiver does not implement the method\").\n */\nfunction rpcGetter(instance: object, name: string): (() => unknown) | undefined {\n for (\n let proto = Object.getPrototypeOf(instance) as object | null;\n proto !== null && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto) as object | null\n ) {\n const own = Object.getOwnPropertyDescriptor(proto, name);\n if (!own) continue;\n return typeof own.get === \"function\" ? own.get : undefined;\n }\n return undefined;\n}\n\n/** The stub a Worker sees under a service binding whose callee runs for real. */\nexport function proxyCallee(\n binding: string,\n ctx: ProxyContext,\n setup: CalleeSetup,\n module: CalleeModule,\n env: object,\n state: CalleeState,\n): object {\n const target = `Service:${binding}`;\n const view = calleeEnv(module.name, env);\n const entrypointName = setup.entrypoint ?? module.entrypoint;\n const props = module.props ?? {};\n const unsupported = (what: string): never => {\n const reason = `callee ${binding}: ${what}`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n const point = (op: string, args: JsonValue) => ({\n invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed: callFaults,\n });\n /** The hosted invocation's id: the n-th call of a method from one caller invocation is `#n`. */\n const invocationId = (method: string): string => {\n const key = `${ctx.currentInvocation()}/${binding}.${method}`;\n const n = (state.counts.get(key) ?? 0) + 1;\n state.counts.set(key, n);\n return n === 1 ? key : `${key}#${n}`;\n };\n\n /** The callee's code as an invocation of its own inside the call: the handler, then its background work. */\n const invoke = <T>(\n method: string,\n work: (executionContext: ExecutionContext) => T | Promise<T>,\n ): Promise<Outcome<T>> => {\n const hooks = ctx.hooks;\n const id = invocationId(method);\n return hostInvocation(hooks, id, async (inv) => {\n const background: Promise<unknown>[] = [];\n const ran = await runInvocation(hooks, inv, () =>\n work(executionContext(background, undefined, props)),\n );\n // A cut-off here crashes the callee after it answered: the answer stands, work not started is lost.\n if (ran.status !== \"crashed\") await drainBackground(hooks, inv, id, target, background);\n return ran;\n });\n };\n\n /** What the caller gets out of the callee's outcome: the value, the error as RPC carries it, or an error for a crash. */\n const answer = <T>(outcome: Outcome<T>, method: string): T => {\n if (outcome.status === \"completed\") return outcome.value;\n if (outcome.status === \"errored\") throw crossingError(outcome.error);\n throw new Error(\n `the Worker behind service binding ${binding} crashed while handling ${method}`,\n );\n };\n\n /**\n * Arguments travel by copy, as plain data: a function, a stub or a stream is\n * a capability the model lacks, and a class instance is what RPC refuses\n * (structuredClone would silently make a plain object of it).\n */\n const copied = (method: string, args: readonly unknown[]): unknown[] => {\n if (!args.every((a) => isPlainData(a)))\n return unsupported(\n `the arguments of ${method} are not plain data (a stub, a function, a stream or a class instance); RPC carries plain data only`,\n );\n try {\n return structuredClone([...args]);\n } catch {\n return unsupported(`the arguments of ${method} cannot be copied as RPC copies them`);\n }\n };\n\n /** A result passed back to the caller, by copy; one that is not plain data cannot be followed. */\n const plain = (method: string, value: unknown): unknown => {\n if (!isPlainData(value))\n unsupported(\n `${method} returned something that is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`,\n );\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n };\n\n const entrypoint = (): unknown => {\n const cls = entrypointClass(undefined, module.exports, entrypointName);\n if (typeof cls !== \"function\")\n unsupported(\n `${entrypointName === undefined ? \"the default export\" : `export ${entrypointName}`} of ${module.name} is not a WorkerEntrypoint class`,\n );\n return cls;\n };\n\n const summarize = (value: unknown): JsonValue => ({ value: toJson(value) });\n\n return serviceStub(binding, ctx, {\n call: (method, args) => {\n // Copied now, as RPC copies at the call: what the caller does to its arguments after calling\n // (while the call waits for its turn) does not reach the callee. A refused argument rejects the\n // call's promise, as the real stub's does.\n let copy: unknown[];\n try {\n copy = copied(method, args);\n } catch (err) {\n return Promise.reject(err);\n }\n return ctx.hooks.effect(\n point(method, { args: args.map((a) => toJson(a)) }),\n async () => {\n const cls = entrypoint();\n const outcome = await invoke(method, (executionContext) => {\n const instance = constructEntrypoint(cls, \"WorkerEntrypoint\", executionContext, view);\n const fn = rpcMethod(instance, method);\n if (!fn)\n throw new TypeError(`The RPC receiver does not implement the method \"${method}\".`);\n return fn.apply(instance, copy);\n });\n return plain(method, answer(outcome, method));\n },\n summarize,\n );\n },\n property: (name) =>\n ctx.hooks.effect(\n point(name, { property: true }),\n async () => {\n const cls = entrypoint();\n const outcome = await invoke(name, (executionContext) => {\n const instance = constructEntrypoint(cls, \"WorkerEntrypoint\", executionContext, view);\n const getter = rpcGetter(instance, name);\n if (!getter)\n throw new TypeError(`The RPC receiver does not implement the method \"${name}\".`);\n return getter.call(instance);\n });\n return plain(name, answer(outcome, name));\n },\n summarize,\n ),\n async fetch(request) {\n const { method, headers, body } = await recordRequest(request);\n return ctx.hooks.effect(\n point(method, { url: request.url, method, headers, body }),\n async () => {\n const outcome = await invoke(\"fetch\", (executionContext) => {\n const handler = fetchHandlerOf(module.exports, entrypointName, executionContext, view);\n if (!handler)\n return unsupported(\n `${entrypointName === undefined ? module.name : `export ${entrypointName} of ${module.name}`} has no fetch handler`,\n );\n return handler(request);\n });\n const response = answer(outcome, \"fetch\");\n if (!(response instanceof Response))\n return unsupported(\n `${module.name}'s fetch handler returned something that is not a Response`,\n );\n // workerd follows a redirect from the callee as fetch does; only the first answer ran here.\n if (isRedirect(response.status) && request.redirect !== \"manual\")\n return unsupported(\n `${module.name} answered ${method} ${new URL(request.url).pathname} with a ${response.status} redirect, which the runtime would follow; fetch with redirect: \"manual\"`,\n );\n return response;\n },\n (r) => ({ status: r.status }),\n );\n },\n });\n}\n","import {\n describeVerdict,\n type Platform,\n type ScenarioSpec,\n type ScenarioVerdict,\n} from \"@eutaxy/core\";\nimport { type ExploreOptions, explore } from \"@eutaxy/engine\";\n\n/** Explore a scenario on a platform and return its verdict. */\nexport function check(\n spec: ScenarioSpec,\n platform: Platform,\n options: ExploreOptions = { seed: spec.name },\n): Promise<ScenarioVerdict> {\n return explore(spec, platform, options);\n}\n\n/** For use from a test: passes only when the scenario is BOUNDED. */\nexport async function expectHolds(\n spec: ScenarioSpec,\n platform: Platform,\n options?: ExploreOptions,\n): Promise<void> {\n const verdict = await check(spec, platform, options);\n if (verdict.kind !== \"BOUNDED\") throw new Error(describeVerdict(verdict));\n}\n","/**\n * The D1 binding proxy. Every statement execution is an effect point: the\n * engine decides the fault, the real Miniflare-backed D1 performs the query,\n * and the log records call, result and fault in the documented shape.\n */\n\nimport {\n canonicalJson,\n type EffectPoint,\n type FaultKind,\n type JsonValue,\n type RunHooks,\n readFaults,\n toJson,\n writeFaults,\n} from \"@eutaxy/core\";\n\n/** Whether a binding is a D1 database (what the proxies and the differential wrap). */\nexport function isD1(value: unknown): value is D1Database {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { prepare?: unknown }).prepare === \"function\" &&\n typeof (value as { batch?: unknown }).batch === \"function\"\n );\n}\n\nexport interface ProxyContext {\n readonly hooks: RunHooks;\n /** The invocation currently running; only one runs at a time, even with several in flight. */\n readonly currentInvocation: () => string;\n /** Told when a Durable Object stub's fetch answered 101: the object a WebSocket connection reached, the invocation whose call it was, and the client end. */\n readonly onUpgrade?: (info: {\n binding: string;\n id: string;\n object: string;\n invocation: string;\n client: WebSocket;\n }) => void;\n}\n\nfunction point(\n ctx: ProxyContext,\n target: string,\n op: string,\n args: JsonValue,\n allowed: readonly FaultKind[],\n): EffectPoint {\n return { invocation: ctx.currentInvocation(), target, op, args, allowed };\n}\n\nfunction metaOf(result: D1Result<unknown>): JsonValue {\n return { changes: result.meta.changes ?? 0, lastRowId: result.meta.last_row_id ?? null };\n}\n\nclass StatementProxy {\n private readonly real: D1PreparedStatement;\n private readonly target: string;\n private readonly ctx: ProxyContext;\n readonly sql: string;\n readonly params: readonly unknown[];\n\n constructor(\n real: D1PreparedStatement,\n target: string,\n ctx: ProxyContext,\n sql: string,\n params: readonly unknown[],\n ) {\n this.real = real;\n this.target = target;\n this.ctx = ctx;\n this.sql = sql;\n this.params = params;\n }\n\n /** The real statement, for `batch()`. */\n get statement(): D1PreparedStatement {\n return this.real;\n }\n\n private args(): JsonValue {\n return { sql: this.sql, params: toJson(this.params) };\n }\n\n bind(...values: unknown[]): StatementProxy {\n return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);\n }\n\n run<T = Record<string, unknown>>(): Promise<D1Result<T>> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"run\", this.args(), writeFaults),\n () => this.real.run<T>(),\n (r) => metaOf(r),\n );\n }\n\n all<T = Record<string, unknown>>(): Promise<D1Result<T>> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"all\", this.args(), readFaults),\n () => this.real.all<T>(),\n (r) => ({ rows: r.results.length, changes: r.meta.changes ?? 0 }),\n );\n }\n\n first<T = unknown>(colName?: string): Promise<T | null> {\n return this.ctx.hooks.effect(\n point(\n this.ctx,\n this.target,\n \"first\",\n { ...(this.args() as object), column: colName ?? null } as JsonValue,\n readFaults,\n ),\n () => (colName === undefined ? this.real.first<T>() : this.real.first<T>(colName)),\n (r) => ({ row: toJson(r) }),\n );\n }\n\n raw<T = unknown[]>(options?: { columnNames?: boolean }): Promise<T[]> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"raw\", this.args(), readFaults),\n () =>\n (options\n ? this.real.raw<T>(options as { columnNames: true })\n : this.real.raw<T>()) as Promise<T[]>,\n (r) => ({ rows: r.length }),\n );\n }\n}\n\n/** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */\nexport function proxyD1(real: D1Database, binding: string, ctx: ProxyContext): D1Database {\n const target = `D1:${binding}`;\n const modelled = {\n prepare(sql: string): StatementProxy {\n return new StatementProxy(real.prepare(sql), target, ctx, sql, []);\n },\n batch<T = Record<string, unknown>>(\n statements: readonly (StatementProxy | D1PreparedStatement)[],\n ): Promise<D1Result<T>[]> {\n const unwrapped = statements.map((s) => (s instanceof StatementProxy ? s.statement : s));\n const args = {\n statements: statements.map((s) =>\n s instanceof StatementProxy\n ? { sql: s.sql, params: toJson(s.params) }\n : \"<unproxied statement>\",\n ),\n };\n return ctx.hooks.effect(\n point(ctx, target, \"batch\", args, writeFaults),\n () => real.batch<T>(unwrapped as D1PreparedStatement[]),\n (rs) => ({\n changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),\n statements: rs.length,\n }),\n );\n },\n exec(sql: string): Promise<D1ExecResult> {\n return ctx.hooks.effect(\n point(ctx, target, \"exec\", { sql }, writeFaults),\n () => real.exec(sql),\n (r) => ({ count: r.count, duration: 0 }),\n );\n },\n };\n return new Proxy(real, {\n get(obj, prop, receiver) {\n if (prop in modelled) return modelled[prop as keyof typeof modelled];\n const value = Reflect.get(obj, prop, receiver) as unknown;\n if (typeof value === \"function\") {\n ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);\n return (value as (...a: unknown[]) => unknown).bind(obj);\n }\n return value;\n },\n }) as D1Database;\n}\n\n/**\n * Statements in a schema file. Splits on semicolons outside string literals,\n * quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE\n * expressions) whole by tracking BEGIN/CASE ... END nesting.\n */\nexport function splitSql(sql: string): readonly string[] {\n const out: string[] = [];\n let cur = \"\";\n let depth = 0;\n let i = 0;\n const isWordChar = (c: string | undefined): boolean => c !== undefined && /[A-Za-z0-9_]/.test(c);\n while (i < sql.length) {\n const c = sql[i] as string;\n const next = sql[i + 1];\n if (c === \"-\" && next === \"-\") {\n while (i < sql.length && sql[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"/\" && next === \"*\") {\n const end = sql.indexOf(\"*/\", i + 2);\n i = end === -1 ? sql.length : end + 2;\n continue;\n }\n if (c === \"'\" || c === '\"' || c === \"`\" || c === \"[\") {\n const close = c === \"[\" ? \"]\" : c;\n let j = i + 1;\n for (;;) {\n const k = sql.indexOf(close, j);\n if (k === -1) {\n j = sql.length;\n break;\n }\n if (close !== \"]\" && sql[k + 1] === close) {\n j = k + 2; // a doubled quote inside the literal\n continue;\n }\n j = k + 1;\n break;\n }\n cur += sql.slice(i, j);\n i = j;\n continue;\n }\n if (isWordChar(c) && !isWordChar(sql[i - 1])) {\n let j = i;\n while (isWordChar(sql[j])) j++;\n const word = sql.slice(i, j);\n const upper = word.toUpperCase();\n if (upper === \"BEGIN\" || upper === \"CASE\") depth++;\n else if (upper === \"END\" && depth > 0) depth--;\n cur += word;\n i = j;\n continue;\n }\n if (c === \";\" && depth === 0) {\n const statement = cur.trim();\n if (statement.length > 0) out.push(statement);\n cur = \"\";\n i++;\n continue;\n }\n cur += c;\n i++;\n }\n const last = cur.trim();\n if (last.length > 0) out.push(last);\n return out;\n}\n\n/** Drop every user table and re-apply the schema, using the real binding (not an effect). */\nexport async function resetD1(real: D1Database, schema: string): Promise<void> {\n const tables = await real\n .prepare(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\'\",\n )\n .all<{ name: string }>();\n for (const { name } of tables.results) {\n await real.prepare(`DROP TABLE IF EXISTS \"${name.replace(/\"/g, '\"\"')}\"`).run();\n }\n for (const statement of splitSql(schema)) {\n await real.prepare(statement).run();\n }\n}\n\n/** Every user table's rows, sorted canonically, read through the real binding (not an effect). */\nexport async function snapshotD1(\n real: D1Database,\n): Promise<{ readonly [table: string]: readonly JsonValue[] }> {\n const tables = await real\n .prepare(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\' ORDER BY name\",\n )\n .all<{ name: string }>();\n const out: Record<string, JsonValue[]> = {};\n for (const { name } of tables.results) {\n const rows = await real\n .prepare(`SELECT * FROM \"${name.replace(/\"/g, '\"\"')}\"`)\n .all<Record<string, unknown>>();\n out[name] = rows.results\n .map((r) => toJson(r))\n .map((j) => [canonicalJson(j), j] as const)\n .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))\n .map(([, j]) => j);\n }\n return out;\n}\n","/**\n * The R2 binding proxy. Every `put`, `delete`, `get`, `head` and `list` is\n * an effect point against the real Miniflare-backed bucket. A body is read\n * inside its `get`'s effect and handed back in an object with the same\n * fields and body methods: reading it later would be I/O the run cannot\n * see. An object's random `version` and wall-clock `uploaded` are replaced\n * by stand-ins (see `VersionBook`), so traces stay byte-identical.\n */\n\nimport {\n type EffectPoint,\n type FaultKind,\n type JsonValue,\n readFaults,\n toJson,\n writeFaults,\n} from \"@eutaxy/core\";\nimport type { ProxyContext } from \"./d1.ts\";\n\n/** Whether a binding is an R2 bucket (Miniflare's `R2Bucket`). */\nexport function isR2(value: unknown): value is R2Bucket {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return [\"head\", \"get\", \"put\", \"delete\", \"list\", \"createMultipartUpload\"].every(\n (m) => typeof v[m] === \"function\",\n );\n}\n\n/**\n * Stand-ins for the version and upload time of each object version the run\n * sees, in the order it first sees them: versions count up, and the time is\n * the virtual time it was first seen.\n */\nexport class VersionBook {\n private readonly seen = new Map<string, { version: string; uploaded: Date }>();\n\n clear(): void {\n this.seen.clear();\n }\n\n standIn(realVersion: string, at: number): { version: string; uploaded: Date } {\n let s = this.seen.get(realVersion);\n if (!s) {\n s = { version: (this.seen.size + 1).toString(16).padStart(32, \"0\"), uploaded: new Date(at) };\n this.seen.set(realVersion, s);\n }\n return { version: s.version, uploaded: new Date(s.uploaded.getTime()) };\n }\n}\n\n/** An object's metadata, with stand-ins for its version and upload time. */\nfunction metadata(real: R2Object, book: VersionBook, at: number): R2Object {\n const { version, uploaded } = book.standIn(real.version, at);\n return {\n key: real.key,\n version,\n size: real.size,\n etag: real.etag,\n httpEtag: real.httpEtag,\n uploaded,\n httpMetadata: real.httpMetadata,\n customMetadata: real.customMetadata,\n range: real.range,\n checksums: real.checksums,\n storageClass: real.storageClass,\n ssecKeyMd5: real.ssecKeyMd5,\n writeHttpMetadata: (headers: Headers) => real.writeHttpMetadata(headers),\n } as R2Object;\n}\n\n/**\n * The bytes behind each body stream the proxy hands out. The stream itself\n * has no known length, which the runtime's put requires, so a put given one\n * (copying an object) is given its bytes instead.\n */\nconst buffered = new WeakMap<ReadableStream, () => Uint8Array>();\n\n/**\n * An object with its body, already read: the stream and the body methods\n * share one consumption, as a real body's do. A method fails once the\n * stream is read, cancelled or locked by a reader; the stream ends empty\n * once a method has read the body.\n */\nfunction withBody(meta: R2Object, bytes: Uint8Array): R2ObjectBody {\n let used = false;\n let stream: ReadableStream | undefined;\n const take = (): Uint8Array => {\n if (used || stream?.locked) throw new TypeError(\"Body has already been used\");\n used = true;\n return bytes.slice();\n };\n // Defined, not assigned: Object.assign would call the getters and use the body up.\n return Object.defineProperties(meta, {\n body: {\n enumerable: true,\n get: () => {\n // Pulled only when read, so looking at the body does not use it.\n stream ??= new ReadableStream(\n {\n pull(controller) {\n if (!used) controller.enqueue(bytes.slice());\n used = true;\n controller.close();\n },\n cancel() {\n used = true;\n },\n },\n { highWaterMark: 0 },\n );\n buffered.set(stream, take);\n return stream;\n },\n },\n bodyUsed: { enumerable: true, get: () => used },\n arrayBuffer: { value: async () => take().buffer as ArrayBuffer },\n bytes: { value: async () => take() },\n text: { value: async () => new TextDecoder().decode(take()) },\n json: { value: async () => JSON.parse(new TextDecoder().decode(take())) as unknown },\n blob: { value: async () => new Blob([take()]) },\n }) as unknown as R2ObjectBody;\n}\n\n/** Conditions as the trace keeps them: a `Headers` object by its entries. */\nfunction conditions(onlyIf: unknown): { onlyIf?: unknown } {\n if (onlyIf === undefined) return {};\n return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };\n}\n\n/** What the trace keeps of a get's options: the conditions and range, never an encryption key. */\nfunction getArgs(key: string, options: R2GetOptions | undefined): JsonValue {\n return toJson({\n key,\n ...conditions(options?.onlyIf),\n ...(options?.range === undefined ? {} : { range: options.range }),\n });\n}\n\n/** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */\nfunction putArgs(options: R2PutOptions | undefined): JsonValue {\n if (!options) return {};\n return toJson({\n ...conditions(options.onlyIf),\n ...(options.customMetadata === undefined ? {} : { customMetadata: options.customMetadata }),\n ...(options.httpMetadata === undefined ? {} : { httpMetadata: options.httpMetadata }),\n });\n}\n\nexport function proxyR2(\n real: R2Bucket,\n binding: string,\n ctx: ProxyContext,\n book: VersionBook,\n): R2Bucket {\n const target = `R2:${binding}`;\n const point = (op: string, args: JsonValue, allowed: readonly FaultKind[]): EffectPoint => ({\n invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed,\n });\n const notModelled = (what: string): never => {\n const reason = `R2 ${binding}: ${what} is not modelled`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */\n const checkConditions = (onlyIf: unknown): void => {\n const datedHeaders = [\"if-modified-since\", \"if-unmodified-since\"];\n const dated =\n onlyIf instanceof Headers\n ? datedHeaders.some((h) => onlyIf.has(h))\n : typeof onlyIf === \"object\" &&\n onlyIf !== null &&\n (\"uploadedBefore\" in onlyIf || \"uploadedAfter\" in onlyIf);\n if (dated)\n ctx.hooks.unsupported(`R2 ${binding}: conditions on the upload time are not modelled`);\n };\n const described = (o: R2Object | null) =>\n o === null ? { found: false } : { found: true, key: o.key, size: o.size, etag: o.etag };\n return {\n put: (key: string, value: unknown, options?: R2PutOptions) =>\n ctx.hooks.effect(\n point(\"put\", { key, ...(putArgs(options) as object) }, writeFaults),\n async () => {\n checkConditions(options?.onlyIf);\n const read = value instanceof ReadableStream ? buffered.get(value) : undefined;\n const stored = await real.put(key, (read ? read() : value) as never, options);\n return stored === null ? null : metadata(stored, book, Date.now());\n },\n (o) => (o === null ? { stored: false } : { stored: true, size: o.size, etag: o.etag }),\n ),\n delete: (keys: string | string[]) =>\n ctx.hooks.effect(\n point(\"delete\", { keys: typeof keys === \"string\" ? [keys] : [...keys] }, writeFaults),\n () => real.delete(keys),\n () => null,\n ),\n get: (key: string, options?: R2GetOptions) =>\n ctx.hooks.effect(\n point(\"get\", getArgs(key, options), readFaults),\n async () => {\n checkConditions(options?.onlyIf);\n const o = await real.get(key, options);\n if (o === null) return null;\n const meta = metadata(o, book, Date.now());\n // A failed precondition answers the metadata without a body.\n if (!(\"body\" in o)) return meta;\n return withBody(meta, new Uint8Array(await (o as R2ObjectBody).arrayBuffer()));\n },\n (o) => ({ ...described(o), ...(o !== null ? { body: \"body\" in o } : {}) }),\n ),\n head: (key: string) =>\n ctx.hooks.effect(\n point(\"head\", { key }, readFaults),\n async () => {\n const o = await real.head(key);\n return o === null ? null : metadata(o, book, Date.now());\n },\n described,\n ),\n list: (options?: R2ListOptions) =>\n ctx.hooks.effect(\n point(\"list\", toJson(options ?? {}), readFaults),\n async () => {\n const listed = await real.list(options);\n const at = Date.now();\n return { ...listed, objects: listed.objects.map((o) => metadata(o, book, at)) };\n },\n (l) => ({\n keys: l.objects.map((o) => o.key),\n truncated: l.truncated,\n delimitedPrefixes: l.delimitedPrefixes,\n }),\n ),\n createMultipartUpload: () => notModelled(\"createMultipartUpload()\"),\n resumeMultipartUpload: () => notModelled(\"resumeMultipartUpload()\"),\n } as unknown as R2Bucket;\n}\n\n/** An object a setup seeds: its text, or its text with metadata. */\nexport type R2Seed =\n | string\n | {\n readonly value: string;\n readonly customMetadata?: Readonly<Record<string, string>>;\n readonly httpMetadata?: Readonly<Record<string, string>>;\n };\n\n/** Every object of the bucket, through all pages of a listing. */\nasync function allObjects(real: R2Bucket): Promise<R2Object[]> {\n const out: R2Object[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page: R2Objects = await real.list({\n include: [\"customMetadata\", \"httpMetadata\"],\n ...(cursor === undefined ? {} : { cursor }),\n });\n out.push(...page.objects);\n if (!page.truncated) return out;\n cursor = page.cursor;\n }\n}\n\n/** Empty the bucket and put its seeds, before a run. */\nexport async function resetR2(\n real: R2Bucket,\n seeds: Readonly<Record<string, R2Seed>>,\n): Promise<void> {\n const keys = (await allObjects(real)).map((o) => o.key);\n for (let i = 0; i < keys.length; i += 1000) await real.delete(keys.slice(i, i + 1000));\n for (const [key, seed] of Object.entries(seeds)) {\n if (typeof seed === \"string\") await real.put(key, seed);\n else\n await real.put(key, seed.value, {\n ...(seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {}),\n ...(seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}),\n });\n }\n}\n\n/** Largest object whose text the snapshot keeps. */\nconst snapshotTextLimit = 4096;\n\n/**\n * The bucket's objects as rows `{ key, size, etag, customMetadata,\n * httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is\n * valid UTF-8. Versions and upload times are left out: they are the store's,\n * not the Worker's.\n */\nexport async function snapshotR2(real: R2Bucket): Promise<JsonValue[]> {\n const rows: JsonValue[] = [];\n const objects = (await allObjects(real)).sort((a, b) =>\n a.key < b.key ? -1 : a.key > b.key ? 1 : 0,\n );\n for (const o of objects) {\n let text: string | undefined;\n if (o.size <= snapshotTextLimit) {\n const body = await real.get(o.key);\n if (body && \"body\" in body) {\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false }).decode(\n await body.arrayBuffer(),\n );\n } catch {\n // not text: the size and etag stand for it\n }\n }\n }\n rows.push(\n toJson({\n key: o.key,\n size: o.size,\n etag: o.etag,\n customMetadata: o.customMetadata ?? {},\n httpMetadata: o.httpMetadata ?? {},\n ...(text === undefined ? {} : { text }),\n }),\n );\n }\n return rows;\n}\n","/**\n * Workflows, modelled: the binding's `create`/`get`, and each instance run\n * as invocations of its class's `run(event, step)` against a model of the\n * engine (persisted step results, retries in virtual time, restarts that\n * re-run `run` from the start). The real local engine is never called: it\n * runs on its own real-time clock and retry loop, which Eutaxy can neither\n * fault nor schedule. See docs/design.md, \"Workflows\".\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n type FaultKind,\n invocationOf,\n type JsonValue,\n type RunHooks,\n toJson,\n writeFaults,\n} from \"@eutaxy/core\";\nimport {\n CrashSignal,\n InjectedEffectError,\n type Outcome as RunOutcome,\n runInvocation,\n} from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\nimport { constructEntrypoint } from \"./entrypoint.ts\";\n\n/** The `EventRef.source` of a Workflow instance's run. */\nexport const workflowSource = \"workflow\";\n\n/** Before a step's callback: the engine restarts before the step runs. */\nconst STEP_START: readonly FaultKind[] = [\"crash_before\"];\n/**\n * After it: the engine restarts after the step ran but before its result\n * was persisted (`crash_after`), or the attempt ran and counted as failed,\n * as a timeout does (`ambiguous`).\n */\nconst STEP_RESULT: readonly FaultKind[] = [\"crash_after\", \"ambiguous\"];\n\n/**\n * Cloudflare's defaults for a step without a config (Workflows, Sleeping\n * and retrying). A partial config is merged with them field by field, as\n * the engine does. Miniflare's local engine waits 1 s by default; the\n * model keeps the documented 10 s.\n */\nconst defaultRetries = { limit: 5, delay: 10_000, backoff: \"exponential\" } as const;\n\n/**\n * A persisted step result; a failure is kept as the engine keeps it, serialised\n * (built-in types survive; a custom error name does not survive the clone, so\n * it is kept beside and put back on replay).\n */\ntype Outcome =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown; readonly errorName?: string };\n\n/** Keep a thrown value as the engine keeps it, with an Error's name, which the clone would lose. */\nfunction failure(thrown: unknown): Outcome {\n let kept: unknown;\n try {\n kept = structuredClone(thrown);\n } catch {\n kept = new Error(String(thrown));\n }\n return thrown instanceof Error\n ? { ok: false, error: kept, errorName: thrown.name }\n : { ok: false, error: kept };\n}\n\n/** An event sent to an instance, as `waitForEvent` returns it. */\nexport interface InstanceEvent {\n readonly type: string;\n readonly payload: unknown;\n readonly timestamp: Date;\n}\n\nexport interface Instance {\n readonly id: string;\n readonly params: unknown;\n readonly createdAt: number;\n /** The engine's statuses the model reaches; `waiting` while a wait for an event is pending. */\n status: \"queued\" | \"running\" | \"waiting\" | \"complete\" | \"errored\";\n /** Events sent and not yet consumed by a wait, in order, per type (the engine's buffer). */\n readonly events: Map<string, InstanceEvent[]>;\n /**\n * The pending wait, while the instance is `waiting`: its type, its generation, which a wake\n * must match, and whether an event already woke it (a second event is buffered, not a second wake).\n */\n waiting: { readonly type: string; readonly gen: number; woken: boolean } | undefined;\n /** Generations of waits so far, so a stale wake (the timeout of a wait an event ended) is told apart. */\n waitGen: number;\n /** What `run` returned, as the engine keeps it; summarised only where it is recorded. */\n output?: unknown;\n error?: { readonly name: string; readonly message: string };\n /** Persisted step and sleep results, by name and count: what a restart replays. */\n readonly persisted: Map<string, Outcome>;\n /** Attempts started per step, persisted as the engine does, so a restart goes on counting. */\n readonly attempts: Map<string, number>;\n /** Each step's config as its first attempt resolved it; a restart reuses it, as the engine does. */\n readonly configs: Map<\n string,\n { readonly retries: ResolvedRetries; readonly timeout: unknown; readonly sensitive?: string }\n >;\n /** Each pending sleep's or retry's deadline, persisted before it waits, so a restart waits only the rest. */\n readonly deadlines: Map<string, number>;\n}\n\n/** One binding's instances in the current run. */\nexport class WorkflowRegistry {\n readonly instances = new Map<string, Instance>();\n\n clear(): void {\n this.instances.clear();\n }\n\n /** The instances as rows for the end-of-run snapshot, by id. */\n rows(): JsonValue[] {\n return [...this.instances.values()]\n .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n .map((i) => ({\n id: i.id,\n status: i.status,\n params: toJson(i.params),\n ...(i.output === undefined ? {} : { output: toJson(i.output) }),\n ...(i.error === undefined ? {} : { error: `${i.error.name}: ${i.error.message}` }),\n }));\n }\n}\n\n/** A Workflow binding as the env shows it (Miniflare's `WorkflowImpl`). */\nexport function isWorkflowBinding(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v[\"create\"] === \"function\" &&\n typeof v[\"createBatch\"] === \"function\" &&\n typeof v[\"get\"] === \"function\"\n );\n}\n\ninterface CreateOptions {\n readonly id?: string;\n readonly params?: unknown;\n}\n\n/** The binding's proxy: instances live in the registry and run as events, never in the real engine. */\nexport function proxyWorkflow(\n binding: string,\n ctx: ProxyContext,\n registry: WorkflowRegistry,\n): object {\n const target = `Workflow:${binding}`;\n const unsupported = (what: string): never => {\n const reason = `Workflow ${binding}: ${what} is not modelled`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n const handle = (id: string): object => ({\n id,\n status: () =>\n ctx.hooks.effect(\n { invocation: ctx.currentInvocation(), target, op: \"status\", args: { id }, allowed: [] },\n async () => {\n const i = registry.instances.get(id);\n if (!i) throw new Error(\"instance.not_found\");\n return {\n status: i.status,\n // A copy, as the binding's serialised answer is: the caller cannot change the instance.\n // The binding answers null when there is no output yet, or run() returned nothing.\n output: i.output === undefined ? null : structuredClone(i.output),\n ...(i.error === undefined ? {} : { error: { ...i.error } }),\n };\n },\n (s) => toJson(s),\n ),\n pause: () => unsupported(\"pause()\"),\n resume: () => unsupported(\"resume()\"),\n terminate: () => unsupported(\"terminate()\"),\n restart: () => unsupported(\"restart()\"),\n sendEvent: (args: { readonly type?: unknown; readonly payload?: unknown } = {}) =>\n ctx.hooks.effect(\n {\n invocation: ctx.currentInvocation(),\n target,\n op: \"send_event\",\n args: { id, type: toJson(args.type), payload: toJson(args.payload) },\n // A call to the engine: it may never arrive, or arrive with its answer lost.\n allowed: writeFaults,\n },\n async () => {\n const type = validEventType(args.type);\n const i = registry.instances.get(id);\n if (!i) throw new Error(\"instance.not_found\");\n if (i.status === \"complete\" || i.status === \"errored\")\n throw new Error(\n `(instance.not_running) Workflow instance with id \"${id}\" is ${i.status} and takes no events`,\n );\n const event: InstanceEvent = {\n type,\n payload: structuredClone(args.payload),\n timestamp: new Date(),\n };\n const queue = i.events.get(type) ?? [];\n queue.push(event);\n i.events.set(type, queue);\n // A wait for this type is pending: wake the instance once; its timeout wake becomes stale.\n if (i.status === \"waiting\" && i.waiting?.type === type && !i.waiting.woken) {\n i.waiting.woken = true;\n ctx.hooks.enqueue({\n id: `workflow:${binding}:${id}:event-${i.waiting.gen}`,\n attempt: 1,\n source: workflowSource,\n data: { binding, id, wake: i.waiting.gen },\n });\n }\n return null;\n },\n () => null,\n ),\n delete: () => unsupported(\"delete()\"),\n subscribe: () => unsupported(\"subscribe()\"),\n });\n return {\n async create(options: CreateOptions = {}) {\n // Generated with the run's virtual randomness, before the call, as the binding does locally.\n const id = options.id ?? crypto.randomUUID();\n // The binding's own default (Miniflare): no params is an empty object; null stays null.\n const params = structuredClone(options.params === undefined ? {} : options.params);\n return ctx.hooks.effect(\n {\n invocation: ctx.currentInvocation(),\n target,\n op: \"create\",\n args: { id, params: toJson(params) },\n // A call to the engine: it may never arrive, or arrive with its answer lost.\n allowed: writeFaults,\n },\n async () => {\n if (!validInstanceId(id)) throw new Error(\"Workflow instance has invalid id\");\n if (registry.instances.has(id))\n throw new Error(\n `(instance.already_exists) Workflow instance with id \"${id}\" already exists`,\n );\n registry.instances.set(id, {\n id,\n params,\n createdAt: Date.now(),\n status: \"queued\",\n events: new Map(),\n waiting: undefined,\n waitGen: 0,\n persisted: new Map(),\n attempts: new Map(),\n configs: new Map(),\n deadlines: new Map(),\n });\n ctx.hooks.enqueue({\n id: `workflow:${binding}:${id}`,\n attempt: 1,\n source: workflowSource,\n data: { binding, id },\n });\n return handle(id);\n },\n () => ({ id }),\n );\n },\n async get(id: string) {\n return ctx.hooks.effect(\n { invocation: ctx.currentInvocation(), target, op: \"get\", args: { id }, allowed: [] },\n async () => {\n if (!registry.instances.has(id)) throw new Error(\"instance.not_found\");\n return handle(id);\n },\n () => ({ id }),\n );\n },\n createBatch: () => unsupported(\"createBatch()\"),\n deleteBatch: () => unsupported(\"deleteBatch()\"),\n };\n}\n\n/** The binding's rule for an instance id (Miniflare): up to 100 of these characters. */\nfunction validInstanceId(id: unknown): boolean {\n return typeof id === \"string\" && id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(id);\n}\n\n/** An event type as Workflows accept it (Events and parameters): up to 100 of these characters, else `workflow.invalid_event_type`. */\nfunction validEventType(type: unknown): string {\n if (typeof type === \"string\" && type.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(type))\n return type;\n throw new Error(\n `(workflow.invalid_event_type) event type must be up to 100 letters, digits, - or _, got ${JSON.stringify(type)}`,\n );\n}\n\n/** Thrown through `run()` to suspend an instance waiting for an event; never meant to be caught. */\nclass Suspension {\n readonly gen: number;\n constructor(gen: number) {\n this.gen = gen;\n }\n}\n\n/** A wake event's data: which wait's generation it ends. */\ninterface WakeData {\n readonly binding: string;\n readonly id: string;\n readonly wake?: number;\n}\n\n/**\n * Whether a run event wakes the instance: not a wake at all, the restart of a\n * run a wake began (its first delivery resumed the instance), or the wake of\n * the wait still pending.\n */\nexport function wakes(instance: Instance, event: EventRef): boolean {\n const wake = (event.data as unknown as WakeData).wake;\n if (wake === undefined || event.attempt > 1) return true;\n return instance.status === \"waiting\" && instance.waiting?.gen === wake;\n}\n\n/** Construct a `WorkflowEntrypoint` subclass outside the runtime, for the one `new` per instance run. */\nexport function constructWorkflow(cls: unknown, ctx: unknown, env: unknown): object {\n return constructEntrypoint(cls, \"WorkflowEntrypoint\", ctx, env);\n}\n\n/** The engine's conversion (itty-time): a year is 365.25 days, a month 30; an unknown unit counts 1. */\nconst units: { readonly [unit: string]: number } = {\n year: 31_557_600_000,\n month: 2_592_000_000,\n week: 604_800_000,\n day: 86_400_000,\n hour: 3_600_000,\n minute: 60_000,\n second: 1000,\n m: 1,\n};\n\n/** The engine's reading of a duration, NaN where it reads none. */\nfunction engineDuration(d: unknown): number {\n if (!Number.isNaN(Number(d)) && typeof d !== \"object\") return Number(d);\n if (typeof d !== \"string\") return Number.NaN;\n const m = /^([^ ]+) +(\\w\\w*?)s?$/.exec(d);\n if (!m) return Number.NaN;\n return Number(m[1]) * (units[m[2] as string] ?? 1);\n}\n\n/** A Workflows duration in milliseconds, read as the engine reads it. */\nexport function durationMs(d: unknown): number {\n const ms = engineDuration(d);\n if (Number.isNaN(ms) || ms < 0) throw new TypeError(`not a Workflows duration: ${String(d)}`);\n return ms;\n}\n\n/** Miniflare's `isValidStepConfig`, exactly: its schema is strict, and a timeout `== 0` is refused. */\nexport function validStepConfig(config: unknown): boolean {\n const only = (o: object, keys: readonly string[]) =>\n Object.keys(o).every((k) => keys.includes(k));\n const durationOk = (v: unknown) => !Number.isNaN(engineDuration(v));\n if (\n typeof config !== \"object\" ||\n config === null ||\n !only(config, [\"retries\", \"timeout\", \"sensitive\"])\n )\n return false;\n const c = config as Record<string, unknown>;\n const r = c[\"retries\"] as Record<string, unknown> | undefined;\n if (r !== undefined) {\n if (typeof r !== \"object\" || r === null || !only(r, [\"delay\", \"limit\", \"backoff\"]))\n return false;\n const delay = r[\"delay\"];\n if (\n !(\n typeof delay === \"function\" ||\n typeof delay === \"string\" ||\n (typeof delay === \"number\" && delay >= 0)\n )\n )\n return false;\n if (typeof r[\"limit\"] !== \"number\" || r[\"limit\"] < 0) return false;\n if (\n r[\"backoff\"] !== undefined &&\n ![\"constant\", \"linear\", \"exponential\"].includes(r[\"backoff\"] as string)\n )\n return false;\n if (typeof delay !== \"function\" && !durationOk(delay)) return false;\n }\n const t = c[\"timeout\"];\n if (t !== undefined) {\n if (!(typeof t === \"string\" || (typeof t === \"number\" && t >= 0))) return false;\n // biome-ignore lint/suspicious/noDoubleEquals: the engine's own loose test (\"0\" and \"\" are zero)\n if (t == 0 || !durationOk(t)) return false;\n }\n if (c[\"sensitive\"] !== undefined && c[\"sensitive\"] !== \"output\") return false;\n return true;\n}\n\nconst utf8 = new TextEncoder();\n\n/** About how many bytes a value takes stored, walking it as structured cloning does. */\nfunction approximateBytes(value: unknown, seen = new Set<object>()): number {\n if (value === null || value === undefined) return 1;\n switch (typeof value) {\n case \"string\":\n return utf8.encode(value).length;\n case \"number\":\n case \"bigint\":\n return 8;\n case \"boolean\":\n return 1;\n case \"object\":\n break;\n default:\n return 0;\n }\n const o = value as object;\n if (seen.has(o)) return 0;\n seen.add(o);\n if (o instanceof ArrayBuffer || ArrayBuffer.isView(o)) return o.byteLength;\n if (o instanceof Date) return 8;\n let total = 0;\n if (o instanceof Map)\n for (const [k, v] of o) total += approximateBytes(k, seen) + approximateBytes(v, seen);\n else if (o instanceof Set) for (const v of o) total += approximateBytes(v, seen);\n else\n for (const [k, v] of Object.entries(o))\n total += utf8.encode(k).length + approximateBytes(v, seen);\n return total;\n}\n\nfunction sleep(ms: number): Promise<void> {\n // The virtual setTimeout: the run fires it when the invocation is idle.\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\ninterface ResolvedRetries {\n readonly limit: number;\n readonly delay: unknown;\n readonly backoff?: string;\n}\n\ninterface StepConfig {\n readonly retries?: { readonly limit: number; readonly delay: unknown; readonly backoff?: string };\n readonly timeout?: unknown;\n /** \"output\": the step's output is redacted in the engine's logs, here in the trace. */\n readonly sensitive?: string;\n}\n\ninterface RunDelivery {\n readonly binding: string;\n /** The Workflow's configured name, for `event.workflowName`. */\n readonly name?: string;\n readonly instance: Instance;\n readonly cls: unknown;\n /** The env the instance sees: the proxied bindings. */\n readonly env: object;\n readonly maxFaultsPerRun: number;\n readonly maxRedeliveries: number;\n}\n\n/**\n * One engine attempt of an instance: construct its class and call `run`.\n * Steps whose results were persisted return them without running; a crash\n * restarts the instance (a new attempt, from the start of `run`).\n */\nexport async function deliverWorkflow(\n event: EventRef,\n hooks: RunHooks,\n d: RunDelivery,\n): Promise<DeliveryResult> {\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const target = `Workflow:${d.binding}`;\n const instance = d.instance;\n // A wake of a wait that already ended (an event came before the timeout, or the reverse): nothing to do.\n if (!wakes(instance, event)) return { status: \"completed\", followUps: [] };\n instance.status = \"running\";\n instance.waiting = undefined;\n const background: Promise<unknown>[] = [];\n const counts = new Map<string, number>();\n const key = (kind: string, name: string): string => {\n const count = (counts.get(`${kind}:${name}`) ?? 0) + 1;\n counts.set(`${kind}:${name}`, count);\n return `${kind}:${name}#${count}`;\n };\n const replay = (o: Outcome): unknown => {\n if (o.ok) return structuredClone(o.value);\n const error: unknown = structuredClone(o.error);\n if (o.errorName !== undefined && error instanceof Error) error.name = o.errorName;\n throw error;\n };\n\n const step = {\n do: async (name: string, a: unknown, b?: unknown, c?: unknown): Promise<unknown> => {\n const [config, fn, options] = (typeof a === \"function\" ? [{}, a, b] : [a ?? {}, b, c]) as [\n StepConfig,\n (ctx: unknown) => unknown,\n { rollback?: unknown } | undefined,\n ];\n if (suspending !== undefined) continuedAfterSuspension(\"step.do\");\n if (options?.rollback !== undefined) {\n hooks.unsupported(`Workflow ${d.binding}: rollback handlers are not modelled`);\n throw new Error(\"eutaxy: rollback handlers are not modelled\");\n }\n // The engine's checks, before anything runs: fatal errors there, whose catching is not documented.\n const fatal = (message: string): never => {\n hooks.unsupported(`Workflow ${d.binding}: ${message}`);\n const err = new Error(message);\n err.name = \"WorkflowFatalError\";\n throw err;\n };\n if (name.length > 256 || [...name].some((c) => c.charCodeAt(0) < 0x20))\n fatal(`Step name \"${name}\" exceeds max length (256 chars) or invalid characters found`);\n if (!validStepConfig(config))\n fatal(\n `Step config for \"${name}\" is in a invalid format. See https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/`,\n );\n const k = key(\"do\", name);\n const count = counts.get(`do:${name}`) as number;\n const done = instance.persisted.get(k);\n if (done) return replay(done);\n const live = { ...defaultRetries, ...config.retries };\n const first = instance.configs.get(k);\n if (!first)\n instance.configs.set(k, {\n retries: live,\n timeout: config.timeout ?? \"10 minutes\",\n ...(config.sensitive === undefined ? {} : { sensitive: config.sensitive }),\n });\n const sensitive = first ? first.sensitive : config.sensitive;\n const stored = first?.retries;\n // A delay function is not persisted: the engine calls the one the current run passes, or\n // falls back to the default delay; the crashed run's function is never called again.\n const retries =\n stored && typeof stored.delay === \"function\"\n ? {\n ...stored,\n delay: typeof live.delay === \"function\" ? live.delay : defaultRetries.delay,\n }\n : (stored ?? live);\n const limit = Math.min(retries.limit, d.maxRedeliveries);\n // What the callback sees: a delay function is not exposed (Workflows, Step context).\n const { delay, ...shown } = retries;\n const resolved = {\n retries: typeof delay === \"function\" ? shown : retries,\n timeout: first ? first.timeout : (config.timeout ?? \"10 minutes\"),\n ...(sensitive === undefined ? {} : { sensitive }),\n };\n for (let attempt = (instance.attempts.get(k) ?? 0) + 1; ; attempt++) {\n // A retry the engine was waiting for when it restarted: only the rest of its delay.\n const due = instance.deadlines.get(`retry:${k}`);\n if (due !== undefined) {\n await sleep(Math.max(0, due - Date.now()));\n instance.deadlines.delete(`retry:${k}`);\n }\n // A fresh copy per attempt: what the callback does to it does not reach the engine's own.\n const stepContext = {\n step: { name, count },\n attempt,\n config: { ...resolved, retries: { ...resolved.retries } },\n };\n const args = { instance: instance.id, step: name, count, attempt };\n // The callback runs as the instance's own code, between two points: its effects are ordinary\n // effects of the invocation, and its timers are virtual. The points are asynchronous, as the\n // engine's reading and persisting are: other events may run between steps.\n await hooks.effect(\n { invocation, target, op: \"step\", args, allowed: STEP_START },\n async () => null,\n () => null,\n );\n instance.attempts.set(k, attempt);\n // What the attempt threw, kept as thrown (a plain value too), as the engine rethrows it.\n let failed = false;\n let thrown: unknown;\n let value: unknown;\n let returned: { readonly value: unknown } | undefined;\n try {\n returned = { value: await fn(stepContext) };\n } catch (err) {\n // A crash ends the attempt and the instance; it is not a failure to retry.\n if (err instanceof CrashSignal || inv.isCrashed()) throw err;\n failed = true;\n thrown = err;\n try {\n hooks.effectSync(\n { invocation, target, op: \"step_result\", args, allowed: [] },\n () => {\n throw err;\n },\n () => null,\n );\n } catch {\n // Recorded as the attempt's error; handled below.\n }\n }\n if (returned !== undefined) {\n const notModelled = (reason: string): never => {\n hooks.unsupported(`Workflow ${d.binding}: step \"${name}\" ${reason}`);\n throw new Error(`eutaxy: step \"${name}\" ${reason}`);\n };\n try {\n value = structuredClone(returned.value);\n } catch {\n // A stream, or anything else the engine persists in its own way: not a failure to retry.\n notModelled(\n \"returned a value that is not structured-cloneable (a ReadableStream is not modelled)\",\n );\n }\n if (approximateBytes(value) > 1_048_576)\n notModelled(\n 'returned more than about 1 MiB, which the engine refuses (\"output is too large\"); Eutaxy cannot measure the stored size exactly',\n );\n }\n if (!failed) {\n try {\n await hooks.effect(\n { invocation, target, op: \"step_result\", args, allowed: STEP_RESULT },\n async () => value,\n (v) => ({ output: sensitive === \"output\" ? \"[REDACTED]\" : toJson(v) }),\n );\n instance.persisted.set(k, { ok: true, value });\n return structuredClone(value);\n } catch (err) {\n if (err instanceof CrashSignal || !(err instanceof InjectedEffectError)) throw err;\n // The attempt ran but counted as failed: a timeout, as the engine reports one.\n thrown = Object.assign(\n new Error(`Execution timed out after ${durationMs(resolved.timeout)}ms`),\n { name: \"WorkflowTimeoutError\" },\n );\n }\n }\n // The engine's predicate (an Error so named, or whose message starts so). It rethrows the\n // value as thrown and does not persist it, so after a restart the callback runs again.\n if (\n thrown instanceof Error &&\n (thrown.name === \"NonRetryableError\" || thrown.message.startsWith(\"NonRetryableError\"))\n )\n throw thrown;\n if (attempt > limit) {\n instance.persisted.set(k, failure(thrown));\n throw thrown;\n }\n let wait: number;\n try {\n // A fresh context from the engine's own values: the callback may have changed its copy.\n const delayContext = {\n step: { name, count },\n attempt,\n config: { ...resolved, retries: { ...resolved.retries } },\n };\n wait = await retryDelayMs(retries, attempt, delayContext, thrown);\n } catch (err) {\n hooks.unsupported(\n `Workflow ${d.binding}: step \"${name}\"'s retry delay function threw (${String(err)})`,\n );\n throw err;\n }\n instance.deadlines.set(`retry:${k}`, Date.now() + wait);\n await sleep(wait);\n instance.deadlines.delete(`retry:${k}`);\n }\n },\n sleep: async (name: string, duration: unknown): Promise<void> => {\n const ms = durationMs(duration);\n // Keyed by name and duration, as the engine keys sleeps: another duration is another sleep.\n await sleepStep(key(\"sleep\", `${name}\\u0000${ms}`), name, ms);\n },\n sleepUntil: async (name: string, timestamp: unknown): Promise<void> => {\n const at = timestamp instanceof Date ? timestamp.getTime() : Number(timestamp);\n const k = key(\"sleepUntil\", `${name}\\u0000${at}`);\n if (instance.persisted.has(k)) {\n // Miniflare's engine checks the time before its cache and throws here; production is undocumented.\n if (at < Date.now())\n hooks.unsupported(\n `Workflow ${d.binding}: step.sleepUntil \"${name}\" replayed after its time, where Miniflare's engine throws`,\n );\n return;\n }\n // Miniflare's engine refuses a time in the past, with this message.\n if (at < Date.now() && !instance.deadlines.has(k))\n throw new Error(\"You can't sleep until a time in the past, time-traveler\");\n await sleepStep(k, name, Math.max(0, at - Date.now()), at);\n },\n waitForEvent: async (\n name: string,\n options: { readonly type?: unknown; readonly timeout?: unknown } = {},\n ): Promise<unknown> => {\n if (suspending !== undefined) continuedAfterSuspension(\"step.waitForEvent\");\n const type = validEventType(options.type);\n const timeoutMs = durationMs(options.timeout ?? \"24 hours\");\n if (!(timeoutMs >= 1000 && timeoutMs <= 365 * 24 * 3_600_000)) {\n hooks.unsupported(\n `Workflow ${d.binding}: waitForEvent \"${name}\" timeout must be between 1 second and 365 days`,\n );\n const err = new Error(`Invalid timeout for waitForEvent \"${name}\"`);\n err.name = \"WorkflowFatalError\";\n throw err;\n }\n // Keyed by name and count, as the engine keys waits.\n const k = key(\"waitForEvent\", name);\n const done = instance.persisted.get(k);\n if (done) return replay(done);\n const args = { instance: instance.id, step: name, type };\n const existing = instance.deadlines.get(k);\n // An event already sent: the first of its type, as the engine's queue gives it, if it came\n // before the wait's deadline; one sent after it finds the wait timed out and stays buffered.\n const queue = instance.events.get(type) ?? [];\n const inTime = queue.findIndex(\n (e) => existing === undefined || e.timestamp.getTime() < existing,\n );\n const received = inTime < 0 ? undefined : queue.splice(inTime, 1)[0];\n if (received) {\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"event\",\n args: { ...args, timestamp: received.timestamp.getTime() },\n allowed: [],\n },\n () => received,\n (e) => ({ payload: toJson(e.payload) }),\n );\n instance.persisted.set(k, { ok: true, value: received });\n return structuredClone(received);\n }\n if (existing !== undefined && Date.now() >= existing) {\n // The wait's time is up: the error is the step's, persisted, and the instance fails unless the code catches it.\n const error = Object.assign(new Error(`Execution timed out after ${timeoutMs}ms`), {\n name: \"WorkflowTimeoutError\",\n });\n hooks.effectSync(\n { invocation, target, op: \"wait_timeout\", args, allowed: [] },\n () => null,\n () => null,\n );\n instance.persisted.set(k, failure(error));\n throw error;\n }\n const deadline = existing ?? Date.now() + timeoutMs;\n if (existing === undefined) {\n instance.deadlines.set(k, deadline);\n hooks.effectSync(\n { invocation, target, op: \"wait\", args: { ...args, timeoutMs }, allowed: [] },\n () => null,\n () => null,\n );\n }\n // Nothing to wait on yet: the instance hibernates until the event or the deadline wakes it.\n const gen = ++instance.waitGen;\n instance.waiting = { type, gen, woken: false };\n suspending = { gen, deadline };\n throw new Suspension(gen);\n },\n };\n /** Set once a wait suspended this run: anything the code does after it caught the suspension is not modelled. */\n let suspending: { readonly gen: number; readonly deadline: number } | undefined;\n const continuedAfterSuspension = (what: string): never => {\n const reason = `Workflow ${d.binding}: ${what} after step.waitForEvent suspended the instance; the code caught the suspension (catch only the wait's WorkflowTimeoutError)`;\n hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n async function sleepStep(k: string, name: string, ms: number, until?: number): Promise<void> {\n if (suspending !== undefined) continuedAfterSuspension(\"step.sleep\");\n if (instance.persisted.has(k)) return;\n const pending = instance.deadlines.get(k);\n if (pending !== undefined) {\n await sleep(Math.max(0, pending - Date.now()));\n instance.persisted.set(k, { ok: true, value: null });\n return;\n }\n instance.deadlines.set(k, Date.now() + ms);\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"sleep\",\n args: { instance: instance.id, step: name, ms, ...(until === undefined ? {} : { until }) },\n allowed: [],\n },\n () => null,\n () => null,\n );\n await sleep(ms);\n instance.persisted.set(k, { ok: true, value: null });\n }\n\n const ran = await runInvocation(hooks, inv, () => {\n const flow = constructWorkflow(d.cls, executionContext(background), d.env) as {\n run(event: unknown, step: unknown): unknown;\n };\n const workflowEvent: Record<string, unknown> = {\n payload: structuredClone(instance.params),\n timestamp: new Date(instance.createdAt),\n instanceId: instance.id,\n };\n if (d.name !== undefined) workflowEvent[\"workflowName\"] = d.name;\n else\n Object.defineProperty(workflowEvent, \"workflowName\", {\n enumerable: true,\n get: () => {\n hooks.unsupported(\n `Workflow ${d.binding}: event.workflowName needs the Workflow's name, workflow(binding, className, { name })`,\n );\n return undefined;\n },\n });\n return flow.run(workflowEvent, step);\n });\n // The engine keeps the result serialised: one it cannot keep fails the instance.\n const serialised = (value: unknown): RunOutcome<unknown> => {\n try {\n return { status: \"completed\", value: structuredClone(value) };\n } catch {\n hooks.unsupported(\n `Workflow ${d.binding}: run() returned a value that is not structured-cloneable`,\n );\n return {\n status: \"errored\",\n error: new Error(\"run() returned a value that is not structured-cloneable\"),\n };\n }\n };\n let result: RunOutcome<unknown> = ran.status === \"completed\" ? serialised(ran.value) : ran;\n if (suspending !== undefined) {\n // The run ended by suspending: its outcome is the wait, whatever the code made of the sentinel.\n if (!(ran.status === \"errored\" && ran.error instanceof Suspension) && ran.status !== \"crashed\")\n hooks.unsupported(\n `Workflow ${d.binding}: run() ${ran.status === \"completed\" ? \"returned\" : \"threw\"} after step.waitForEvent suspended the instance; the code caught the suspension (catch only the wait's WorkflowTimeoutError)`,\n );\n if (ran.status !== \"crashed\") result = { status: \"completed\", value: undefined };\n }\n let status = result.status;\n if (suspending !== undefined && result.status === \"completed\") {\n instance.status = \"waiting\";\n const suspended = suspending;\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n if (status === \"crashed\") {\n // The crash ends the run; the restart below suspends again with a new generation.\n instance.status = \"running\";\n instance.waiting = undefined;\n }\n const followUps: EventRef[] =\n status === \"crashed\"\n ? instance.status === \"running\" && event.attempt <= d.maxFaultsPerRun\n ? [{ ...event, attempt: event.attempt + 1 }]\n : []\n : [\n // The timeout wake, due at the deadline; an event sent earlier wakes the instance first.\n {\n id: `workflow:${d.binding}:${instance.id}:timeout-${suspended.gen}`,\n attempt: 1,\n source: workflowSource,\n data: { binding: d.binding, id: instance.id, wake: suspended.gen },\n at: suspended.deadline,\n },\n ];\n return { status, followUps };\n }\n if (result.status === \"completed\") {\n instance.status = \"complete\";\n instance.output = result.value;\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"complete\",\n args: { instance: instance.id, output: toJson(instance.output) },\n allowed: [],\n },\n () => null,\n () => null,\n );\n } else if (result.status === \"errored\") {\n instance.status = \"errored\";\n const e = result.error;\n instance.error =\n e instanceof Error\n ? { name: e.name, message: e.message }\n : { name: \"Error\", message: String(e) };\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"errored\",\n args: { instance: instance.id, error: `${instance.error.name}: ${instance.error.message}` },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n // The engine restarts a crashed instance from the start of `run`; crashes come from faults, so few.\n const followUps =\n status === \"crashed\" && instance.status === \"running\" && event.attempt <= d.maxFaultsPerRun\n ? [{ ...event, attempt: event.attempt + 1 }]\n : [];\n return { status, followUps };\n}\n\n/** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */\nasync function retryDelayMs(\n retries: NonNullable<StepConfig[\"retries\"]>,\n attempt: number,\n ctx: unknown,\n error: unknown,\n): Promise<number> {\n const delay =\n typeof retries.delay === \"function\"\n ? await (retries.delay as (i: unknown) => unknown)({ ctx, error })\n : retries.delay;\n // The backoff applies to a delay function's value too, as in Miniflare's engine.\n const base = durationMs(delay);\n switch (retries.backoff) {\n case \"linear\":\n return base * attempt;\n case \"exponential\":\n return base * 2 ** (attempt - 1);\n default:\n return base;\n }\n}\n","/**\n * Each kind of binding the platform models, as one record: how an env value\n * is recognised, what the Worker sees in its place, what is forgotten before\n * a run, the reset its setup step asks for, the snapshot the run ends with,\n * and, for the kinds with events of their own (alarms, Workflow runs), their\n * delivery. The platform and the differential runner iterate these records;\n * neither knows a kind by name.\n */\n\nimport type {\n DeliveryResult,\n EventRef,\n JsonValue,\n PlatformData,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { alarmSource, deliverAlarm } from \"./alarms.ts\";\nimport { type CalleeModule, CalleeState, calleeEnv, proxyCallee } from \"./callees.ts\";\nimport { isD1, type ProxyContext, proxyD1, resetD1, snapshotD1 } from \"./d1.ts\";\nimport {\n alarmRunner,\n BindingState,\n type DurableObjectTestHelpers,\n evictObject,\n isDurableObjectNamespace,\n proxyNamespace,\n resetNamespace,\n runInObject,\n snapshotNamespace,\n} from \"./durable-objects.ts\";\nimport { isR2, proxyR2, resetR2, snapshotR2, VersionBook } from \"./r2.ts\";\nimport {\n type CalleeSetup,\n type D1Setup,\n type DurableObjectSetup,\n defaultAlarmsPerObject,\n type R2Setup,\n type ServiceSetup,\n type WorkflowSetup,\n} from \"./scenario.ts\";\nimport { isServiceBinding, proxyService } from \"./services.ts\";\nimport {\n deliverWorkflow,\n isWorkflowBinding,\n proxyWorkflow,\n WorkflowRegistry,\n workflowSource,\n} from \"./workflows.ts\";\n\n/** A setup step that names a binding; every kind modelled here has one. */\nexport interface BindingSetup extends PlatformData {\n readonly binding: string;\n}\n\n/** The tables of one binding's end-of-run snapshot. */\nexport type Tables = { readonly [table: string]: readonly JsonValue[] };\n\n/**\n * One kind of binding. `Real` is the env value's type once `is` accepted it;\n * `Setup` the setup step that names a binding of this kind.\n */\nexport interface Binding<Real = unknown, Setup extends BindingSetup = BindingSetup> {\n /** The `kind` of the setup step naming a binding of this type. */\n readonly kind: Setup[\"kind\"];\n /** The prefix of its snapshot targets: `D1`, `DO`, `R2`, `Workflow`. */\n readonly target: string;\n /** Whether an env value is a binding of this kind. */\n is(value: unknown): value is Real;\n /**\n * What the Worker sees in place of the real binding, asked on every access\n * of `env.<name>`: the record keeps one proxy per name where it may, and\n * reports a binding the scenario did not set up each time it is touched.\n * `undefined` means the name is not this record's (two records share one\n * kind of env value: a service binding is a callee's or scripted), so the\n * next record is asked.\n */\n proxy(name: string, real: Real, ctx: ProxyContext): unknown;\n /** Forget what the last run learned, before the next run's setup. */\n clear(): void;\n /** Bring the real binding, or the model, to the state the setup step asks for. */\n reset(step: Setup, real: unknown): Promise<void>;\n /**\n * The snapshot the run ends with, read through the real binding, or null\n * when the env value is not this binding. `unsupported` reports what the\n * snapshot found that the run could not control.\n */\n snapshot(\n step: Setup,\n real: unknown,\n unsupported: (reason: string) => void,\n ): Promise<Tables | null>;\n /** `EventRef.source` of the events this binding emits, when it has any. */\n readonly source?: string;\n /** Deliver one of its events. */\n deliver?(event: EventRef, hooks: RunHooks, spec: ScenarioSpec): Promise<DeliveryResult>;\n}\n\n/** A D1 database: Miniflare's SQLite, reset to the scenario's schema and read back whole. */\nexport function d1Binding(schemas: Readonly<Record<string, string>>): Binding<D1Database, D1Setup> {\n const proxies = new Map<string, D1Database>();\n return {\n kind: \"d1\",\n target: \"D1\",\n is: isD1,\n proxy(name, real, ctx) {\n let p = proxies.get(name);\n if (!p) {\n p = proxyD1(real, name, ctx);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {},\n async reset(step, real) {\n const schema = schemas[step.binding];\n if (schema === undefined)\n throw new Error(`no schema provided for D1 binding ${step.binding}`);\n if (!isD1(real)) throw new Error(`env.${step.binding} is not a D1 binding`);\n await resetD1(real, schema);\n },\n async snapshot(_step, real) {\n return isD1(real) ? snapshotD1(real) : null;\n },\n };\n}\n\n/** An R2 bucket: Miniflare's real one, emptied and seeded before each run. */\nexport function r2Binding(): Binding<R2Bucket, R2Setup> {\n /** The buckets the current scenario sets up. */\n let setUp = new Set<string>();\n const proxies = new Map<string, R2Bucket>();\n /** One book for every bucket: the stand-ins count up across them. */\n const versions = new VersionBook();\n return {\n kind: \"r2\",\n target: \"R2\",\n is: isR2,\n proxy(name, real, ctx) {\n if (!setUp.has(name))\n ctx.hooks.unsupported(\n `R2 binding ${name} needs an r2Bucket() setup step, which empties it before each run`,\n );\n let p = proxies.get(name);\n if (!p) {\n p = proxyR2(real, name, ctx, versions);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n setUp = new Set();\n versions.clear();\n },\n async reset(step, real) {\n if (!isR2(real)) throw new Error(`env.${step.binding} is not an R2 bucket`);\n setUp.add(step.binding);\n await resetR2(real, step.objects);\n },\n async snapshot(_step, real) {\n return isR2(real) ? { objects: await snapshotR2(real) } : null;\n },\n };\n}\n\nexport interface DurableObjectDeps {\n readonly ctx: ProxyContext;\n /** The Cloudflare test helpers, without which objects cannot be reset, seeded or snapshotted. */\n readonly helpers: DurableObjectTestHelpers | undefined;\n /** The env value under a binding name: alarm events name their binding, not an object. */\n readonly real: (name: string) => unknown;\n}\n\n/** What the WebSocket delivery needs of a namespace's objects: to run code inside one, and the crash semantics an alarm has. */\nexport interface ObjectAccess {\n run<T>(\n binding: string,\n id: string,\n object: string,\n fn: (instance: unknown, live: DurableObjectState) => Promise<T>,\n ): Promise<T | undefined>;\n abort(binding: string, id: string): void;\n mayPark(binding: string, id: string): boolean;\n evict(binding: string, id: string): Promise<void>;\n}\n\n/**\n * A Durable Object namespace: the real objects workerd runs, cleared, seeded\n * and evicted before each run, their storage snapshotted after it, and their\n * alarms taken over and fired as events of the run.\n */\nexport function durableObjectBinding(\n deps: DurableObjectDeps,\n): Binding<DurableObjectNamespace, DurableObjectSetup> & { readonly objects: ObjectAccess } {\n const { ctx, helpers } = deps;\n const proxies = new Map<string, DurableObjectNamespace>();\n /** The bindings the current scenario's setup resets before each run. */\n let setUp = new Set<string>();\n /** Per binding, alarm firings allowed per object in the current run. */\n let alarmLimits = new Map<string, number>();\n /** Per binding, what the current run knows about its objects. */\n const states = new Map<string, BindingState>();\n const stateFor = (binding: string): BindingState => {\n let state = states.get(binding);\n if (!state) {\n state = new BindingState();\n states.set(binding, state);\n }\n return state;\n };\n const namespace = (name: string, real: unknown = deps.real(name)): DurableObjectNamespace => {\n if (!isDurableObjectNamespace(real))\n throw new Error(`env.${name} is not a Durable Object namespace`);\n return real;\n };\n const required = (): DurableObjectTestHelpers => {\n if (!helpers)\n throw new Error(\n 'Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })',\n );\n return helpers;\n };\n const objects: ObjectAccess = {\n run: (binding, id, object, fn) =>\n runInObject(namespace(binding), binding, ctx, helpers, stateFor(binding), id, object, fn),\n abort: (binding, id) => stateFor(binding).abort(id),\n mayPark: (binding, id) => stateFor(binding).mayPark(id),\n evict: (binding, id) => evictObject(namespace(binding), helpers, id),\n };\n return {\n objects,\n kind: \"durable_object\",\n target: \"DO\",\n is: isDurableObjectNamespace,\n proxy(name, real, ctx) {\n let p = proxies.get(name);\n if (!p) {\n p = proxyNamespace(real, name, ctx, stateFor(name), helpers, () => setUp.has(name));\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n setUp = new Set();\n alarmLimits = new Map();\n for (const state of states.values()) state.clear();\n },\n async reset(step, real) {\n setUp.add(step.binding);\n alarmLimits.set(step.binding, step.alarmsPerObject ?? defaultAlarmsPerObject);\n stateFor(step.binding).seededSql = await resetNamespace(\n namespace(step.binding, real),\n required(),\n stateFor(step.binding).names,\n step.objects,\n step.sql ?? {},\n );\n },\n async snapshot(step, real, unsupported) {\n const binding = step.binding;\n return snapshotNamespace(\n namespace(binding, real),\n required(),\n stateFor(binding).names,\n stateFor(binding).touched,\n step.objects,\n step.sql ?? {},\n stateFor(binding).seededSql,\n (object) =>\n unsupported(\n `Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`,\n ),\n unsupported,\n );\n },\n source: alarmSource,\n async deliver(event, hooks, spec) {\n const binding = String((event.data as { binding?: unknown }).binding ?? \"\");\n return deliverAlarm(event, hooks, spec.bounds.maxRedeliveries, {\n binding,\n book: stateFor(binding).alarms,\n limit: alarmLimits.get(binding) ?? defaultAlarmsPerObject,\n runAlarm: alarmRunner(namespace(binding), binding, ctx, helpers, stateFor(binding)),\n abort: (id) => stateFor(binding).abort(id),\n mayPark: (id) => stateFor(binding).mayPark(id),\n evict: (id) => evictObject(namespace(binding), helpers, id),\n bookkeep: (op, args) =>\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target: `DO:${binding}`,\n op,\n args,\n allowed: [],\n },\n () => null,\n () => null,\n ),\n });\n },\n };\n}\n\nexport interface WorkflowDeps {\n /** The Worker module's exports, where the classes `workflow` setup steps name are found. */\n readonly exports: Readonly<Record<string, unknown>> | undefined;\n /** The env the instances run with: the Worker's proxied one. */\n readonly env: () => object;\n /** The callee a qualified binding (`inventory/FLOW`) belongs to, if the platform was given it: its classes and env are the callee's. */\n readonly calleeOf?: (binding: string) => CalleeModule | undefined;\n}\n\n/**\n * A Workflow binding: a model of the engine running the scenario's own\n * class, never the real binding; instances live in a registry and run as\n * events of the run.\n */\nexport function workflowBinding(deps: WorkflowDeps): Binding<object, WorkflowSetup> {\n /** The bindings the current scenario sets up, with the class each runs. */\n let classes = new Map<string, WorkflowSetup>();\n const registries = new Map<string, WorkflowRegistry>();\n const registryFor = (binding: string): WorkflowRegistry => {\n let r = registries.get(binding);\n if (!r) {\n r = new WorkflowRegistry();\n registries.set(binding, r);\n }\n return r;\n };\n const proxies = new Map<string, object>();\n return {\n kind: \"workflow\",\n target: \"Workflow\",\n is: isWorkflowBinding,\n proxy(name, _real, ctx) {\n if (!classes.has(name)) {\n ctx.hooks.unsupported(\n `Workflow binding ${name} needs a workflow() setup step naming its class`,\n );\n // Never the real binding: its engine would run the class on the real clock.\n return proxyWorkflow(name, ctx, new WorkflowRegistry());\n }\n let p = proxies.get(name);\n if (!p) {\n p = proxyWorkflow(name, ctx, registryFor(name));\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n classes = new Map();\n for (const registry of registries.values()) registry.clear();\n },\n async reset(step) {\n classes.set(step.binding, step);\n },\n async snapshot(step) {\n return { instances: registryFor(step.binding).rows() };\n },\n source: workflowSource,\n async deliver(event, hooks, spec) {\n const { binding, id } = event.data as { binding: string; id: string };\n const setup = classes.get(binding);\n // A binding with no setup step was already reported when the Worker touched it.\n if (!setup) return { status: \"errored\", followUps: [] };\n const className = setup.className;\n // A callee's Workflow runs the callee's class with the callee's env, as the callee's code does.\n const callee = deps.calleeOf?.(binding);\n const cls = (callee?.exports ?? deps.exports)?.[className];\n const instance = registryFor(binding).instances.get(id);\n if (typeof cls !== \"function\" || !instance) {\n hooks.unsupported(\n callee\n ? `Workflow ${binding}: class ${className} is not among the exports of the callee ${callee.name}`\n : `Workflow ${binding}: class ${className} is not among the Worker module's exports; pass them as createCloudflarePlatform({ ..., exports })`,\n );\n return { status: \"errored\", followUps: [] };\n }\n return deliverWorkflow(event, hooks, {\n binding,\n ...(setup.name === undefined ? {} : { name: setup.name }),\n instance,\n cls,\n env: callee ? calleeEnv(callee.name, deps.env()) : deps.env(),\n maxFaultsPerRun: spec.bounds.maxFaultsPerRun,\n maxRedeliveries: spec.bounds.maxRedeliveries,\n });\n },\n };\n}\n\nexport interface CalleeDeps {\n /** The callees' modules by binding, as the test gives them. */\n readonly callees: Readonly<Record<string, CalleeModule>> | undefined;\n /** The scenario's env as the Worker sees it: the callee's env is a view of it under qualified names. */\n readonly env: () => object;\n}\n\n/**\n * A service binding whose callee runs for real (a `callee` setup step): a\n * stub running the callee's module inside each call. Never the real binding.\n * Nothing to reset or snapshot of its own: the callee's bindings have their\n * own steps under their qualified names. A binding without a `callee` step\n * is not this record's.\n */\nexport function calleeBinding(deps: CalleeDeps): Binding<object, CalleeSetup> {\n /** The bindings the current scenario names a callee for. */\n let setups = new Map<string, CalleeSetup>();\n const proxies = new Map<string, object>();\n const state = new CalleeState();\n return {\n kind: \"callee\",\n target: \"Service\",\n is: isServiceBinding,\n proxy(name, _real, ctx) {\n const setup = setups.get(name);\n if (!setup) return undefined;\n let p = proxies.get(name);\n if (!p) {\n const module = deps.callees?.[name];\n if (!module) {\n ctx.hooks.unsupported(\n `callee ${name}: the platform was not given its module; pass createCloudflarePlatform({ ..., callees: { ${name}: { name, exports } } }) (eutaxy check does not load callees yet)`,\n );\n // Never the real binding: a stub whose every call is reported.\n return proxyService(name, ctx, { kind: \"service\", binding: name, methods: {} });\n }\n p = proxyCallee(name, ctx, setup, module, deps.env(), state);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n setups = new Map();\n proxies.clear();\n state.clear();\n },\n async reset(step) {\n setups.set(step.binding, step);\n },\n async snapshot() {\n return null;\n },\n };\n}\n\n/**\n * A service binding: never the real binding, a stub answering from the\n * scenario's `service` setup; each call one effect. Nothing to reset or\n * snapshot, the callee is scripted.\n */\nexport function serviceBinding(): Binding<object, ServiceSetup> {\n /** The bindings the current scenario scripts. */\n let scripts = new Map<string, ServiceSetup>();\n /** Per binding, the stub for the current run's script. */\n const proxies = new Map<string, object>();\n return {\n kind: \"service\",\n target: \"Service\",\n is: isServiceBinding,\n proxy(name, _real, ctx) {\n const script = scripts.get(name);\n if (!script) {\n ctx.hooks.unsupported(\n `service binding ${name} needs a service() setup step scripting the Worker it reaches`,\n );\n // Never the real binding: it would call the real peer.\n return proxyService(name, ctx, { kind: \"service\", binding: name, methods: {} });\n }\n let p = proxies.get(name);\n if (!p) {\n p = proxyService(name, ctx, script);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n scripts = new Map();\n proxies.clear();\n },\n async reset(step) {\n scripts.set(step.binding, step);\n },\n async snapshot() {\n return null;\n },\n };\n}\n\n/**\n * The setup steps these records own, each with its record, in setup order:\n * what the platform resets and snapshots, and the differential runner\n * compares. A step no record owns is left to the scenario's validation.\n */\nexport function ownedSetups(\n setup: ScenarioSpec[\"setup\"],\n bindings: readonly Binding[],\n): readonly (readonly [Binding, BindingSetup])[] {\n const out: (readonly [Binding, BindingSetup])[] = [];\n for (const step of setup) {\n const binding = bindings.find((b) => b.kind === step.kind);\n if (binding) out.push([binding, step as BindingSetup]);\n }\n return out;\n}\n","/** Inbound HTTP delivery: one invocation per attempt of a request the drive's caller sends. */\n\nimport type { DeliveryResult, EventRef, JsonValue, RunHooks, ScenarioSpec } from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport { startCaller } from \"./caller.ts\";\nimport type { HttpDrive, HttpRequestSpec } from \"./scenario.ts\";\n\n/** The URL inbound requests are addressed to; handlers read only the path. */\nexport const requestOrigin = \"https://worker.test\";\n\n/** Build the `Request` a drive entry describes. */\nexport function requestFor(r: HttpRequestSpec): Request {\n const headers = new Headers(r.headers);\n let body: string | null = null;\n if (r.body !== undefined) {\n if (typeof r.body === \"string\") body = r.body;\n else {\n // Any JSON value, `null` included, travels as application/json.\n body = JSON.stringify(r.body);\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n }\n }\n return new Request(`${requestOrigin}${r.path}`, { method: r.method, headers, body });\n}\n\n/** A compact record of a response for the effect log: status, ok, and a bounded body. */\nexport async function summarizeResponse(response: Response): Promise<JsonValue> {\n const text = await response.clone().text();\n let body: JsonValue = text.length > 1000 ? `${text.slice(0, 1000)}…` : text;\n if (text && (response.headers.get(\"content-type\") ?? \"\").includes(\"json\")) {\n try {\n body = JSON.parse(text) as JsonValue;\n } catch {\n // keep the text\n }\n }\n return { status: response.status, ok: response.ok, body };\n}\n\n/** One attempt of an inbound request, under the caller's retry policy and deadline. */\nexport async function deliverRequest(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: HttpDrive,\n invocation: string,\n worker: RunningWorker,\n): Promise<DeliveryResult> {\n const req = event.data as unknown as HttpRequestSpec;\n const target = `Http:${req.path}`;\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n const handler = worker.handler.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n const args: JsonValue = { requestId: event.id, method: req.method, path: req.path };\n const caller = startCaller(event, hooks, spec, drive, target, {\n requestId: event.id,\n attempts: event.attempt,\n });\n\n const handled = await runInvocation(hooks, inv, () =>\n handler.call(worker.handler, requestFor(req), worker.env, executionContext(background)),\n );\n const response = handled.status === \"completed\" ? handled.value : undefined;\n let status: DeliveryResult[\"status\"] = handled.status;\n\n let summary: { status: number; ok: boolean } | null = null;\n let read: { status: number; ok: boolean; body: JsonValue } | \"crashed\" | \"errored\" = \"errored\";\n if (status === \"completed\" && response) {\n // The body is read before the point so the record is complete; the point itself is the send.\n // Streaming bodies run handler code: a crash inside it abandons the read, an error fails the delivery.\n const body = await runInvocation(hooks, inv, () => summarizeResponse(response));\n read =\n body.status === \"completed\"\n ? (body.value as { status: number; ok: boolean; body: JsonValue })\n : body.status;\n if (read === \"crashed\" || read === \"errored\") status = read;\n }\n let late = caller.isLate();\n const allowed = caller.responseFaults;\n if (status === \"completed\" && typeof read === \"object\") {\n const s = read;\n try {\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed },\n () => s,\n (v) => v,\n );\n summary = s;\n } catch (err) {\n if (err instanceof CrashSignal) status = \"crashed\";\n else if (err instanceof InjectedEffectError) {\n // Sent, but after the caller's deadline: the handler carries on, the caller resends.\n summary = s;\n late = true;\n } else throw err;\n }\n } else if (status === \"errored\") {\n // Cloudflare answers an uncaught exception with a 500 (workers runtime behaviour); the caller sees that.\n const s = { status: 500, ok: false, body: \"\" };\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed: [] },\n () => s,\n (v) => v,\n );\n summary = s;\n }\n\n const accepted =\n summary !== null && !late && (drive.retryOn === \"5xx\" ? summary.status < 500 : summary.ok);\n caller.settle(accepted, late);\n\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\n}\n","/** Queue delivery: one invocation per delivery of a message, redelivered until acked or dead-lettered. */\n\nimport {\n type DeliveryResult,\n decisionFaults,\n type EventRef,\n type JsonValue,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { CrashSignal, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport type { QueueDrive } from \"./scenario.ts\";\n\n/** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */\nfunction cloneJson(value: JsonValue): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n\n/** One delivery of a queue message, with Queues' at-least-once semantics. */\nexport async function deliverMessage(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: QueueDrive,\n invocation: string,\n worker: RunningWorker,\n maxRetries: number,\n): Promise<DeliveryResult> {\n const queueTarget = `Queue:${drive.queue}`;\n const inv = hooks.startInvocation(invocation);\n /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */\n const state: { decision: \"ack\" | \"retry\" | null } = { decision: null };\n const background: Promise<unknown>[] = [];\n\n /** Records the call; the result says whether it took effect (the first decision wins). */\n const decide = (op: \"ack\" | \"retry\", args: JsonValue): void => {\n hooks.effectSync(\n { invocation, target: queueTarget, op, args, allowed: decisionFaults },\n () => {\n if (state.decision !== null) return false;\n state.decision = op;\n return true;\n },\n (effective) => ({ effective }),\n );\n };\n const message: Message<unknown> = {\n id: event.id,\n timestamp: new Date(),\n body: cloneJson(event.data),\n attempts: event.attempt,\n ack: () => decide(\"ack\", { messageId: event.id, implicit: false, body: event.data }),\n retry: () => decide(\"retry\", { messageId: event.id, body: event.data }),\n };\n const batch: MessageBatch<unknown> = {\n queue: drive.queue,\n messages: [message],\n metadata: { metrics: { backlogCount: 0, backlogBytes: 0 } },\n ackAll: () => message.ack(),\n retryAll: () => message.retry(),\n };\n const execution = executionContext(background);\n\n const handler = worker.handler.queue;\n if (!handler) throw new Error(\"the Worker has no queue() handler\");\n let status: DeliveryResult[\"status\"] = (\n await runInvocation(hooks, inv, () =>\n handler.call(worker.handler, batch, worker.env, execution),\n )\n ).status;\n\n if (status === \"completed\" && state.decision === null) {\n try {\n decide(\"ack\", { messageId: event.id, implicit: true, body: event.data });\n } catch (err) {\n if (err instanceof CrashSignal) status = \"crashed\";\n else throw err;\n }\n }\n\n if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = \"crashed\";\n\n const followUps: EventRef[] = [];\n if (state.decision !== \"ack\") {\n const next = redelivery(event, maxRetries, spec.bounds);\n if (next) {\n followUps.push(next);\n } else {\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target: queueTarget,\n op: \"dead_letter\",\n args: { messageId: event.id, attempts: event.attempt },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n }\n return { status, followUps };\n}\n","/**\n * Cron Trigger delivery: one invocation of the Worker's `scheduled()` handler\n * per tick attempt, with `scheduledTime` the tick's virtual time and `cron`\n * the expression (Workers, Scheduled handler). Cloudflare documents\n * `noRetry()` but no retry count, so the drive declares how many times a\n * tick whose handler failed is re-run; `noRetry()` stops them.\n */\n\nimport {\n type DeliveryResult,\n decisionFaults,\n type EventRef,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport type { CronDrive } from \"./scenario.ts\";\n\n/** What a tick event carries: what the controller shows the handler. */\nexport interface TickData {\n readonly cron: string;\n readonly scheduledTime: number;\n}\n\n/** One attempt of a tick: the handler runs, and a failure is re-run as the drive declares unless it said noRetry(). */\nexport async function deliverTick(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: CronDrive,\n invocation: string,\n worker: RunningWorker,\n): Promise<DeliveryResult> {\n const tick = event.data as unknown as TickData;\n const target = `Cron:${drive.cron}`;\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n /** Rejections of waitUntil work: the first one is the invocation's status (Cloudflare, Scheduled handler). */\n const failures: unknown[] = [];\n const handler = worker.handler.scheduled;\n if (!handler) throw new Error(\"the Worker has no scheduled() handler\");\n let noRetry = false;\n const controller: ScheduledController = {\n scheduledTime: tick.scheduledTime,\n cron: tick.cron,\n // A decision the runtime honours, like a queue ack: a crash around it may lose or keep it.\n noRetry: () => {\n hooks.effectSync(\n { invocation, target, op: \"no_retry\", args: { tick: event.id }, allowed: decisionFaults },\n () => {\n noRetry = true;\n return null;\n },\n () => null,\n );\n },\n };\n let status: DeliveryResult[\"status\"] = (\n await runInvocation(hooks, inv, () =>\n handler.call(worker.handler, controller, worker.env, executionContext(background, failures)),\n )\n ).status;\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n if (status === \"completed\" && failures.length > 0) status = \"errored\";\n\n const followUps: EventRef[] = [];\n if (status !== \"completed\" && !noRetry) {\n // The re-run is the same tick: same scheduledTime, next attempt.\n const next = redelivery(event, drive.retries, spec.bounds);\n if (next) followUps.push(next);\n else\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target,\n op: \"gave_up\",\n args: { tick: event.id, attempts: event.attempt },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n return { status, followUps };\n}\n","/**\n * WebSocket connections as events. The scenario opens a connection with an\n * upgrade request through the Worker's fetch handler, as a client would;\n * the Worker hands it to a Durable Object (the Agents SDK's router does),\n * whose fetch answers 101, and Eutaxy keeps the client end. Each message is\n * then one event delivered inside the object, by calling its\n * `webSocketMessage` handler (the Hibernation API; the Agents SDK uses it)\n * on the server end of that connection, as an alarm is delivered by calling\n * `alarm()`, with the faults an alarm has: `crash_before` (the object\n * crashed before handling it), `crash_after` (handled, then crashed) and\n * `error` (the handler threw). A crash drops the instance, rebuilt within\n * the same delivery since no retry follows a message; the runtime keeps\n * a hibernatable connection, as it does across hibernation, and the next\n * instance sees it under a new `WebSocket` identity with its attachment and\n * tags, so before each message the connection's server end is found again\n * in the live object: by identity, else by attachment and tags (the object\n * must give them to tell its connections apart; otherwise the run is\n * `UNSUPPORTED`). A message is an event of its own, so the scheduler\n * interleaves connections; it waits for its connection to be open and for\n * the message before it on that connection. One the object closed is\n * recorded as not delivered. What the object sends back arrives on the\n * client end; the frames are kept per connection in arrival order and\n * recorded at the end of the run as effects (`WebSocket:<connection>`, op\n * `message`, under the platform's own invocation), since when a frame\n * crosses the pair depends on the event loop, not on the schedule, and a\n * trace must repeat. A close the object makes during the run is recorded\n * too (op `close`). After the run's snapshot the connections still open are\n * torn down outside the run: what the objects' `webSocketClose` handlers\n * do then is not modelled (a request made then makes the run UNSUPPORTED).\n */\n\nimport {\n canonicalJson,\n type DeliveryResult,\n type EventRef,\n invocationOf,\n type JsonValue,\n type RunHooks,\n readFaults,\n type ScenarioSpec,\n toJson,\n} from \"@eutaxy/core\";\nimport { realTick, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport type { ObjectAccess } from \"./bindings.ts\";\nimport { requestOrigin } from \"./http.ts\";\nimport type { WebSocketConnectionSpec, WebSocketDrive, WebSocketEventData } from \"./scenario.ts\";\n\n/** The object a connection reached, as the stub proxy saw its 101: the invocation whose stub call it was, and the client end. */\nexport interface UpgradeInfo {\n readonly binding: string;\n readonly id: string;\n readonly object: string;\n readonly invocation: string;\n readonly client: WebSocket;\n}\n\n/**\n * Drop a client end nobody will use, so the object sees the connection close\n * (as it does when a Worker dies holding one). An end must be accepted before\n * it can be closed; one left unaccepted stays in the object for ever and\n * keeps its instance from being evicted.\n */\nfunction dropEnd(ws: WebSocket, reason: string): void {\n try {\n ws.accept();\n } catch {\n // accepted already\n }\n try {\n ws.close(1011, reason);\n } catch {\n // closed already\n }\n}\n\n/** How the object closed a connection (its handler called `close`), as the client end saw it. */\nexport interface Closed {\n readonly code: number;\n readonly reason: string;\n}\n\ninterface Connection {\n readonly spec: WebSocketConnectionSpec;\n readonly client: WebSocket;\n /** The server end as the object last saw it; a dropped instance leaves a new identity behind. None when the object closed the connection before answering the upgrade. */\n server: WebSocket | undefined;\n /** The tags and the attachment the object gave the server end, as last seen; both survive the instance. */\n identity: Identity;\n readonly upgrade: UpgradeInfo;\n closed: Closed | undefined;\n}\n\n/** A promise settled from outside, for one connection's open and for each message's turn. */\nclass Gate {\n readonly promise: Promise<void>;\n resolve: () => void = () => {};\n constructor() {\n this.promise = new Promise((r) => {\n this.resolve = r;\n });\n }\n}\n\n/** What identifies a server end across instances: its tags (fixed at accept) and its attachment (the object may change it). */\ninterface Identity {\n readonly tags: string;\n readonly attachment: string;\n}\n\nfunction identityOf(ws: WebSocket, live: DurableObjectState): Identity {\n let attachment: JsonValue;\n try {\n attachment = toJson(ws.deserializeAttachment());\n } catch {\n attachment = \"<unreadable>\";\n }\n let tags: string[] = [];\n try {\n tags = live.getTags(ws);\n } catch {\n // not accepted with the Hibernation API: no tags\n }\n return { tags: canonicalJson(tags), attachment: canonicalJson(attachment) };\n}\n\n/** Turns of the event loop the teardown waits for the objects to let their connections go. */\nconst closeTurns = 20;\n\n/** The run's connections; the platform clears it before each run, closing what is still open. */\nexport class Connections {\n readonly open = new Map<string, Connection>();\n /** Per connection: settled once its open was delivered, whatever came of it. */\n readonly opened = new Map<string, Gate>();\n /** Per connection and message index: settled once that message was delivered. */\n readonly delivered = new Map<string, Gate>();\n /** The frames each connection received this run, in arrival order, until the end of the run records them. */\n readonly frames = new Map<string, JsonValue[]>();\n /** Every 101 a stub fetch answered this run, as the proxy saw it; an open claims its own, the rest are dropped. */\n readonly upgrades: { readonly info: UpgradeInfo; claimed: boolean }[] = [];\n\n gate(map: Map<string, Gate>, key: string): Gate {\n let g = map.get(key);\n if (!g) {\n g = new Gate();\n map.set(key, g);\n }\n return g;\n }\n\n /** Resolves once the connection's open was delivered (it may have failed: `open` then lacks it). */\n openedOf(connection: string): Promise<void> {\n return this.gate(this.opened, connection).promise;\n }\n\n /** Resolves once message `index` of the connection was delivered; index -1 is at once. */\n deliveredOf(connection: string, index: number): Promise<void> {\n return index < 0\n ? Promise.resolve()\n : this.gate(this.delivered, `${connection}:${index}`).promise;\n }\n\n /** Closes that reached a client end before its connection was registered: the object closed it while answering the upgrade. */\n readonly earlyClosed = new Map<string, Closed>();\n /** Counts the runs, so what a client end of an earlier run reports after its teardown is ignored. */\n generation = 0;\n\n received(generation: number, connection: string, data: JsonValue): void {\n if (generation !== this.generation) return;\n const list = this.frames.get(connection);\n if (list) list.push(data);\n else this.frames.set(connection, [data]);\n }\n\n /** The client end saw a close during the run: the object closed the connection. */\n closedBy(generation: number, connection: string, code: number, reason: string): void {\n if (generation !== this.generation) return;\n const c = this.open.get(connection);\n if (c) {\n if (!c.closed) c.closed = { code, reason };\n } else if (!this.earlyClosed.has(connection))\n this.earlyClosed.set(connection, { code, reason });\n }\n\n upgradedTo(info: UpgradeInfo): void {\n this.upgrades.push({ info, claimed: false });\n }\n\n /** The object this open reached: a stub fetch of its own invocation answered 101 during it. Claimed once. */\n upgraded(invocation: string): UpgradeInfo | undefined {\n const u = this.upgrades.find((x) => !x.claimed && x.info.invocation === invocation);\n if (u) u.claimed = true;\n return u?.info;\n }\n\n /** Drop the client ends no open claimed: an open that crashed after the object accepted, or an upgrade made elsewhere. */\n dropUnclaimed(reason: string): boolean {\n let dropped = false;\n for (const u of this.upgrades) {\n if (u.claimed) continue;\n u.claimed = true;\n dropEnd(u.info.client, reason);\n dropped = true;\n }\n return dropped;\n }\n\n /**\n * Inside an object: bind its open connections to the sockets it holds now.\n * A connection whose server end is still there keeps it; one whose instance\n * was dropped since finds it again by its tags, or by tags and attachment\n * when the tags alone do not single it out. What comes back:\n * the sockets no connection holds (a new one during an open), and the\n * connections that could not be told apart.\n */\n rebind(\n upgrade: Pick<UpgradeInfo, \"binding\" | \"id\">,\n live: DurableObjectState,\n ): { readonly unbound: readonly WebSocket[]; readonly lost: readonly Connection[] } {\n const free = new Set(live.getWebSockets());\n const stale: Connection[] = [];\n for (const c of this.open.values()) {\n if (c.upgrade.binding !== upgrade.binding || c.upgrade.id !== upgrade.id || c.closed)\n continue;\n if (c.server && free.has(c.server)) {\n free.delete(c.server);\n // The object may have rewritten the attachment since: what identifies the end is what it holds now.\n c.identity = identityOf(c.server, live);\n } else stale.push(c);\n }\n const lost: Connection[] = [];\n const identities = new Map([...free].map((ws) => [ws, identityOf(ws, live)] as const));\n const single = (ok: (i: Identity) => boolean): WebSocket | undefined => {\n const matches = [...free].filter((ws) => ok(identities.get(ws) as Identity));\n return matches.length === 1 ? matches[0] : undefined;\n };\n for (const c of stale) {\n const ws =\n single((i) => i.tags === c.identity.tags) ??\n single((i) => i.tags === c.identity.tags && i.attachment === c.identity.attachment);\n if (ws) {\n c.server = ws;\n free.delete(ws);\n } else lost.push(c);\n }\n return { unbound: [...free], lost };\n }\n\n /**\n * After the run's snapshot: close what is still open and wait until each\n * object has let its connections go, so nothing survives into the next run\n * (a hibernatable socket outlives eviction and `deleteAll`). The objects'\n * `webSocketClose` handlers run meanwhile, outside the run: nothing they\n * do is observed. Returns why, when an object still holds a socket.\n */\n async teardown(objects: ObjectAccess): Promise<string | undefined> {\n this.dropUnclaimed(\"the Worker died holding this connection\");\n const reached = new Map<string, UpgradeInfo>();\n for (const c of this.open.values()) {\n reached.set(`${c.upgrade.binding}/${c.upgrade.id}`, c.upgrade);\n if (c.closed) continue;\n try {\n c.client.close(1000, \"run over\");\n } catch {\n // the other side closed first; its close reaches the client end on its way\n }\n }\n for (const u of reached.values()) {\n let left = 0;\n for (let turn = 0; turn < closeTurns; turn++) {\n left =\n (await objects.run(\n u.binding,\n u.id,\n u.object,\n async (_i, live) => live.getWebSockets().length,\n )) ?? 0;\n if (left === 0) break;\n await realTick();\n }\n if (left !== 0)\n return `WebSocket connections of ${u.object} were still open ${closeTurns} turns of the event loop after the run closed them`;\n }\n return undefined;\n }\n\n /** Record every connection's frames (connection order, then arrival order) and the close the object made, if any; forget the frames. */\n record(hooks: RunHooks): void {\n const bookkeeping = () => hooks.bookkeeping();\n for (const [connection, c] of this.open) {\n for (const data of this.frames.get(connection) ?? [])\n hooks.effectSync(\n {\n invocation: bookkeeping(),\n target: `WebSocket:${connection}`,\n op: \"message\",\n args: { connection, data },\n allowed: [],\n },\n () => null,\n () => null,\n );\n if (c.closed)\n hooks.effectSync(\n {\n invocation: bookkeeping(),\n target: `WebSocket:${connection}`,\n op: \"close\",\n args: { connection, code: c.closed.code, reason: c.closed.reason },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n this.frames.clear();\n }\n\n /** Before a run: close what the last run left open (it ended early), and let the closes cross before the objects are evicted. */\n async clear(): Promise<void> {\n this.generation++;\n let closing = this.dropUnclaimed(\"run over\");\n for (const c of this.open.values()) {\n if (c.closed) continue;\n closing = true;\n try {\n c.client.close(1000, \"run over\");\n } catch {\n // already closed by the other side\n }\n }\n this.open.clear();\n this.frames.clear();\n this.earlyClosed.clear();\n this.opened.clear();\n this.delivered.clear();\n this.upgrades.length = 0;\n if (closing) await settleFrames();\n }\n}\n\n/** The upgrade request a connection opens with. */\nexport function upgradeRequest(c: WebSocketConnectionSpec): Request {\n const headers = new Headers(c.headers);\n headers.set(\"Upgrade\", \"websocket\");\n headers.set(\"Connection\", \"Upgrade\");\n return new Request(`${requestOrigin}${c.path}`, { headers });\n}\n\n/** A frame's data as recorded: JSON where it parses, the text otherwise. */\nexport function frameData(data: unknown): JsonValue {\n const text = typeof data === \"string\" ? data : \"<binary>\";\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n return text;\n }\n}\n\n/** The text a message is sent as: a string as is, any other JSON value as its JSON. */\nexport function frameText(data: JsonValue): string {\n return typeof data === \"string\" ? data : JSON.stringify(data);\n}\n\n/** Two turns of the real event loop: what a frame, or a close, needs to cross from one end of the pair to the other. */\nasync function settleFrames(): Promise<void> {\n await realTick();\n await realTick();\n}\n\nexport interface WebSocketDeps {\n readonly worker: RunningWorker;\n readonly connections: Connections;\n readonly objects: ObjectAccess;\n}\n\nexport async function deliverWebSocket(\n event: EventRef,\n hooks: RunHooks,\n _spec: ScenarioSpec,\n drive: WebSocketDrive,\n deps: WebSocketDeps,\n): Promise<DeliveryResult> {\n const data = event.data as unknown as WebSocketEventData;\n const c = drive.connections.find((x) => x.id === data.connection);\n if (!c) throw new Error(`websocket drive has no connection ${data.connection}`);\n switch (data.kind) {\n case \"open\":\n try {\n return await openConnection(event, hooks, drive, c, deps);\n } finally {\n deps.connections.gate(deps.connections.opened, c.id).resolve();\n }\n case \"message\":\n try {\n return await deliverMessage(event, hooks, c, data, deps);\n } finally {\n deps.connections.gate(deps.connections.delivered, `${c.id}:${data.index}`).resolve();\n }\n }\n}\n\n/** What an open finds in the object: this connection's server end, or why there is none. */\ntype Found =\n | { readonly server: WebSocket; readonly identity: Identity }\n | { readonly unbound: readonly WebSocket[]; readonly lost: readonly Connection[] };\n\nasync function openConnection(\n event: EventRef,\n hooks: RunHooks,\n drive: WebSocketDrive,\n c: WebSocketConnectionSpec,\n deps: WebSocketDeps,\n): Promise<DeliveryResult> {\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const target = `WebSocket:${c.id}`;\n const background: Promise<unknown>[] = [];\n const handler = deps.worker.handler.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n const position = drive.connections.findIndex((x) => x.id === c.id);\n const previous = drive.connections[position - 1];\n // Opens run one at a time, in order, so the socket an object accepts during this one is this\n // connection's; the wait is this invocation's, which the scheduler can see and abandon. Messages are\n // not held back this way.\n const handled = await runInvocation(hooks, inv, async () => {\n if (previous) await deps.connections.openedOf(previous.id);\n return handler.call(\n deps.worker.handler,\n upgradeRequest(c),\n deps.worker.env,\n executionContext(background),\n );\n });\n let status: DeliveryResult[\"status\"] = handled.status;\n const response = handled.status === \"completed\" ? handled.value : undefined;\n const args: JsonValue = { connection: c.id, path: c.path };\n if (status === \"completed\" && response) {\n const r = response;\n // The open as one effect: the answer, and, on a 101, the client end accepted and the server end\n // found in the object. The waits inside are I/O of this invocation, which the scheduler sees.\n const opened = await runInvocation(hooks, inv, () =>\n hooks.effect(\n { invocation, target, op: \"open\", args, allowed: [], hostsEffects: true },\n async () => {\n const summary = { status: r.status, ok: r.status === 101 };\n if (r.status !== 101 || !r.webSocket) return summary;\n const client = r.webSocket;\n const upgrade = deps.connections.upgraded(invocation);\n if (!upgrade) {\n hooks.unsupported(\n `WebSocket ${c.id}: the Worker answered the upgrade itself; only connections a Durable Object accepts are modelled`,\n );\n dropEnd(client, \"not modelled\");\n return summary;\n }\n // Kept, not recorded: when a frame crosses the pair is the event loop's doing, so the end of\n // the run records them in arrival order. A close the object makes is kept the same way.\n const generation = deps.connections.generation;\n client.addEventListener(\"message\", (ev: MessageEvent) => {\n deps.connections.received(generation, c.id, frameData(ev.data));\n });\n client.addEventListener(\"close\", (ev: CloseEvent) => {\n deps.connections.closedBy(generation, c.id, ev.code, ev.reason);\n });\n client.accept();\n await settleFrames();\n // Closed by the object while it answered the upgrade: open and closed at once, nothing to send on.\n const early = deps.connections.earlyClosed.get(c.id);\n if (early) {\n deps.connections.open.set(c.id, {\n spec: c,\n client,\n server: undefined,\n identity: { tags: \"[]\", attachment: \"null\" },\n upgrade,\n closed: early,\n });\n return summary;\n }\n // The server end: the one socket the object holds that no connection does.\n const found = await deps.objects.run(\n upgrade.binding,\n upgrade.id,\n upgrade.object,\n async (_i, live): Promise<Found> => {\n const { unbound, lost } = deps.connections.rebind(upgrade, live);\n const server = unbound[0];\n if (lost.length > 0 || unbound.length !== 1 || !server) return { unbound, lost };\n return { server, identity: identityOf(server, live) };\n },\n );\n if (!found || !(\"server\" in found)) {\n // Accepted above: closing it from here reaches the object.\n client.close(1011, \"not modelled\");\n const lost = found?.lost ?? [];\n const n = found?.unbound.length ?? 0;\n hooks.unsupported(\n lost.length > 0\n ? `WebSocket ${c.id}: the connections ${lost.map((l) => l.spec.id).join(\", \")} of ${upgrade.object} cannot be told apart after its instance was dropped; give each socket an attachment or a tag`\n : `WebSocket ${c.id}: ${n === 0 ? \"the object accepted no WebSocket with the Hibernation API (ctx.acceptWebSocket); the standard API is not modelled\" : `${n} sockets were accepted by ${upgrade.object} during this open, so this connection's cannot be told apart`}`,\n );\n return summary;\n }\n deps.connections.open.set(c.id, {\n spec: c,\n client,\n server: found.server,\n identity: found.identity,\n upgrade,\n closed: undefined,\n });\n return summary;\n },\n (v) => v,\n ),\n );\n if (opened.status !== \"completed\") status = opened.status;\n } else {\n // The Worker did not answer: an object it reached meanwhile sees its connection close, as when a\n // Worker dies holding one. An uncaught exception is answered with a 500; so is the connection's open.\n const upgrade = deps.connections.upgraded(invocation);\n // The runtime hands the object the close before any later call reaches it (events enter an\n // object in arrival order), so the snapshot sees what webSocketClose wrote.\n if (upgrade) dropEnd(upgrade.client, \"the Worker died during the upgrade\");\n if (status === \"errored\")\n hooks.effectSync(\n { invocation, target, op: \"open\", args, allowed: [] },\n () => ({ status: 500, ok: false }),\n (v) => v,\n );\n }\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\n}\n\nasync function deliverMessage(\n event: EventRef,\n hooks: RunHooks,\n c: WebSocketConnectionSpec,\n data: Extract<WebSocketEventData, { kind: \"message\" }>,\n deps: WebSocketDeps,\n): Promise<DeliveryResult> {\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const target = `WebSocket:${c.id}`;\n // Its connection must be open and the message before it handled. Waited for as a run of this\n // invocation, which the scheduler can see and abandon; the effect then starts in a run of its own,\n // so this invocation is the one running when the object's handler makes its effects.\n const waited = await runInvocation(hooks, inv, async () => {\n await Promise.all([\n deps.connections.openedOf(c.id),\n deps.connections.deliveredOf(c.id, data.index - 1),\n ]);\n return null;\n });\n if (waited.status !== \"completed\") return { status: waited.status, followUps: [] };\n const conn = deps.connections.open.get(c.id);\n const args: JsonValue = {\n connection: c.id,\n object: conn?.upgrade.object ?? null,\n message: data.message,\n data: data.data,\n };\n // Nothing to send on: the open failed or was refused, or the object closed the connection since.\n const server = conn?.server;\n if (!conn || conn.closed || !server) {\n hooks.effectSync(\n { invocation, target, op: \"send\", args, allowed: [] },\n () => ({ delivered: false }),\n (v) => v,\n );\n return { status: \"completed\", followUps: [] };\n }\n const { binding, id, object } = conn.upgrade;\n const { status } = await runInvocation(hooks, inv, () =>\n hooks.effect(\n { invocation, target, op: \"send\", args, allowed: readFaults, hostsEffects: true },\n async () => {\n await deps.objects.run(binding, id, object, async (instance, live) => {\n // A dropped instance left the connection's server end under a new identity: find it again.\n const { lost } = deps.connections.rebind(conn.upgrade, live);\n if (lost.includes(conn)) {\n hooks.unsupported(\n `WebSocket ${c.id}: the connections ${lost.map((l) => l.spec.id).join(\", \")} of ${object} cannot be told apart after its instance was dropped; give each socket an attachment or a tag`,\n );\n return;\n }\n // The runtime would answer these without waking the object; delivering to the handler would not.\n if (live.getWebSocketAutoResponse()) {\n hooks.unsupported(\n `Durable Object ${binding} ${object} uses setWebSocketAutoResponse, which is not modelled`,\n );\n return;\n }\n const handler = (instance as { webSocketMessage?: unknown }).webSocketMessage;\n if (typeof handler !== \"function\") {\n hooks.unsupported(\n `Durable Object ${binding} ${object} has no webSocketMessage handler; only the Hibernation API is modelled`,\n );\n return;\n }\n const end = conn.server ?? server;\n await (handler as (ws: WebSocket, m: string) => Promise<unknown>).call(\n instance,\n end,\n frameText(data.data),\n );\n // The handler may have rewritten the attachment: keep what identifies the end current.\n conn.identity = identityOf(end, live);\n });\n // The frames the object sent back, or its close, cross to the client end now.\n await settleFrames();\n return { delivered: true };\n },\n (v) => v,\n {\n onAbandon: () => deps.objects.abort(binding, id),\n mayPark: () => deps.objects.mayPark(binding, id),\n },\n ),\n );\n // A crash is the object's: its in-memory state goes with the instance; the connection stays. No\n // retry follows a message, so the instance is rebuilt here, within the run, where its constructor\n // is observed (an alarm's retry does that for an alarm); an object rebuilt only for the snapshot\n // would make the run UNSUPPORTED.\n if (status === \"crashed\") {\n await deps.objects.evict(binding, id);\n // An effect of a run of its own (the crashed invocation is over), so the scheduler sees the\n // wait and the constructor's effects have an invocation.\n const rebuild = hooks.startInvocation(`${invocation}/rebuild`);\n await runInvocation(hooks, rebuild, () =>\n hooks.effect(\n {\n invocation: rebuild.id,\n target,\n op: \"rebuild\",\n args: { connection: c.id, object },\n allowed: [],\n hostsEffects: true,\n },\n async () => {\n await deps.objects.run(binding, id, object, async () => undefined);\n return null;\n },\n () => null,\n ),\n );\n }\n return { status, followUps: [] };\n}\n","/**\n * The Cloudflare platform: delivers queue messages to the Worker's `queue()`\n * handler and inbound requests to its `fetch()` handler, with proxied\n * bindings, and applies Queues' at-least-once semantics (explicit and\n * implicit ack, retry, redelivery up to max_retries, dead-lettering) as\n * documented by Cloudflare, and for requests the caller's retry policy\n * declared in the drive.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n invocationOf,\n type Platform,\n type RunHooks,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { withoutNetwork } from \"@eutaxy/engine\";\nimport type { RunningWorker } from \"./background.ts\";\nimport {\n type Binding,\n calleeBinding,\n d1Binding,\n durableObjectBinding,\n ownedSetups,\n r2Binding,\n serviceBinding,\n workflowBinding,\n} from \"./bindings.ts\";\nimport type { CalleeModule } from \"./callees.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\nimport type { DurableObjectTestHelpers } from \"./durable-objects.ts\";\nimport { deliverRequest } from \"./http.ts\";\nimport { deliverMessage } from \"./queues.ts\";\nimport { deliverCall, entrypointClass } from \"./rpc.ts\";\nimport { type Drive, driveEvents, restrictDrive } from \"./scenario.ts\";\nimport { deliverTick } from \"./scheduled.ts\";\nimport { Connections, deliverWebSocket } from \"./websocket.ts\";\n\n/** The Worker's default export, as far as the platform drives it. */\nexport interface WorkerHandler {\n queue?(batch: MessageBatch<unknown>, env: unknown, ctx: ExecutionContext): void | Promise<void>;\n fetch?(request: Request, env: unknown, ctx: ExecutionContext): Response | Promise<Response>;\n scheduled?(\n controller: ScheduledController,\n env: unknown,\n ctx: ExecutionContext,\n ): void | Promise<void>;\n}\n\n/** A `WorkerEntrypoint` subclass: the Worker's default export when it exposes RPC methods. Its env is its own. */\nexport type WorkerEntrypointClass = abstract new (ctx: ExecutionContext, env: never) => object;\n\nexport interface CloudflarePlatformOptions {\n /** The bindings from `cloudflare:workers`. */\n readonly env: object;\n /**\n * The Worker's default export: the handler object, or the\n * `WorkerEntrypoint` class the `rpc` drive calls (its own `fetch()`\n * method is not driven by `http()` yet).\n */\n readonly handler: WorkerHandler | WorkerEntrypointClass;\n /** Schema SQL per D1 binding named in the scenario's setup. */\n readonly schemas: Readonly<Record<string, string>>;\n /** Cloudflare's default when the consumer does not set max_retries. */\n readonly maxRetries?: number;\n /**\n * The Cloudflare Vitest plugin's test helpers (`import * as helpers from\n * \"cloudflare:test\"`), needed for Durable Object bindings: Eutaxy resets,\n * seeds and snapshots the real objects through them.\n */\n readonly durableObjects?: DurableObjectTestHelpers;\n /**\n * The Worker module's exports (`import * as worker from \"./worker.ts\"`),\n * where the classes `workflow` setup steps name are found.\n */\n readonly exports?: Readonly<Record<string, unknown>>;\n /**\n * The Workers behind service bindings that `callee` setup steps name, by\n * binding: each one's name from its wrangler config, which qualifies its\n * bindings in `env` (`orders/DB`), and its module's exports.\n */\n readonly callees?: Readonly<Record<string, CalleeModule>>;\n /**\n * Bindings that name a resource another binding already names (the same\n * database, the same Durable Object namespace), by their qualified name\n * (`inventory/DB`) to the name the resource is set up and snapshotted\n * under (`DB`): one resource, one snapshot, the alias a second name for it\n * in `env`. A setup step on an alias is refused.\n */\n readonly aliases?: Readonly<Record<string, string>>;\n}\n\nfunction isBindingLike(value: unknown): boolean {\n if (typeof value === \"function\") return true;\n if (typeof value !== \"object\" || value === null) return false;\n const proto = Object.getPrototypeOf(value) as object | null;\n const names = [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})];\n return names.some(\n (k) => k !== \"constructor\" && typeof (value as Record<string, unknown>)[k] === \"function\",\n );\n}\n\nconst assumptions: readonly string[] = [\n \"platform model: Cloudflare Queues at-least-once delivery; the first ack or retry decision per message wins; unacked messages are redelivered up to max_retries then dead-lettered\",\n \"D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect\",\n \"message.timestamp is the virtual clock's time at delivery\",\n \"only D1, Durable Object, R2, Workflow and scripted service bindings are proxied; touching any other binding makes the run UNSUPPORTED\",\n \"service bindings are scripted callees unless the scenario names a callee for them: the Worker behind a scripted binding is never called; each RPC method call or fetch() through it is one effect answered from the scenario's service() setup, where crash_before and error mean the call never reached the callee, ambiguous that it acted and the answer was lost, and crash_after that the caller died after it (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/); Cloudflare does not retry such a call\",\n \"a binding named as an alias of another (the same database, the same Durable Object namespace, in two Workers' configs) is that binding: its effects and snapshot carry the other's name, and a callee's Workflow runs the callee's class with the callee's env\",\n \"a service binding with a callee() setup runs that Worker's real code in the caller's simulation, in the same isolate, as Cloudflare runs both Workers on one thread (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/): each RPC method call or fetch() through it is one effect hosting the callee's invocation (<caller invocation>/<binding>.<method>), which constructs the entrypoint anew with a fresh ExecutionContext and the callee's env (its bindings under <worker name>/<binding>) and answers with the return value, plain data by copy, or the Response as it is; what the callee throws reaches the caller as a new error with its name, message and serializable own properties, a built-in class as itself (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); the callee's waitUntil work finishes before its answer crosses; crash_before means the call never reached the callee, ambiguous that it acted and the answer was lost, crash_after that the caller died after it, and a fault that crashes the callee ends its invocation and throws an Error to the caller; Cloudflare retries nothing\",\n \"R2 buckets are Miniflare's real ones, emptied and seeded before each run and snapshotted after it; R2 is strongly consistent and the last writer wins (developers.cloudflare.com/r2/reference/consistency/); each put, delete, get, head and list is one effect, a body is read inside its get, and an object's version and upload time are stand-ins so traces repeat; multipart uploads and conditions on the upload time are not modelled\",\n \"Durable Objects are the real objects workerd runs (storage, transactions, input and output gates are the runtime's own); each stub call is one effect: crash_before or error means it never reached the object, ambiguous means the object committed and the caller lost the answer, crash_after means the caller died after it; in a concurrent run an object's own outbound I/O during a call is a turn, so another event may enter the object meanwhile (its input gate is open then), except while it holds the gate with blockConcurrencyWhile, when its effects run at once; storage operations are not turns (the input gate holds other events during them); the object's own binding calls are not recorded; objects are cleared, seeded and evicted before each run and their storage is snapshotted after it (developers.cloudflare.com/durable-objects/api/storage-api/)\",\n \"Durable Object alarms are taken over so none is scheduled on the real clock and fire in virtual time: one alarm per object, a later setAlarm replaces it, setAlarm in a transaction applies on commit, the alarm survives eviction, alarm() is one effect (crash_before: it never ran; crash_after: it ran and counts as failed; error: it threw), and a failed alarm is retried after 2 s, 4 s, 8 s ... up to six retries and maxRedeliveries, with retryCount and isRetry (developers.cloudflare.com/durable-objects/api/base/#alarm); each object's alarm fires at most alarmsPerObject times per run (default 3)\",\n \"Workflows are a model of the engine, never the local one, running the scenario's own class: create is one effect that queues the instance; each step.do attempt is two effect points around its callback, which runs as the instance's own code (step, crash_before: the engine restarts before it; step_result, crash_after: it ran and committed but its result was not persisted, so it runs again; ambiguous: the attempt ran but counted as failed, as a timeout does); a failed attempt is retried after its delay in virtual time (defaults 5 retries, 10 s, exponential, merged field by field with a step's config), up to its limit and maxRedeliveries, except a NonRetryableError; a restart re-runs run() from the start with the persisted step and sleep results, so code outside steps repeats; step timeouts are not measured (developers.cloudflare.com/workflows/build/rules-of-workflows/, /workflows/build/sleeping-and-retrying/)\",\n \"state invariants read a snapshot of every D1 binding named in setup, taken after the last event\",\n \"work passed to ctx.waitUntil runs after the handler returns and never affects acknowledgement or the response; a cut_off fault at that point loses work not yet started, and an effect in flight commits without its continuation\",\n \"concurrent invocations (maxConcurrentInvocations above 1) share one isolate's module state and bindings, and another may run while one awaits I/O (developers.cloudflare.com/workers/reference/how-workers-works/); queue consumers run concurrently up to max_concurrency (developers.cloudflare.com/queues/configuration/consumer-concurrency/)\",\n \"inbound requests: one invocation per attempt; an uncaught exception is a 500 response; the drive's caller resends a request it got no acceptable response for (crash before the response, an answer after its deadlineMs, or a status its retryOn policy rejects) up to its retries, each resend after its delaysMs entry of virtual time; the handler's own time is virtual, so a late answer is the ambiguous fault at the response point or an answer later than deadlineMs in virtual time\",\n \"cron triggers: each tick of the drive's expression is one invocation of scheduled(), with scheduledTime the tick's virtual time (UTC, the expression's matches from the virtual epoch on, in Cloudflare's dialect where weekdays run 1 = Sunday to 7 = Saturday; L, W and # are not modelled) and cron the expression (developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/, /workers/configuration/cron-triggers/); Cloudflare documents noRetry() but no retry count, so the drive declares how many times a tick whose handler failed is re-run, and none after noRetry()\",\n \"inbound RPC: one invocation per call attempt, the entrypoint constructed anew for each with a fresh ExecutionContext (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/); the return value is the response effect, and an exception reaches the caller as a new error with its name and message (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); Cloudflare does not retry a call, so the drive's caller resends a call that threw or got no answer as the http drive's caller does; a result that is not plain data (a stub, a function, a stream) makes the run UNSUPPORTED\",\n];\n\nexport function createCloudflarePlatform(options: CloudflarePlatformOptions): Platform {\n const env = options.env as Record<string, unknown>;\n const aliases = options.aliases ?? {};\n /** The name a binding is known by: itself, or the name it is an alias of. */\n const canonical = (name: string): string => aliases[name] ?? name;\n const maxRetries = options.maxRetries ?? 3;\n let hooksRef: RunHooks | null = null;\n\n const connections = new Connections();\n const ctx: ProxyContext = {\n get hooks() {\n if (!hooksRef) throw new Error(\"no run in progress\");\n return hooksRef;\n },\n // Bindings are shared by every invocation in flight; the engine knows which one is running.\n currentInvocation: () => ctx.hooks.running(),\n onUpgrade: (info) => connections.upgradedTo(info),\n };\n\n /**\n * The kinds of binding modelled, in the order an env value is tried against\n * them: service bindings first (a callee's, then scripted), since in workerd\n * they answer every duck type (their property reads are RPC stubs).\n */\n const durable = durableObjectBinding({\n ctx,\n helpers: options.durableObjects,\n real: (name) => env[name],\n });\n const bindings: readonly Binding[] = [\n calleeBinding({ callees: options.callees, env: () => proxiedEnv }),\n serviceBinding(),\n d1Binding(options.schemas),\n durable,\n r2Binding(),\n workflowBinding({\n exports: options.exports,\n env: () => proxiedEnv,\n // A qualified binding's callee: the Worker whose name qualifies it.\n calleeOf: (binding) => {\n const at = binding.indexOf(\"/\");\n if (at < 0) return undefined;\n const name = binding.slice(0, at);\n return Object.values(options.callees ?? {}).find((c) => c.name === name);\n },\n }),\n ];\n // The Cloudflare Vitest plugin adds bindings of its own to env (its loopback and self services, its\n // runner object); a Worker that walks env (the Agents SDK's router does, to name each namespace) must\n // not meet them: they are the test environment's, not the Worker's.\n const own = (prop: string | symbol): boolean =>\n typeof prop !== \"string\" || !prop.startsWith(\"__VITEST_POOL_WORKERS_\");\n // An alias is read as the binding it names, so effects and snapshots carry that binding's name.\n const aliasKeys = Object.keys(aliases).filter((a) => canonical(a) in env);\n const proxiedEnv = new Proxy(env, {\n get(target, prop, receiver) {\n if (!own(prop)) return undefined;\n if (typeof prop !== \"string\") return Reflect.get(target, prop, receiver) as unknown;\n const name = canonical(prop);\n const value = Reflect.get(target, name, receiver) as unknown;\n for (const binding of bindings) {\n if (!binding.is(value)) continue;\n const proxied = binding.proxy(name, value, ctx);\n if (proxied !== undefined) return proxied;\n }\n if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${name} is not proxied`);\n return value;\n },\n has: (target, prop) =>\n own(prop) &&\n (Reflect.has(target, prop) || (typeof prop === \"string\" && aliasKeys.includes(prop))),\n // An alias may also be a key of env (the test declared it for the callee's sake): listed once.\n ownKeys: (target) => [...new Set([...Reflect.ownKeys(target).filter(own), ...aliasKeys])],\n getOwnPropertyDescriptor: (target, prop) => {\n if (!own(prop)) return undefined;\n if (typeof prop === \"string\" && aliasKeys.includes(prop))\n return {\n value: env[canonical(prop)],\n enumerable: true,\n configurable: true,\n writable: false,\n };\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n });\n // An entrypoint class exposes RPC methods; the queue and http drives need the handler object.\n const handler: WorkerHandler = typeof options.handler === \"function\" ? {} : options.handler;\n const worker: RunningWorker = { handler, env: proxiedEnv };\n\n return {\n name: \"cloudflare\",\n assumptions,\n concurrent: true,\n\n async reset(spec: ScenarioSpec): Promise<void> {\n await connections.clear();\n for (const binding of bindings) binding.clear();\n for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {\n // One resource is set up once, under the name it is known by.\n if (setup.binding in aliases)\n throw new Error(\n `binding ${setup.binding} is an alias of ${canonical(setup.binding)}: set it up and read it as ${canonical(setup.binding)}`,\n );\n await binding.reset(setup, env[setup.binding]);\n }\n },\n\n restrictEvents(spec: ScenarioSpec, keepIds: readonly string[]): ScenarioSpec {\n return { ...spec, drive: restrictDrive(spec.drive as Drive, keepIds) };\n },\n\n async finish(spec: ScenarioSpec, hooks: RunHooks): Promise<void> {\n // What each WebSocket connection received, and a close its object made, before the stores are read.\n connections.record(hooks);\n for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {\n const tables = await binding.snapshot(setup, env[setup.binding], (reason) =>\n hooks.unsupported(reason),\n );\n if (tables)\n hooks.snapshot(hooks.bookkeeping(), `${binding.target}:${setup.binding}`, { tables });\n }\n // Then the connections are torn down, outside the run: what an object does on close is not\n // modelled, and a request it makes then is caught.\n const torn = await withoutNetwork(() => connections.teardown(durable.objects));\n if (torn.value) hooks.unsupported(torn.value);\n if (torn.requested)\n hooks.unsupported(\n \"a Durable Object made a request while its WebSocket connections were torn down after the run; what webSocketClose does is not modelled\",\n );\n },\n\n initialEvents(spec: ScenarioSpec): readonly EventRef[] {\n return driveEvents(spec.drive as Drive);\n },\n\n async deliver(event: EventRef, hooks: RunHooks, spec: ScenarioSpec): Promise<DeliveryResult> {\n const drive = spec.drive as Drive;\n const invocation = invocationOf(event);\n hooksRef = hooks;\n // An event of a binding's own (an alarm, a Workflow run) is the binding's to deliver.\n const owner =\n event.source === undefined ? undefined : bindings.find((b) => b.source === event.source);\n if (owner?.deliver) return owner.deliver(event, hooks, spec);\n switch (drive.kind) {\n case \"http\":\n return deliverRequest(event, hooks, spec, drive, invocation, worker);\n case \"cron\":\n return deliverTick(event, hooks, spec, drive, invocation, worker);\n case \"websocket\":\n return deliverWebSocket(event, hooks, spec, drive, {\n worker,\n connections,\n objects: durable.objects,\n });\n case \"rpc\": {\n const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);\n if (typeof cls !== \"function\") {\n hooks.unsupported(\n `Rpc: ${drive.entrypoint === undefined ? \"the Worker's default export\" : `export ${drive.entrypoint}`} is not a WorkerEntrypoint class; pass the Worker module's exports as createCloudflarePlatform({ ..., exports })`,\n );\n return { status: \"errored\", followUps: [] };\n }\n return deliverCall(event, hooks, spec, drive, invocation, cls, proxiedEnv);\n }\n default:\n return deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries);\n }\n },\n };\n}\n","/**\n * Differential check: the same fault-free scenario run once through Eutaxy's\n * proxies and once against the raw bindings, with the queue model (or the\n * HTTP caller's retry policy) applied on the raw side itself. Any difference in the per-attempt decisions or in\n * the final D1 and R2 state is a bug in the proxies or the platform model, not in\n * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue\n * semantics (core's redelivery rule among it); what it does not share is any proxy code.\n */\n\nimport {\n type EventRef,\n getPath,\n invocationOf,\n type JsonValue,\n redelivery,\n type ScenarioSpec,\n toJson,\n} from \"@eutaxy/core\";\nimport {\n CrashSignal,\n compareSides,\n DifferentialStuck,\n effectLatencyMs,\n installScriptedFetch,\n patchGlobals,\n proxiedSide,\n settleOn,\n type VirtualClock,\n} from \"@eutaxy/engine\";\nimport { executionContext } from \"./background.ts\";\nimport { type Binding, d1Binding, ownedSetups, r2Binding } from \"./bindings.ts\";\nimport { isD1 } from \"./d1.ts\";\nimport { requestFor } from \"./http.ts\";\nimport { type CloudflarePlatformOptions, createCloudflarePlatform } from \"./platform.ts\";\nimport { isR2 } from \"./r2.ts\";\nimport { callMethod, describeError, entrypointClass } from \"./rpc.ts\";\nimport { type Drive, driveEvents, type HttpRequestSpec, type RpcCallSpec } from \"./scenario.ts\";\nimport type { TickData } from \"./scheduled.ts\";\n\n/** A type, not an interface, so it is JSON data the comparison takes as it is. */\nexport type AttemptRecord = {\n readonly event: string;\n readonly attempt: number;\n readonly status: \"completed\" | \"errored\";\n /** Queue drive: the acknowledgement that took effect. Cron drive: `no_retry` when the handler asked for none. */\n readonly decision: \"ack\" | \"retry\" | \"no_retry\" | null;\n /** HTTP drive: the response status the caller saw (500 for an uncaught exception). */\n readonly response?: number;\n /** RPC drive: the answer the caller saw, `{ ok: true, value }` or `{ ok: false, error }`. */\n readonly result?: JsonValue;\n};\n\nexport interface Side {\n readonly attempts: readonly AttemptRecord[];\n readonly state: {\n readonly [binding: string]: { readonly [table: string]: readonly JsonValue[] };\n };\n}\n\nexport interface DifferentialResult {\n /** True only when both sides agree and the proxied run touched nothing unmodelled. */\n readonly equal: boolean;\n readonly eutaxy: Side;\n readonly raw: Side;\n readonly differences: readonly string[];\n /** What the proxied run could not control; non-empty means the comparison proves nothing. */\n readonly unsupported: readonly string[];\n}\n\n/**\n * The raw side's only wrapper: counts D1 calls in flight (so the settle loop\n * knows real I/O is pending) and advances the clock as the proxies do. It\n * records nothing and injects nothing.\n */\nfunction countingD1(real: D1Database, io: { n: number }, clock: VirtualClock): D1Database {\n const realOf = new WeakMap<object, D1PreparedStatement>();\n const track = async <T>(p: Promise<T>): Promise<T> => {\n io.n++;\n try {\n return await p;\n } finally {\n io.n--;\n clock.advance(effectLatencyMs);\n }\n };\n const wrapStatement = (s: D1PreparedStatement): D1PreparedStatement => {\n const proxy = new Proxy(s, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (prop === \"bind\") return (...a: unknown[]) => wrapStatement(t.bind(...a));\n if (prop === \"run\" || prop === \"all\" || prop === \"first\" || prop === \"raw\") {\n return (...a: unknown[]) =>\n track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a));\n }\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n realOf.set(proxy, s);\n return proxy;\n };\n return new Proxy(real, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (prop === \"prepare\") return (sql: string) => wrapStatement(t.prepare(sql));\n if (prop === \"batch\") {\n return (stmts: D1PreparedStatement[]) =>\n track(t.batch(stmts.map((s) => realOf.get(s) ?? s)));\n }\n if (prop === \"exec\") return (sql: string) => track(t.exec(sql));\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n}\n\n/**\n * The same for an R2 bucket: each call advances the clock as its proxied\n * effect does, and reading a body it gave counts as I/O in flight but does\n * not advance the clock (the proxy reads it inside the get). Reads through\n * the body's own stream are not counted: wrapping it would lose the known\n * length a copy's put needs, and Miniflare answers them within the settle\n * loop's real tick (checked with an 8 MB body).\n */\nfunction countingR2(real: R2Bucket, io: { n: number }, clock: VirtualClock): R2Bucket {\n const track = async <T>(p: Promise<T>, advance: boolean): Promise<T> => {\n io.n++;\n try {\n return await p;\n } finally {\n io.n--;\n if (advance) clock.advance(effectLatencyMs);\n }\n };\n const reads = [\"arrayBuffer\", \"bytes\", \"text\", \"json\", \"blob\"];\n const counted = (o: unknown): unknown => {\n if (o === null || typeof o !== \"object\" || !(\"body\" in o)) return o;\n return new Proxy(o, {\n get(t, prop) {\n // The object's own getters (body, etag) need the object itself as receiver.\n const v = Reflect.get(t, prop) as unknown;\n if (typeof prop === \"string\" && reads.includes(prop) && typeof v === \"function\")\n return (...a: unknown[]) =>\n track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a), false);\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n };\n return new Proxy(real, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (\n prop === \"put\" ||\n prop === \"delete\" ||\n prop === \"get\" ||\n prop === \"head\" ||\n prop === \"list\"\n )\n return async (...a: unknown[]) =>\n counted(await track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a), true));\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n}\n\n/**\n * The bindings whose state the two sides compare: those a store holds and\n * the real binding resets and reads back (D1, R2). Durable Objects and\n * Workflows have no raw side.\n */\nfunction storedBindings(options: CloudflarePlatformOptions): readonly Binding[] {\n return [d1Binding(options.schemas), r2Binding()];\n}\n\nasync function snapshotAll(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n): Promise<Side[\"state\"]> {\n const env = options.env as Record<string, unknown>;\n const out: Record<string, { readonly [table: string]: readonly JsonValue[] }> = {};\n for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) {\n // A D1 or R2 snapshot reports nothing; if one ever did, the comparison could not stand.\n const tables = await binding.snapshot(setup, env[setup.binding], (reason) => {\n throw new Error(`snapshot of ${setup.binding}: ${reason}`);\n });\n if (tables) out[setup.binding] = tables;\n }\n return out;\n}\n\n/** The Eutaxy side, keeping each delivery's status and the decision it made. */\nasync function eutaxySide(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n): Promise<Side & { readonly unsupported: readonly string[] }> {\n const { attempts, unsupported } = await proxiedSide(\n spec,\n createCloudflarePlatform(options),\n (event, result, entries): AttemptRecord => {\n const invocation = invocationOf(event);\n const mine = entries.filter((e) => e.invocation === invocation);\n const decision = mine.some((e) => e.kind === \"result\" && e.op === \"no_retry\")\n ? \"no_retry\"\n : (mine.find(\n (e) =>\n e.kind === \"result\" &&\n (e.op === \"ack\" || e.op === \"retry\") &&\n getPath(e.payload, \"result.effective\") === true,\n )?.op as \"ack\" | \"retry\" | undefined);\n const response = mine.find((e) => e.kind === \"result\" && e.op === \"response\");\n const answer = (): Partial<AttemptRecord> => {\n if (!response) return {};\n if (spec.drive.kind === \"rpc\")\n return { result: getPath(response.payload, \"result\") ?? null };\n return { response: getPath(response.payload, \"result.status\") as number };\n };\n return {\n event: event.id,\n attempt: event.attempt,\n status: result.status === \"completed\" ? \"completed\" : \"errored\",\n decision: decision ?? null,\n ...answer(),\n };\n },\n );\n return { attempts, state: await snapshotAll(spec, options), unsupported };\n}\n\n/** Each binding's tables under `<binding>.<table>`, as the comparison names them. */\nfunction flatten(state: Side[\"state\"]): { readonly [name: string]: readonly JsonValue[] } {\n const out: Record<string, readonly JsonValue[]> = {};\n for (const [binding, tables] of Object.entries(state))\n for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;\n return out;\n}\n\n/** The next event as the engine picks it: the earliest due, the first inserted among equals. */\nfunction takeEarliest(pending: EventRef[]): EventRef {\n let best = 0;\n for (let i = 1; i < pending.length; i++)\n if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;\n return pending.splice(best, 1)[0] as EventRef;\n}\n\n/** The raw side: the handler called directly with the real bindings and plain message or Request objects. */\nasync function rawSide(spec: ScenarioSpec, options: CloudflarePlatformOptions): Promise<Side> {\n const env = options.env as Record<string, unknown>;\n const drive = spec.drive as Drive;\n const maxRetries = options.maxRetries ?? 3;\n // The same resets as the proxied side's, which ran first on the same env and so already holds.\n for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options)))\n await binding.reset(setup, env[setup.binding]);\n const attempts: AttemptRecord[] = [];\n const pending: EventRef[] = [...driveEvents(drive)];\n // The same virtual globals as the proxied side, from the same seed, so Date.now and randomness agree,\n // and the same scripted externals, without recording.\n const patched = patchGlobals(0);\n const unsupported: string[] = [];\n const restoreFetch = installScriptedFetch(\n spec.externals,\n null,\n (r) => unsupported.push(r),\n () => patched.clock.advance(effectLatencyMs), // the proxied side advances per effect; match it\n );\n const io = { n: 0 };\n const counting = new Map<string, D1Database | R2Bucket>();\n const countedEnv = new Proxy(env, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown;\n if (typeof prop !== \"string\" || !(isD1(value) || isR2(value))) return value;\n let c = counting.get(prop);\n if (!c) {\n c = isD1(value)\n ? countingD1(value, io, patched.clock)\n : countingR2(value, io, patched.clock);\n counting.set(prop, c);\n }\n return c;\n },\n });\n const settle = <T>(p: Promise<T>): Promise<T> =>\n settleOn(p, {\n clock: patched.clock,\n inFlight: () => io.n,\n crashed: () => false,\n stuck: () => {\n throw new DifferentialStuck();\n },\n });\n try {\n // The queue and http drives need the handler object; an entrypoint class has neither handler.\n const handlers = typeof options.handler === \"function\" ? {} : options.handler;\n if (drive.kind === \"websocket\")\n throw new Error(\n \"runDifferential has no raw side for a websocket drive: its messages are delivered inside the object\",\n );\n if (drive.kind === \"rpc\") {\n const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);\n if (typeof cls !== \"function\") throw new Error(\"the Worker has no WorkerEntrypoint class\");\n while (pending.length > 0) {\n const event = takeEarliest(pending);\n const call = event.data as unknown as RpcCallSpec;\n const background: Promise<unknown>[] = [];\n let status: \"completed\" | \"errored\";\n let result: JsonValue;\n try {\n const value = await settle(\n Promise.resolve().then(() =>\n callMethod(cls, call, executionContext(background), countedEnv),\n ),\n );\n result = { ok: true, value: toJson(value) };\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n result = { ok: false, error: describeError(err) };\n status = \"errored\";\n }\n await settle(Promise.all(background));\n attempts.push({ event: event.id, attempt: event.attempt, status, decision: null, result });\n const next = status === \"completed\" ? null : redelivery(event, drive.retries, spec.bounds);\n if (next) pending.push(next);\n }\n } else if (drive.kind === \"cron\") {\n const handler = handlers.scheduled;\n if (!handler) throw new Error(\"the Worker has no scheduled() handler\");\n while (pending.length > 0) {\n const event = takeEarliest(pending);\n const tick = event.data as unknown as TickData;\n // The proxied side's clock moved to the tick; so does this one.\n if (event.at !== undefined && event.at > patched.clock.now())\n patched.clock.advance(event.at - patched.clock.now());\n const background: Promise<unknown>[] = [];\n const failures: unknown[] = [];\n let noRetry = false;\n const controller: ScheduledController = {\n scheduledTime: tick.scheduledTime,\n cron: tick.cron,\n noRetry: () => {\n noRetry = true;\n },\n };\n let status: \"completed\" | \"errored\";\n try {\n await settle(\n Promise.resolve().then(() =>\n handler.call(\n handlers,\n controller,\n countedEnv,\n executionContext(background, failures),\n ),\n ),\n );\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n status = \"errored\";\n }\n await settle(Promise.all(background));\n // A failed waitUntil is the invocation's status, as for the proxied side.\n if (status === \"completed\" && failures.length > 0) status = \"errored\";\n attempts.push({\n event: event.id,\n attempt: event.attempt,\n status,\n decision: noRetry ? \"no_retry\" : null,\n });\n const next =\n status === \"completed\" || noRetry ? null : redelivery(event, drive.retries, spec.bounds);\n if (next) pending.push(next);\n }\n } else if (drive.kind === \"http\") {\n const handler = handlers.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n while (pending.length > 0) {\n const event = takeEarliest(pending);\n const req = event.data as unknown as HttpRequestSpec;\n const background: Promise<unknown>[] = [];\n let status: \"completed\" | \"errored\";\n let response = 500;\n try {\n const r = await settle(\n Promise.resolve().then(() =>\n handler.call(handlers, requestFor(req), countedEnv, executionContext(background)),\n ),\n );\n await settle(r.clone().text());\n response = r.status;\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n status = \"errored\";\n }\n await settle(Promise.all(background));\n attempts.push({\n event: event.id,\n attempt: event.attempt,\n status,\n decision: null,\n response,\n });\n const accepted =\n drive.retryOn === \"5xx\" ? response < 500 : response >= 200 && response < 300;\n const next = accepted ? null : redelivery(event, drive.retries, spec.bounds);\n if (next) pending.push(next);\n }\n } else {\n const handler = handlers.queue;\n if (!handler) throw new Error(\"the Worker has no queue() handler\");\n while (pending.length > 0) {\n const event = takeEarliest(pending);\n let decision: \"ack\" | \"retry\" | null = null;\n const background: Promise<unknown>[] = [];\n const message: Message<unknown> = {\n id: event.id,\n timestamp: new Date(),\n body: JSON.parse(JSON.stringify(event.data)) as JsonValue,\n attempts: event.attempt,\n ack: () => {\n decision ??= \"ack\";\n },\n retry: () => {\n decision ??= \"retry\";\n },\n };\n const batch: MessageBatch<unknown> = {\n queue: drive.queue,\n messages: [message],\n metadata: { metrics: { backlogCount: 0, backlogBytes: 0 } },\n ackAll: () => message.ack(),\n retryAll: () => message.retry(),\n };\n const ctx = executionContext(background);\n let status: \"completed\" | \"errored\";\n try {\n await settle(\n Promise.resolve().then(() => handler.call(handlers, batch, countedEnv, ctx)),\n );\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n status = \"errored\";\n }\n if (status === \"completed\") decision ??= \"ack\";\n await settle(Promise.all(background));\n attempts.push({ event: event.id, attempt: event.attempt, status, decision });\n const next = decision === \"ack\" ? null : redelivery(event, maxRetries, spec.bounds);\n if (next) pending.push(next);\n }\n }\n } finally {\n restoreFetch();\n patched.restore();\n }\n if (unsupported.length > 0) throw new DifferentialStuck(`raw side: ${unsupported.join(\"; \")}`);\n return { attempts, state: await snapshotAll(spec, options) };\n}\n\n/** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */\nexport async function runDifferential(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n): Promise<DifferentialResult> {\n if (\n (spec.drive.kind === \"http\" || spec.drive.kind === \"rpc\") &&\n (\"delaysMs\" in spec.drive || \"deadlineMs\" in spec.drive)\n ) {\n throw new Error(\"runDifferential does not model the caller's delaysMs or deadlineMs yet\");\n }\n // The raw side calls the real bindings; a callee's real code is Eutaxy's model, with no runtime side.\n if (spec.setup.some((s) => s.kind === \"callee\"))\n throw new Error(\n \"runDifferential keeps to the binding proxies: a scenario with a callee() has no raw side; script the service for the differential entry\",\n );\n const { unsupported, ...eutaxy } = await eutaxySide(spec, options);\n const raw = await rawSide(spec, options);\n const differences = compareSides(\n { attempts: eutaxy.attempts, state: flatten(eutaxy.state) },\n { attempts: raw.attempts, state: flatten(raw.state) },\n unsupported,\n );\n return { equal: differences.length === 0, eutaxy, raw, differences, unsupported };\n}\n","/** How the two halves of `eutaxy check` name a module next to the scenario. Imports nothing, so workerd can load it. */\n\n/** Normalize a module path from a scenario's `specs` to a key: \"./domain.ts\". */\nexport function specKey(path: string): string {\n const posix = path\n .split(\"\\\\\")\n .join(\"/\")\n .replace(/^(\\.\\/)+/, \"\");\n return `./${posix}`;\n}\n\n/** The key Vite's `import.meta.glob` gives a path next to the scenario, seen from `.eutaxy/`. */\nexport function globKey(path: string): string {\n return `.${specKey(path)}`;\n}\n","/**\n * The half of `eutaxy check` that runs inside workerd: the generated test\n * passes its module globs here and stores what this returns in its task\n * meta, which the CLI reads back. It imports nothing that needs Node, so\n * the Cloudflare Vitest plugin can load it.\n */\n\nimport {\n type CalleeModule,\n check,\n createCloudflarePlatform,\n type DurableObjectTestHelpers,\n type WorkerHandler,\n} from \"@eutaxy/cloudflare\";\nimport type { ScenarioSpec, SpecVerdict } from \"@eutaxy/core\";\nimport { observeCore } from \"@eutaxy/engine\";\nimport { checkSpecModule } from \"@eutaxy/prover\";\nimport { renderJson } from \"@eutaxy/report\";\nimport type { ModuleSpecs } from \"@eutaxy/spec\";\nimport { globKey, specKey } from \"./keys.ts\";\n\n/** What the generated test stores in its task meta. */\nexport interface CheckTransport {\n readonly report: unknown;\n /** Set instead of a report when a module the scenario's `specs` names has no usable spec file. */\n readonly specErrors?: readonly SpecError[];\n readonly worker: { readonly entry: string; readonly config: string };\n readonly setup: readonly { readonly kind: string; readonly [key: string]: unknown }[];\n /** The scenario's drive, for what the regression test must pass the platform (a named entrypoint). */\n readonly drive?: { readonly kind: string; readonly [key: string]: unknown };\n /** The core modules observed (as the scenario's specs name them) and the functions on each. */\n /** The callees the platform ran, by binding: each one's Worker name, and what the binding carried, for the regression test. */\n readonly callees?: Readonly<\n Record<\n string,\n {\n readonly name: string;\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, unknown>>;\n }\n >\n >;\n /** The aliases the platform ran with, for the regression test. */\n readonly aliases?: Readonly<Record<string, string>>;\n readonly observed?: readonly { readonly module: string; readonly functions: readonly string[] }[];\n}\n\nexport interface SpecError {\n readonly module: string;\n readonly line: number;\n readonly message: string;\n}\n\n/** A generated spec entry: the module's specs, read on the Node side, and a loader of its spec file. */\nexport interface SpecEntry {\n readonly specs: ModuleSpecs;\n readonly load: () => Promise<object>;\n}\n\n/** Vite globs, keyed as `import.meta.glob` keys them from `.eutaxy/` (see `globKey`). */\nexport type ModuleGlob = Readonly<Record<string, () => Promise<unknown>>>;\n\n/** Each D1 binding's schema, read from the `.sql` files next to the scenario. */\nexport function schemasFor(\n scenario: ScenarioSpec,\n sqlFiles: Readonly<Record<string, string>>,\n): Record<string, string> {\n const schemas: Record<string, string> = {};\n for (const step of scenario.setup) {\n if (step.kind !== \"d1\") continue;\n const file = String(step[\"schemaFile\"]);\n const sql = sqlFiles[globKey(file)];\n if (sql === undefined) throw new Error(`schema file ${file} not found next to the scenario`);\n schemas[String(step[\"binding\"])] = sql;\n }\n return schemas;\n}\n\nexport interface SelectedModule {\n /** As the scenario names it. */\n readonly path: string;\n readonly key: string;\n readonly namespace: object;\n readonly specs: ModuleSpecs;\n /** The spec file's namespace: its exports are the specs. */\n readonly props: Readonly<Record<string, unknown>>;\n /** The functions observed: the ones with specs, and the decisions `refines` names that the module exports. */\n readonly names: readonly string[];\n}\n\n/**\n * The modules the scenario's `specs` name, loaded with their specs and\n * their spec files, and every reason the check cannot go ahead: a module\n * that is not there, a spec that does not read, a function name observed\n * in two modules (decisions are logged by name, so it would be ambiguous).\n * The spec files are loaded here, before anything is observed, so the\n * functions their specs hold are the modules' own.\n */\nexport async function selectSpecModules(\n scenario: ScenarioSpec,\n modules: ModuleGlob,\n specEntries: Readonly<Record<string, SpecEntry>>,\n): Promise<{\n readonly selected: readonly SelectedModule[];\n readonly specErrors: readonly SpecError[];\n}> {\n const decisions = scenario.invariants.flatMap((i) => (i.kind === \"refines\" ? [i.decision] : []));\n const specErrors: SpecError[] = [];\n const selected: SelectedModule[] = [];\n for (const path of scenario.specs ?? []) {\n const load = modules[globKey(path)];\n if (!load) {\n specErrors.push({ module: path, line: 0, message: \"no such module next to the scenario\" });\n continue;\n }\n const namespace = (await load()) as Record<string, unknown>;\n const key = specKey(path);\n const entry = Object.hasOwn(specEntries, key) ? specEntries[key] : undefined;\n const specs: ModuleSpecs = entry?.specs ?? { functions: [], errors: [] };\n for (const e of specs.errors)\n specErrors.push({\n module: e.inModule ? path : `${path.replace(/\\.ts$/, \"\")}.props.ts`,\n line: e.line,\n message: e.message,\n });\n const props = entry ? ((await entry.load()) as Record<string, unknown>) : {};\n const exported = decisions.filter((d) => typeof namespace[d] === \"function\");\n const names = [...new Set([...specs.functions.map((f) => f.name), ...exported])];\n selected.push({ path, key, namespace, specs, props, names });\n }\n const observedIn = new Map<string, string>();\n for (const m of selected)\n for (const n of m.names) {\n const other = observedIn.get(n);\n if (other === undefined) observedIn.set(n, m.path);\n else\n specErrors.push({\n module: m.path,\n line: 0,\n message: `${n} is observed in both ${other} and ${m.path}; decisions of one name must come from one module`,\n });\n }\n return { selected, specErrors };\n}\n\nexport interface WorkerdCheckInput {\n /** The scenario module's default export. */\n readonly scenario: ScenarioSpec;\n /** `env` from `cloudflare:workers`. */\n readonly env: object;\n /** The `cloudflare:test` module, for Durable Objects. */\n readonly durableObjects: DurableObjectTestHelpers;\n /** The raw text of the `.sql` files next to the scenario. */\n readonly sqlFiles: Readonly<Record<string, string>>;\n /** The TypeScript modules next to the scenario (the Worker and the spec modules among them). */\n readonly modules: ModuleGlob;\n /** The generated `specs.ts` entries, by module key. */\n readonly specEntries: Readonly<Record<string, SpecEntry>>;\n /** The callees the scenario names, by binding: each one's Worker name and module exports, imported by the generated test. */\n readonly callees?: Readonly<Record<string, CalleeModule>>;\n /** SQL files outside the scenario's directory, by the key `schemasFor` looks up. */\n readonly extraSql?: Readonly<Record<string, string>>;\n /** Qualified binding names that are aliases of the caller's bindings (shared resources). */\n readonly aliases?: Readonly<Record<string, string>>;\n readonly seed: string;\n readonly maxRuns?: number;\n readonly budgetMs?: number;\n readonly exhaustive?: boolean;\n}\n\n/** Run the scenario's check, with its specs observed, and return what the CLI reads back. */\nexport async function checkInWorkerd(input: WorkerdCheckInput): Promise<CheckTransport> {\n const { scenario } = input;\n const schemas = schemasFor(scenario, { ...input.sqlFiles, ...input.extraSql });\n const load = input.modules[globKey(scenario.worker.entry)];\n if (!load)\n throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);\n const worker = (await load()) as { default: WorkerHandler } & Record<string, unknown>;\n const platform = createCloudflarePlatform({\n env: input.env,\n handler: worker.default,\n schemas,\n durableObjects: input.durableObjects,\n exports: worker,\n ...(input.callees === undefined ? {} : { callees: input.callees }),\n ...(input.aliases === undefined ? {} : { aliases: input.aliases }),\n });\n const { selected, specErrors } = await selectSpecModules(\n scenario,\n input.modules,\n input.specEntries,\n );\n const transportBase = {\n worker: scenario.worker,\n setup: scenario.setup,\n drive: scenario.drive,\n ...(input.callees === undefined\n ? {}\n : {\n callees: Object.fromEntries(\n Object.entries(input.callees).map(([binding, c]) => [\n binding,\n {\n name: c.name,\n ...(c.entrypoint === undefined ? {} : { entrypoint: c.entrypoint }),\n ...(c.props === undefined ? {} : { props: c.props }),\n },\n ]),\n ),\n }),\n ...(input.aliases === undefined ? {} : { aliases: input.aliases }),\n };\n if (specErrors.length > 0) return { report: null, specErrors, ...transportBase };\n const observers = selected.map((m) => observeCore(m.namespace, m.names));\n let verdict: Awaited<ReturnType<typeof check>>;\n try {\n verdict = await check(scenario, platform, {\n seed: input.seed,\n ...(input.maxRuns === undefined ? {} : { maxRuns: input.maxRuns }),\n ...(input.budgetMs === undefined ? {} : { budgetMs: input.budgetMs }),\n ...(input.exhaustive ? { exhaustive: true } : {}),\n });\n } finally {\n for (const o of observers) o.restore();\n }\n // CHECKED on the calls the exploration recorded, then TESTED on inputs drawn from the check's seed.\n const specs: SpecVerdict[] = selected.flatMap((m, i) =>\n checkSpecModule(\n m.key,\n m.specs,\n m.props,\n m.namespace as Record<string, unknown>,\n observers[i] as ReturnType<typeof observeCore>,\n { tested: { seed: input.seed } },\n ),\n );\n return {\n report: JSON.parse(renderJson(verdict, specs)) as unknown,\n ...transportBase,\n observed: selected.map((m) => ({ module: m.path, functions: m.names })),\n };\n}\n"],"mappings":";;;;;;;;;AA+DA,SAAS,YAAY,OAAuD;CAC1E,MAAM,wBAAQ,IAAI,IAAY;CAC9B,MAAM,sBAAM,IAAI,IAAoB;CACpC,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,OAAO,KAAK,QAAQ,mBAAmB,GAAG;EAChD,IAAI,KAAK;EACT,KAAK,IAAI,IAAI,GAAG,MAAM,IAAI,EAAE,GAAG,KAAK,KAAK,GAAG,KAAK,GAAG;EACpD,MAAM,IAAI,EAAE;EACZ,IAAI,IAAI,MAAM,EAAE;CAClB;CACA,OAAO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