eutaxy 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/dist/aws.d.mts +7 -5
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +41 -135
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +2 -2
  7. package/dist/checked-CGpA2-F0.d.mts +285 -0
  8. package/dist/checked-CGpA2-F0.d.mts.map +1 -0
  9. package/dist/cli-IJrKkeYS.mjs +2 -0
  10. package/dist/cli.d.mts.map +1 -1
  11. package/dist/cli.mjs +2 -2
  12. package/dist/cloudflare.d.mts +158 -54
  13. package/dist/cloudflare.d.mts.map +1 -1
  14. package/dist/cloudflare.mjs +3 -1815
  15. package/dist/delivery-invariants-BraYqcYN.d.mts +5 -0
  16. package/dist/delivery-invariants-BraYqcYN.d.mts.map +1 -0
  17. package/dist/delivery-invariants-Cuxdna28.mjs +39 -0
  18. package/dist/delivery-invariants-Cuxdna28.mjs.map +1 -0
  19. package/dist/index.d.mts +22 -189
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +17 -197
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{platform-eVgCMbX0.d.mts → platform-DfMwknw1.d.mts} +94 -73
  24. package/dist/platform-DfMwknw1.d.mts.map +1 -0
  25. package/dist/{src-C19_yfMM.mjs → src-Bqc9Eyb1.mjs} +961 -543
  26. package/dist/src-Bqc9Eyb1.mjs.map +1 -0
  27. package/dist/src-DKb-fkdb.mjs +3399 -0
  28. package/dist/src-DKb-fkdb.mjs.map +1 -0
  29. package/dist/{src-CgfGiH25.mjs → src-Dxl9ZlKn.mjs} +223 -17
  30. package/dist/src-Dxl9ZlKn.mjs.map +1 -0
  31. package/package.json +1 -1
  32. package/dist/cli-NqY61bpo.mjs +0 -2
  33. package/dist/cloudflare.mjs.map +0 -1
  34. package/dist/explore-BHYvAZKN.d.mts +0 -84
  35. package/dist/explore-BHYvAZKN.d.mts.map +0 -1
  36. package/dist/platform-eVgCMbX0.d.mts.map +0 -1
  37. package/dist/src-BD3jkjgG.mjs +0 -477
  38. package/dist/src-BD3jkjgG.mjs.map +0 -1
  39. package/dist/src-C19_yfMM.mjs.map +0 -1
  40. package/dist/src-CgfGiH25.mjs.map +0 -1
  41. package/dist/src-s6uYyC0B.mjs +0 -89
  42. package/dist/src-s6uYyC0B.mjs.map +0 -1
  43. package/dist/verdict-evEM5Gxx.mjs +0 -12
  44. package/dist/verdict-evEM5Gxx.mjs.map +0 -1
@@ -0,0 +1,3399 @@
1
+ import { a as emitRegressionTest, d as predicateSource, f as extractSpecs, l as lemmaBool, n as renderSpecs, o as describeVerdict, r as renderText, s as checkSpecModule, t as renderJson, u as lemmaUnresolved } from "./src-Dxl9ZlKn.mjs";
2
+ import { S as canonicalJson, _ as defaultBounds, a as explore, c as CrashSignal, d as withoutNetwork, f as patchGlobals, g as toJson, i as proxiedSide, l as InjectedEffectError, m as settleOn, n as DifferentialStuck, r as compareSides, t as observeCore, u as installScriptedFetch, v as validateScenario, x as getPath } from "./src-Bqc9Eyb1.mjs";
3
+ import { n as atLeastOncePerMessage$1 } from "./delivery-invariants-Cuxdna28.mjs";
4
+ import { createRequire } from "node:module";
5
+ import { spawn } from "node:child_process";
6
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
7
+ import { basename, dirname, join, relative, resolve } from "node:path";
8
+ // packages/cli/src/args.ts
9
+ function parseArgs(argv, booleans = []) {
10
+ const positionals = [];
11
+ const flags = {};
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const a = argv[i];
14
+ if (!a.startsWith("--")) {
15
+ positionals.push(a);
16
+ continue;
17
+ }
18
+ const eq = a.indexOf("=");
19
+ if (eq !== -1) {
20
+ flags[a.slice(2, eq)] = a.slice(eq + 1);
21
+ continue;
22
+ }
23
+ const name = a.slice(2);
24
+ const next = argv[i + 1];
25
+ if (booleans.includes(name) || next === void 0 || next.startsWith("--")) flags[name] = true;
26
+ else {
27
+ flags[name] = next;
28
+ i++;
29
+ }
30
+ }
31
+ return {
32
+ positionals,
33
+ flags
34
+ };
35
+ }
36
+ // packages/cli/src/generate.ts
37
+ /**
38
+ * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before
39
+ * running Vitest: a test that performs the check inside workerd and prints
40
+ * the verdict on one marked line, and a Vitest config with the Cloudflare
41
+ * plugin pointed at the scenario's wrangler config.
42
+ */
43
+ /** Key under which the generated test stores its result in the Vitest task meta, read back from the JSON reporter. */
44
+ const metaKey = "eutaxy";
45
+ /**
46
+ * The generated test: the module globs (Vite resolves them at build time,
47
+ * so they must be written in the test) and one call to `checkInWorkerd`,
48
+ * which does the rest.
49
+ */
50
+ function checkTestSource(g) {
51
+ const options = `seed: ${JSON.stringify(g.seed)}` + (g.maxRuns === void 0 ? "" : `, maxRuns: ${g.maxRuns}`) + (g.budgetMs === void 0 ? "" : `, budgetMs: ${g.budgetMs}`) + (g.exhaustive ? ", exhaustive: true" : "");
52
+ return `// Generated by eutaxy check; deleted after the run.
53
+ import { checkInWorkerd } from "eutaxy/cloudflare";
54
+ import { env } from "cloudflare:workers";
55
+ import * as durableObjects from "cloudflare:test";
56
+ import { test } from "vitest";
57
+ import scenario from ${JSON.stringify(g.scenarioImport)};
58
+ import { specLoaders } from "./specs.ts";
59
+
60
+ const sqlFiles = import.meta.glob("../**/*.sql", { query: "?raw", import: "default", eager: true }) as Record<string, string>;
61
+ const modules = import.meta.glob(["../**/*.ts", "!../**/*.test.ts", "!../**/*.sim.ts", "!../**/node_modules/**", "!../**/.eutaxy/**"]);
62
+
63
+ test("eutaxy check", async ({ task }) => {
64
+ task.meta[${JSON.stringify(metaKey)}] = await checkInWorkerd({ scenario, env, durableObjects, sqlFiles, modules, specLoaders, ${options} });
65
+ });
66
+ `;
67
+ }
68
+ function vitestConfigSource(wranglerConfigPath, testPath, outputFile) {
69
+ return `// Generated by eutaxy check; deleted after the run.
70
+ import { cloudflareTest } from "@cloudflare/vitest-plugin";
71
+ import { defineConfig } from "vitest/config";
72
+
73
+ export default defineConfig({
74
+ plugins: [cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })],
75
+ test: {
76
+ include: [${JSON.stringify(testPath)}],
77
+ testTimeout: 600_000,
78
+ reporters: ["json"],
79
+ outputFile: ${JSON.stringify(outputFile)},
80
+ },
81
+ });
82
+ `;
83
+ }
84
+ // packages/cli/src/regression.ts
85
+ /** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */
86
+ function cloudflareRegressionTest(verdict, options) {
87
+ const bindings = Object.keys(options.schemaPaths).sort();
88
+ const imports = [
89
+ "import { createCloudflarePlatform } from \"eutaxy/cloudflare\";",
90
+ "import { env } from \"cloudflare:workers\";",
91
+ ...options.durableObjects ? ["import * as cloudflareTest from \"cloudflare:test\";"] : [],
92
+ `import scenario from ${JSON.stringify(options.scenarioPath)};`,
93
+ ...bindings.map((b) => `import schema_${b} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`),
94
+ options.workflows ? `import * as worker from ${JSON.stringify(options.workerPath)};` : `import handler from ${JSON.stringify(options.workerPath)};`,
95
+ ...(options.specModules ?? []).map((m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`)
96
+ ];
97
+ const schemas = `{ ${bindings.map((b) => `${b}: schema_${b}`).join(", ")} }`;
98
+ const retries = options.maxRetries === void 0 ? "" : `, maxRetries: ${options.maxRetries}`;
99
+ const objects = options.durableObjects ? ", durableObjects: cloudflareTest" : "";
100
+ const handler = options.workflows ? "handler: worker.default" : "handler";
101
+ const exports = options.workflows ? ", exports: worker" : "";
102
+ return emitRegressionTest(verdict, {
103
+ imports,
104
+ platform: `createCloudflarePlatform({ env, ${handler}, schemas: ${schemas}${retries}${objects}${exports} })`,
105
+ scenario: options.budgetMs === void 0 ? "scenario" : `{ ...scenario, bounds: { ...scenario.bounds, budgetMs: ${options.budgetMs} } }`,
106
+ ...options.expect ? { expect: options.expect } : {},
107
+ ...options.engineModule ? { engineModule: options.engineModule } : {},
108
+ ...options.specModules && options.specModules.length > 0 ? { observe: options.specModules.map((m, i) => ({
109
+ namespace: `core_${i}`,
110
+ functions: m.functions
111
+ })) } : {}
112
+ });
113
+ }
114
+ // packages/cli/src/keys.ts
115
+ /** How the two halves of `eutaxy check` name a module next to the scenario. Imports nothing, so workerd can load it. */
116
+ /** Normalize a module path from a scenario's `specs` to a key: "./domain.ts". */
117
+ function specKey(path) {
118
+ return `./${path.split("\\").join("/").replace(/^(\.\/)+/, "")}`;
119
+ }
120
+ /** The key Vite's `import.meta.glob` gives a path next to the scenario, seen from `.eutaxy/`. */
121
+ function globKey(path) {
122
+ return `.${specKey(path)}`;
123
+ }
124
+ // packages/cli/src/specs.ts
125
+ /**
126
+ * Spec modules for `eutaxy check`: every TypeScript module next to the
127
+ * scenario with Lemma annotations, and the generated module that holds
128
+ * their predicates as compiled code (workerd runs no `eval`). Which of them
129
+ * a run checks is the scenario's `specs`, read where the scenario is loaded,
130
+ * inside the generated test.
131
+ */
132
+ const skipDirs = /* @__PURE__ */ new Set([
133
+ "node_modules",
134
+ ".eutaxy",
135
+ "dist",
136
+ ".git"
137
+ ]);
138
+ /** Annotated modules under `dir`, tests and scenarios excepted. */
139
+ function findSpecModules(dir) {
140
+ const out = [];
141
+ const walk = (at) => {
142
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
143
+ const path = join(at, entry.name);
144
+ if (entry.isDirectory()) {
145
+ if (!skipDirs.has(entry.name)) walk(path);
146
+ continue;
147
+ }
148
+ const name = entry.name;
149
+ if (!name.endsWith(".ts") || name.endsWith(".d.ts") || name.endsWith(".test.ts") || name.endsWith(".sim.ts")) continue;
150
+ const source = readFileSync(path, "utf8");
151
+ if (!/@(ensures|total|throws)\b/.test(source)) continue;
152
+ const specs = extractSpecs(source);
153
+ if (specs.functions.length === 0 && specs.errors.length === 0) continue;
154
+ out.push({
155
+ key: specKey(relative(dir, path)),
156
+ path,
157
+ specs
158
+ });
159
+ }
160
+ };
161
+ walk(dir);
162
+ return out.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
163
+ }
164
+ /** The generated module's own names; each predicate takes them as parameters, so nothing in a property shadows them. */
165
+ const helpers = {
166
+ bool: "__eutaxyBool",
167
+ same: "__eutaxySame",
168
+ scope: "__eutaxyNamespace",
169
+ unresolved: "__eutaxyUnresolved"
170
+ };
171
+ /**
172
+ * The generated spec files: `specs.ts`, which maps each annotated module's
173
+ * key to a loader, and one file per module with its extracted specs and a
174
+ * function from its namespace to its predicates. A module's file loads only
175
+ * when a scenario names the module, so an annotation elsewhere that does not
176
+ * compile cannot stop a check. Each predicate binds its free names from the
177
+ * namespace (else the globals) when it is built, which happens before
178
+ * anything is observed, so checking a property never counts as a call the
179
+ * simulator made.
180
+ */
181
+ function specFiles(modules) {
182
+ const header = "// Generated by eutaxy check; deleted after the run.";
183
+ const index = [
184
+ header,
185
+ "export const specLoaders: Record<string, () => Promise<any>> = {",
186
+ ...modules.map((m, i) => ` ${JSON.stringify(m.key)}: () => import("./specs/m${i}.ts"),`),
187
+ "};"
188
+ ];
189
+ const files = modules.map((m, i) => {
190
+ const lines = [
191
+ header,
192
+ `const ${helpers.same} = Object.is;`,
193
+ "",
194
+ `export const specs = ${JSON.stringify(m.specs)};`,
195
+ "",
196
+ `export const predicates = (${helpers.scope}: any, ${helpers.bool}: any, ${helpers.unresolved}: any) => ({`
197
+ ];
198
+ for (const fn of m.specs.functions) {
199
+ lines.push(` [${JSON.stringify(fn.name)}]: {`);
200
+ for (const p of fn.ensures) {
201
+ const source = predicateSource(p.property, helpers).split("\n").join("\n ");
202
+ lines.push(` [${JSON.stringify(p.name)}]: ${source},`);
203
+ }
204
+ lines.push(" },");
205
+ }
206
+ lines.push("});");
207
+ return {
208
+ name: `specs/m${i}.ts`,
209
+ source: `${lines.join("\n")}\n`
210
+ };
211
+ });
212
+ return [{
213
+ name: "specs.ts",
214
+ source: `${index.join("\n")}\n`
215
+ }, ...files];
216
+ }
217
+ // packages/cli/src/check.ts
218
+ /**
219
+ * `eutaxy check <scenario.sim.ts>`: run a scenario inside workerd through
220
+ * the user's Vitest and the Cloudflare plugin, print the verdict as text or
221
+ * JSON, and on a violation write a regression test next to the scenario.
222
+ */
223
+ const exitCodes = {
224
+ BOUNDED: 0,
225
+ VIOLATED: 1,
226
+ UNSUPPORTED: 2,
227
+ error: 3
228
+ };
229
+ function findWrangler(dir, explicit, cwd) {
230
+ if (explicit) return resolve(cwd, explicit);
231
+ for (const name of [
232
+ "wrangler.jsonc",
233
+ "wrangler.json",
234
+ "wrangler.toml"
235
+ ]) {
236
+ const p = join(dir, name);
237
+ if (existsSync(p)) return p;
238
+ }
239
+ return null;
240
+ }
241
+ function vitestBin(from) {
242
+ const req = createRequire(join(from, "package.json"));
243
+ return join(dirname(req.resolve("vitest/package.json")), "vitest.mjs");
244
+ }
245
+ function runVitest(bin, configPath, cwd) {
246
+ return new Promise((resolveRun) => {
247
+ const child = spawn(process.execPath, [
248
+ bin,
249
+ "run",
250
+ "--config",
251
+ configPath
252
+ ], {
253
+ cwd,
254
+ env: {
255
+ ...process.env,
256
+ CI: "1",
257
+ FORCE_COLOR: "0"
258
+ },
259
+ stdio: [
260
+ "ignore",
261
+ "pipe",
262
+ "pipe"
263
+ ]
264
+ });
265
+ let output = "";
266
+ child.stdout.on("data", (d) => {
267
+ output += d.toString();
268
+ });
269
+ child.stderr.on("data", (d) => {
270
+ output += d.toString();
271
+ });
272
+ child.on("close", (code) => resolveRun({
273
+ code: code ?? 1,
274
+ output
275
+ }));
276
+ });
277
+ }
278
+ /** The transport the generated test left in its task meta, via Vitest's JSON reporter. */
279
+ function readTransport(reportPath) {
280
+ if (!existsSync(reportPath)) return null;
281
+ const report = JSON.parse(readFileSync(reportPath, "utf8"));
282
+ for (const file of report.testResults ?? []) for (const t of file.assertionResults ?? []) {
283
+ const m = t.meta?.[metaKey];
284
+ if (m) return m;
285
+ }
286
+ return null;
287
+ }
288
+ function toPosix(p) {
289
+ const s = p.split("\\").join("/");
290
+ return s.startsWith(".") ? s : `./${s}`;
291
+ }
292
+ async function runCheck(o) {
293
+ const scenarioPath = resolve(o.cwd, o.scenario);
294
+ if (!existsSync(scenarioPath)) {
295
+ o.stderr(`scenario not found: ${scenarioPath}\n`);
296
+ return exitCodes.error;
297
+ }
298
+ const dir = dirname(scenarioPath);
299
+ const name = basename(scenarioPath).replace(/\.sim\.ts$/, "").replace(/\.ts$/, "");
300
+ const wrangler = findWrangler(dir, o.wrangler, o.cwd);
301
+ if (!wrangler || !existsSync(wrangler)) {
302
+ o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\n`);
303
+ return exitCodes.error;
304
+ }
305
+ const workDir = join(dir, ".eutaxy");
306
+ const testPath = join(workDir, `${name}.check.test.ts`);
307
+ const configPath = join(workDir, "vitest.config.mts");
308
+ mkdirSync(workDir, { recursive: true });
309
+ try {
310
+ writeFileSync(testPath, checkTestSource({
311
+ seed: o.seed ?? name,
312
+ ...o.maxRuns === void 0 ? {} : { maxRuns: o.maxRuns },
313
+ ...o.budgetMs === void 0 ? {} : { budgetMs: o.budgetMs },
314
+ ...o.exhaustive ? { exhaustive: true } : {},
315
+ scenarioImport: `../${basename(scenarioPath)}`
316
+ }));
317
+ for (const f of specFiles(findSpecModules(dir))) {
318
+ mkdirSync(dirname(join(workDir, f.name)), { recursive: true });
319
+ writeFileSync(join(workDir, f.name), f.source);
320
+ }
321
+ const reportPath = join(workDir, "vitest-report.json");
322
+ rmSync(reportPath, { force: true });
323
+ writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));
324
+ const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
325
+ const transport = code === 0 ? readTransport(reportPath) : null;
326
+ if (!transport) {
327
+ o.stderr(`eutaxy check could not read a verdict from Vitest (exit ${code}):\n${output}\n`);
328
+ return exitCodes.error;
329
+ }
330
+ if (transport.specErrors && transport.specErrors.length > 0) {
331
+ for (const e of transport.specErrors) o.stderr(`${e.module}${e.line > 0 ? `:${e.line}` : ""}: ${e.message}\n`);
332
+ return exitCodes.error;
333
+ }
334
+ const report = transport.report;
335
+ const verdict = report.verdict;
336
+ const specs = report.specs ?? [];
337
+ if (o.json) o.stdout(`${canonicalJson(transport.report)}\n`);
338
+ else o.stdout(`${renderText(verdict)}\n${specs.length > 0 ? `\n${renderSpecs(specs)}\n` : ""}`);
339
+ if (verdict.kind === "VIOLATED" && !o.noRegression) {
340
+ const outPath = o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`);
341
+ const outDir = dirname(outPath);
342
+ const schemaPaths = {};
343
+ for (const step of transport.setup) if (step.kind === "d1") schemaPaths[String(step["binding"])] = toPosix(relative(outDir, resolve(dir, String(step["schemaFile"]))));
344
+ const source = cloudflareRegressionTest(verdict, {
345
+ scenarioPath: toPosix(relative(outDir, scenarioPath)),
346
+ workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),
347
+ schemaPaths,
348
+ ...o.budgetMs === void 0 ? {} : { budgetMs: o.budgetMs },
349
+ ...transport.setup.some((s) => s.kind === "durable_object") ? { durableObjects: true } : {},
350
+ ...transport.setup.some((s) => s.kind === "workflow") ? { workflows: true } : {},
351
+ ...o.expectViolation ? { expect: "violates" } : {},
352
+ ...(transport.observed ?? []).length > 0 ? { specModules: (transport.observed ?? []).map((m) => ({
353
+ path: toPosix(relative(outDir, resolve(dir, m.module))),
354
+ functions: m.functions
355
+ })) } : {}
356
+ });
357
+ mkdirSync(outDir, { recursive: true });
358
+ writeFileSync(outPath, source);
359
+ if (!o.json) o.stdout(`\nRegression test written to ${relative(o.cwd, outPath) || outPath}\n`);
360
+ }
361
+ if (verdict.kind !== "VIOLATED" && specs.some((v) => v.kind === "REFUTED")) return exitCodes.VIOLATED;
362
+ return exitCodes[verdict.kind];
363
+ } finally {
364
+ if (!o.keep) rmSync(workDir, {
365
+ recursive: true,
366
+ force: true
367
+ });
368
+ }
369
+ }
370
+ // packages/cli/src/main.ts
371
+ const usage = `eutaxy — deterministic simulation checks for Cloudflare Workers
372
+
373
+ Usage:
374
+ eutaxy check <scenario.sim.ts> [options]
375
+
376
+ Options:
377
+ --wrangler <path> wrangler config (default: wrangler.jsonc/json/toml beside the scenario)
378
+ --seed <seed> exploration seed (default: the scenario file name)
379
+ --max-runs <n> cap on exploration runs in addition to the scenario's time budget
380
+ --budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)
381
+ --exhaustive run every schedule within the bounds once (with partial-order reduction)
382
+ --json print the versioned JSON report instead of text
383
+ --out <path> where to write the regression test on a violation
384
+ --no-regression do not write a regression test
385
+ --expect-violation write a regression test that asserts the violation (for corpora)
386
+ --keep keep the generated .eutaxy/ files
387
+
388
+ Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED spec, 2 UNSUPPORTED, 3 error.
389
+ `;
390
+ async function main(argv, io) {
391
+ const { positionals, flags } = parseArgs(argv, [
392
+ "json",
393
+ "no-regression",
394
+ "expect-violation",
395
+ "keep",
396
+ "help",
397
+ "exhaustive"
398
+ ]);
399
+ const command = positionals[0];
400
+ if (!command || command === "help" || flags["help"] === true) {
401
+ io.stdout(usage);
402
+ return command ? exitCodes.BOUNDED : exitCodes.error;
403
+ }
404
+ if (command !== "check") {
405
+ io.stderr(`unknown command ${command}\n\n${usage}`);
406
+ return exitCodes.error;
407
+ }
408
+ const scenario = positionals[1];
409
+ if (!scenario) {
410
+ io.stderr(`check needs a scenario file\n\n${usage}`);
411
+ return exitCodes.error;
412
+ }
413
+ const str = (k) => typeof flags[k] === "string" ? flags[k] : void 0;
414
+ const maxRunsText = str("max-runs");
415
+ const maxRuns = maxRunsText === void 0 ? void 0 : Number(maxRunsText);
416
+ if (maxRuns !== void 0 && !(Number.isInteger(maxRuns) && maxRuns > 0)) {
417
+ io.stderr(`--max-runs must be a positive integer, got ${JSON.stringify(maxRunsText)}\n`);
418
+ return exitCodes.error;
419
+ }
420
+ const budgetText = str("budget-ms");
421
+ const budgetMs = budgetText === void 0 ? void 0 : Number(budgetText);
422
+ if (budgetMs !== void 0 && !(Number.isInteger(budgetMs) && budgetMs > 0)) {
423
+ io.stderr(`--budget-ms must be a positive integer, got ${JSON.stringify(budgetText)}\n`);
424
+ return exitCodes.error;
425
+ }
426
+ return runCheck({
427
+ scenario,
428
+ cwd: io.cwd,
429
+ ...str("wrangler") ? { wrangler: str("wrangler") } : {},
430
+ ...str("seed") ? { seed: str("seed") } : {},
431
+ ...maxRuns === void 0 ? {} : { maxRuns },
432
+ ...budgetMs === void 0 ? {} : { budgetMs },
433
+ exhaustive: flags["exhaustive"] === true,
434
+ json: flags["json"] === true,
435
+ ...str("out") ? { out: str("out") } : {},
436
+ noRegression: flags["no-regression"] === true,
437
+ expectViolation: flags["expect-violation"] === true,
438
+ keep: flags["keep"] === true,
439
+ stdout: io.stdout,
440
+ stderr: io.stderr
441
+ });
442
+ }
443
+ // packages/cloudflare/src/check.ts
444
+ /** Explore a scenario on a platform and return its verdict. */
445
+ function check(spec, platform, options = { seed: spec.name }) {
446
+ return explore(spec, platform, options);
447
+ }
448
+ /** For use from a test: passes only when the scenario is BOUNDED. */
449
+ async function expectHolds(spec, platform, options) {
450
+ const verdict = await check(spec, platform, options);
451
+ if (verdict.kind !== "BOUNDED") throw new Error(describeVerdict(verdict));
452
+ }
453
+ // packages/cloudflare/src/d1.ts
454
+ /**
455
+ * The D1 binding proxy. Every statement execution is an effect point: the
456
+ * engine decides the fault, the real Miniflare-backed D1 performs the query,
457
+ * and the log records call, result and fault in the documented shape.
458
+ */
459
+ const WRITE$1 = [
460
+ "crash_before",
461
+ "crash_after",
462
+ "ambiguous",
463
+ "error"
464
+ ];
465
+ const READ$1 = [
466
+ "crash_before",
467
+ "crash_after",
468
+ "error"
469
+ ];
470
+ /** Whether a binding is a D1 database (what the proxies and the differential wrap). */
471
+ function isD1(value) {
472
+ return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
473
+ }
474
+ function point(ctx, target, op, args, allowed) {
475
+ return {
476
+ invocation: ctx.currentInvocation(),
477
+ target,
478
+ op,
479
+ args,
480
+ allowed
481
+ };
482
+ }
483
+ function metaOf(result) {
484
+ return {
485
+ changes: result.meta.changes ?? 0,
486
+ lastRowId: result.meta.last_row_id ?? null
487
+ };
488
+ }
489
+ var StatementProxy = class StatementProxy {
490
+ real;
491
+ target;
492
+ ctx;
493
+ sql;
494
+ params;
495
+ constructor(real, target, ctx, sql, params) {
496
+ this.real = real;
497
+ this.target = target;
498
+ this.ctx = ctx;
499
+ this.sql = sql;
500
+ this.params = params;
501
+ }
502
+ /** The real statement, for `batch()`. */
503
+ get statement() {
504
+ return this.real;
505
+ }
506
+ args() {
507
+ return {
508
+ sql: this.sql,
509
+ params: toJson(this.params)
510
+ };
511
+ }
512
+ bind(...values) {
513
+ return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
514
+ }
515
+ run() {
516
+ return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), WRITE$1), () => this.real.run(), (r) => metaOf(r));
517
+ }
518
+ all() {
519
+ return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), READ$1), () => this.real.all(), (r) => ({
520
+ rows: r.results.length,
521
+ changes: r.meta.changes ?? 0
522
+ }));
523
+ }
524
+ first(colName) {
525
+ return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
526
+ ...this.args(),
527
+ column: colName ?? null
528
+ }, READ$1), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
529
+ }
530
+ raw(options) {
531
+ return this.ctx.hooks.effect(point(this.ctx, this.target, "raw", this.args(), READ$1), () => options ? this.real.raw(options) : this.real.raw(), (r) => ({ rows: r.length }));
532
+ }
533
+ };
534
+ /** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
535
+ function proxyD1(real, binding, ctx) {
536
+ const target = `D1:${binding}`;
537
+ const modelled = {
538
+ prepare(sql) {
539
+ return new StatementProxy(real.prepare(sql), target, ctx, sql, []);
540
+ },
541
+ batch(statements) {
542
+ const unwrapped = statements.map((s) => s instanceof StatementProxy ? s.statement : s);
543
+ const args = { statements: statements.map((s) => s instanceof StatementProxy ? {
544
+ sql: s.sql,
545
+ params: toJson(s.params)
546
+ } : "<unproxied statement>") };
547
+ return ctx.hooks.effect(point(ctx, target, "batch", args, WRITE$1), () => real.batch(unwrapped), (rs) => ({
548
+ changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
549
+ statements: rs.length
550
+ }));
551
+ },
552
+ exec(sql) {
553
+ return ctx.hooks.effect(point(ctx, target, "exec", { sql }, WRITE$1), () => real.exec(sql), (r) => ({
554
+ count: r.count,
555
+ duration: 0
556
+ }));
557
+ }
558
+ };
559
+ return new Proxy(real, { get(obj, prop, receiver) {
560
+ if (prop in modelled) return modelled[prop];
561
+ const value = Reflect.get(obj, prop, receiver);
562
+ if (typeof value === "function") {
563
+ ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);
564
+ return value.bind(obj);
565
+ }
566
+ return value;
567
+ } });
568
+ }
569
+ /**
570
+ * Statements in a schema file. Splits on semicolons outside string literals,
571
+ * quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE
572
+ * expressions) whole by tracking BEGIN/CASE ... END nesting.
573
+ */
574
+ function splitSql(sql) {
575
+ const out = [];
576
+ let cur = "";
577
+ let depth = 0;
578
+ let i = 0;
579
+ const isWordChar = (c) => c !== void 0 && /[A-Za-z0-9_]/.test(c);
580
+ while (i < sql.length) {
581
+ const c = sql[i];
582
+ const next = sql[i + 1];
583
+ if (c === "-" && next === "-") {
584
+ while (i < sql.length && sql[i] !== "\n") i++;
585
+ continue;
586
+ }
587
+ if (c === "/" && next === "*") {
588
+ const end = sql.indexOf("*/", i + 2);
589
+ i = end === -1 ? sql.length : end + 2;
590
+ continue;
591
+ }
592
+ if (c === "'" || c === "\"" || c === "`" || c === "[") {
593
+ const close = c === "[" ? "]" : c;
594
+ let j = i + 1;
595
+ for (;;) {
596
+ const k = sql.indexOf(close, j);
597
+ if (k === -1) {
598
+ j = sql.length;
599
+ break;
600
+ }
601
+ if (close !== "]" && sql[k + 1] === close) {
602
+ j = k + 2;
603
+ continue;
604
+ }
605
+ j = k + 1;
606
+ break;
607
+ }
608
+ cur += sql.slice(i, j);
609
+ i = j;
610
+ continue;
611
+ }
612
+ if (isWordChar(c) && !isWordChar(sql[i - 1])) {
613
+ let j = i;
614
+ while (isWordChar(sql[j])) j++;
615
+ const word = sql.slice(i, j);
616
+ const upper = word.toUpperCase();
617
+ if (upper === "BEGIN" || upper === "CASE") depth++;
618
+ else if (upper === "END" && depth > 0) depth--;
619
+ cur += word;
620
+ i = j;
621
+ continue;
622
+ }
623
+ if (c === ";" && depth === 0) {
624
+ const statement = cur.trim();
625
+ if (statement.length > 0) out.push(statement);
626
+ cur = "";
627
+ i++;
628
+ continue;
629
+ }
630
+ cur += c;
631
+ i++;
632
+ }
633
+ const last = cur.trim();
634
+ if (last.length > 0) out.push(last);
635
+ return out;
636
+ }
637
+ /** Drop every user table and re-apply the schema, using the real binding (not an effect). */
638
+ async function resetD1(real, schema) {
639
+ const tables = await real.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\'").all();
640
+ for (const { name } of tables.results) await real.prepare(`DROP TABLE IF EXISTS "${name.replace(/"/g, "\"\"")}"`).run();
641
+ for (const statement of splitSql(schema)) await real.prepare(statement).run();
642
+ }
643
+ /** Every user table's rows, sorted canonically, read through the real binding (not an effect). */
644
+ async function snapshotD1(real) {
645
+ const tables = await real.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\' ORDER BY name").all();
646
+ const out = {};
647
+ for (const { name } of tables.results) out[name] = (await real.prepare(`SELECT * FROM "${name.replace(/"/g, "\"\"")}"`).all()).results.map((r) => toJson(r)).map((j) => [canonicalJson(j), j]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0).map(([, j]) => j);
648
+ return out;
649
+ }
650
+ // packages/cloudflare/src/background.ts
651
+ const CUT_OFF = ["cut_off"];
652
+ /** The `ExecutionContext` handed to a handler; `waitUntil` work is collected to run after it returns. */
653
+ function executionContext(background) {
654
+ return {
655
+ waitUntil: (promise) => {
656
+ background.push(promise.then(() => void 0, () => void 0));
657
+ },
658
+ passThroughOnException: () => {},
659
+ props: {}
660
+ };
661
+ }
662
+ /**
663
+ * Background work extends the invocation but never changes the acknowledgement or the response.
664
+ * A cut-off here is the isolate dying after them: work not yet started is lost.
665
+ */
666
+ async function drainBackground(hooks, inv, invocation, target, background) {
667
+ if (background.length === 0 || inv.isCrashed()) return false;
668
+ try {
669
+ hooks.effectSync({
670
+ invocation,
671
+ target,
672
+ op: "background",
673
+ args: { pending: background.length },
674
+ allowed: CUT_OFF
675
+ }, () => null, () => null);
676
+ await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);
677
+ return false;
678
+ } catch (err) {
679
+ if (!(err instanceof CrashSignal)) throw err;
680
+ return true;
681
+ }
682
+ }
683
+ // packages/cloudflare/src/scenario.ts
684
+ /**
685
+ * Typed construction of scenario specs for Cloudflare Workers. Everything here
686
+ * produces the plain-data `ScenarioSpec` from core; this module only knows the
687
+ * Cloudflare shapes (queues, D1 bindings) and the effect conventions the
688
+ * proxies follow.
689
+ */
690
+ function http(requests, options = {}) {
691
+ return {
692
+ kind: "http",
693
+ requests: requests.map((r, i) => ({
694
+ id: r.id ?? `req-${i + 1}`,
695
+ method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
696
+ path: r.path,
697
+ headers: r.headers ?? {},
698
+ ...r.body === void 0 ? {} : { body: r.body }
699
+ })),
700
+ retries: options.retries ?? 3,
701
+ retryOn: options.retryOn ?? "non-2xx",
702
+ ...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
703
+ ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
704
+ };
705
+ }
706
+ /** The virtual delay before resend number `resend` (1 for the first), per the drive's caller. */
707
+ function retryDelayMs$1(drive, resend) {
708
+ const delays = drive.delaysMs ?? [];
709
+ return delays[Math.min(resend, delays.length) - 1] ?? 0;
710
+ }
711
+ function durableObject(binding, objects = {}, options = {}) {
712
+ return {
713
+ kind: "durable_object",
714
+ binding,
715
+ objects,
716
+ ...options.alarmsPerObject === void 0 ? {} : { alarmsPerObject: options.alarmsPerObject }
717
+ };
718
+ }
719
+ function r2Bucket(binding, objects = {}) {
720
+ return {
721
+ kind: "r2",
722
+ binding,
723
+ objects
724
+ };
725
+ }
726
+ /**
727
+ * Selects an R2 bucket's operations that completed, a `put` by default; a
728
+ * put whose `onlyIf` failed stored nothing and is not selected, as a D1
729
+ * write that changed no row is not.
730
+ */
731
+ function r2Op(binding, op = "put") {
732
+ const target = `R2:${binding}`;
733
+ return op === "put" ? {
734
+ target,
735
+ op,
736
+ kind: "result",
737
+ where: { "result.stored": true }
738
+ } : {
739
+ target,
740
+ op,
741
+ kind: "result"
742
+ };
743
+ }
744
+ /** A bucket's objects at the end of the run as rows `{ key, size, etag, customMetadata, httpMetadata, text? }`. */
745
+ function r2Rows(binding, where) {
746
+ const target = `R2:${binding}`;
747
+ return where ? {
748
+ target,
749
+ table: "objects",
750
+ where
751
+ } : {
752
+ target,
753
+ table: "objects"
754
+ };
755
+ }
756
+ /**
757
+ * Every row the query returns is named by some row of `in` (its `column`
758
+ * equals the row's value at `path`), as with a foreign key.
759
+ */
760
+ function references(name, query, path, inQuery, column) {
761
+ return {
762
+ kind: "references",
763
+ name,
764
+ query,
765
+ path,
766
+ in: inQuery,
767
+ column
768
+ };
769
+ }
770
+ function workflow(binding, className, options = {}) {
771
+ return {
772
+ kind: "workflow",
773
+ binding,
774
+ className,
775
+ ...options.name === void 0 ? {} : { name: options.name }
776
+ };
777
+ }
778
+ /** Selects a Workflow's step attempts, optionally of one step; a failed attempt's result carries its error. */
779
+ function workflowStep(binding, step) {
780
+ return {
781
+ target: `Workflow:${binding}`,
782
+ op: "step_result",
783
+ kind: "result",
784
+ ...step === void 0 ? {} : { where: { "args.step": step } }
785
+ };
786
+ }
787
+ /** A Workflow's instances at the end of the run as rows `{ id, status, params, output?, error? }`. */
788
+ function workflowRows(binding, where) {
789
+ const target = `Workflow:${binding}`;
790
+ return where ? {
791
+ target,
792
+ table: "instances",
793
+ where
794
+ } : {
795
+ target,
796
+ table: "instances"
797
+ };
798
+ }
799
+ /**
800
+ * The storage of one object (by the name its id was made from) as rows
801
+ * `{ key, value }`, for state invariants.
802
+ */
803
+ function durableObjectRows(binding, object, where) {
804
+ const target = `DO:${binding}`;
805
+ return where ? {
806
+ target,
807
+ table: object,
808
+ where
809
+ } : {
810
+ target,
811
+ table: object
812
+ };
813
+ }
814
+ function queue(name, messages) {
815
+ return {
816
+ kind: "queue",
817
+ queue: name,
818
+ messages: messages.map((m, i) => ({
819
+ id: m.id ?? `msg-${i + 1}`,
820
+ body: m.body
821
+ }))
822
+ };
823
+ }
824
+ function d1Schema(binding, schemaFile) {
825
+ return {
826
+ kind: "d1",
827
+ binding,
828
+ schemaFile
829
+ };
830
+ }
831
+ /**
832
+ * Effect conventions for D1 (what the proxies record):
833
+ * call payload { args: { sql, params } }
834
+ * result payload { args: { sql, params }, result: { changes, lastRowId } }
835
+ * A committed write is a `result` whose `result.changes` is at least 1.
836
+ */
837
+ function d1Write(binding, op = "run") {
838
+ return {
839
+ target: `D1:${binding}`,
840
+ op,
841
+ kind: "result",
842
+ atLeast: { "result.changes": 1 }
843
+ };
844
+ }
845
+ /** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */
846
+ function d1Read(binding, op = "first") {
847
+ return {
848
+ target: `D1:${binding}`,
849
+ op,
850
+ kind: "result"
851
+ };
852
+ }
853
+ /** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
854
+ function d1Param(index) {
855
+ return `args.params.${index}`;
856
+ }
857
+ /**
858
+ * The shell follows the core function `decision` (see the `refines`
859
+ * invariant): every selected effect carries out the latest decision of its
860
+ * invocation, agrees with it on `follows`, and, with `state`, was not made
861
+ * stale by another invocation's write between the read it rests on and the
862
+ * effect. The core function's module must be listed in the scenario's
863
+ * `specs`, which is what records its calls.
864
+ */
865
+ function refines(name, decision, effect, options = {}) {
866
+ return {
867
+ kind: "refines",
868
+ name,
869
+ decision,
870
+ effect,
871
+ ...options
872
+ };
873
+ }
874
+ /**
875
+ * Every message's (or request's) `bodyKey` value must appear at least once
876
+ * as `key` in a selected effect: nothing the drive delivered may be lost.
877
+ */
878
+ function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
879
+ if (drive.kind === "queue") return atLeastOncePerMessage$1(name, drive.messages, effect, key, bodyKey);
880
+ const requests = drive.requests.map((r) => ({
881
+ id: r.id,
882
+ body: r.body ?? null
883
+ }));
884
+ return {
885
+ ...atLeastOncePerMessage$1(name, requests, effect, key, bodyKey),
886
+ perMessage: { bodyKey: bodyKey === "" ? "body" : `body.${bodyKey}` }
887
+ };
888
+ }
889
+ /**
890
+ * Selects the responses the Worker returned for a path (`ok` narrows to 2xx
891
+ * or to everything else). One `result` per attempt: a crash before the
892
+ * response leaves none, a thrown error records status 500.
893
+ */
894
+ function httpResponse(path, options = {}) {
895
+ return {
896
+ target: `Http:${path}`,
897
+ op: "response",
898
+ kind: "result",
899
+ ...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
900
+ };
901
+ }
902
+ /** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
903
+ function d1Rows(binding, table, where) {
904
+ return where ? {
905
+ target: `D1:${binding}`,
906
+ table,
907
+ where
908
+ } : {
909
+ target: `D1:${binding}`,
910
+ table
911
+ };
912
+ }
913
+ /** Every row the query selects satisfies all conditions. */
914
+ function everyRow(name, query, holds) {
915
+ return {
916
+ kind: "everyRow",
917
+ name,
918
+ query,
919
+ holds
920
+ };
921
+ }
922
+ /** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */
923
+ function unique(name, query, path) {
924
+ return {
925
+ kind: "unique",
926
+ name,
927
+ query,
928
+ path
929
+ };
930
+ }
931
+ /** Every selected effect has a row whose column equals the effect's key. */
932
+ function implies(name, when, key, state, column) {
933
+ return {
934
+ kind: "implies",
935
+ name,
936
+ when,
937
+ key,
938
+ state,
939
+ column
940
+ };
941
+ }
942
+ /** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
943
+ function queueAck(queueName) {
944
+ return {
945
+ target: `Queue:${queueName}`,
946
+ op: "ack",
947
+ kind: "result",
948
+ where: { "result.effective": true }
949
+ };
950
+ }
951
+ /**
952
+ * Declare an external service: requests to `host` are answered from
953
+ * `responses` (every request gets 200 and an empty body when omitted), and
954
+ * `dedupeBy` names the header whose value makes repeated requests
955
+ * idempotent at that service.
956
+ */
957
+ function external(name, host, options = {}) {
958
+ return {
959
+ name,
960
+ host,
961
+ guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
962
+ ...options.responses ? { responses: options.responses } : {}
963
+ };
964
+ }
965
+ /**
966
+ * Selects the requests to an external that took effect: a request replayed
967
+ * under a dedupe key the external had already seen is not counted.
968
+ */
969
+ function fetchCall(externalName, method) {
970
+ return {
971
+ target: `Fetch:${externalName}`,
972
+ ...method ? { op: method.toUpperCase() } : {},
973
+ kind: "result",
974
+ where: { "result.effective": true }
975
+ };
976
+ }
977
+ function validateHttpDrive(drive) {
978
+ const errors = [];
979
+ if (drive.requests.length === 0) errors.push("http drive needs at least one request");
980
+ const ids = /* @__PURE__ */ new Set();
981
+ drive.requests.forEach((r, i) => {
982
+ if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
983
+ if (!r.method) errors.push(`requests[${i}].method must not be empty`);
984
+ if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
985
+ ids.add(r.id);
986
+ if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
987
+ });
988
+ if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("http drive retries must be a non-negative integer");
989
+ (drive.delaysMs ?? []).forEach((d, i) => {
990
+ if (!(Number.isInteger(d) && d >= 0)) errors.push(`http drive delaysMs[${i}] must be a non-negative integer`);
991
+ });
992
+ if (drive.deadlineMs !== void 0 && !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)) errors.push("http drive deadlineMs must be a positive integer");
993
+ return errors;
994
+ }
995
+ /** Build and validate a scenario spec; throws with every problem listed. */
996
+ function defineScenario(input) {
997
+ const drive = input.drive.kind === "http" ? input.drive : queue(input.drive.queue, input.drive.messages);
998
+ const spec = {
999
+ version: 1,
1000
+ name: input.name,
1001
+ platform: "cloudflare",
1002
+ worker: input.worker,
1003
+ drive,
1004
+ setup: input.setup ?? [],
1005
+ externals: input.externals ?? [],
1006
+ invariants: input.invariants,
1007
+ bounds: {
1008
+ ...defaultBounds,
1009
+ ...input.bounds
1010
+ },
1011
+ ...input.specs ? { specs: input.specs } : {}
1012
+ };
1013
+ const errors = [...validateScenario(spec), ...drive.kind === "http" ? validateHttpDrive(drive) : []];
1014
+ if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
1015
+ return spec;
1016
+ }
1017
+ // packages/cloudflare/src/http.ts
1018
+ /** The response point: a crash before it is a response the caller never saw. */
1019
+ const RESPOND = ["crash_before"];
1020
+ /**
1021
+ * With a caller deadline the answer can also arrive too late: `ambiguous`
1022
+ * here means it was sent, the caller counted it as failed, and the handler
1023
+ * carried on.
1024
+ */
1025
+ const RESPOND_WITH_DEADLINE = ["crash_before", "ambiguous"];
1026
+ /** The URL inbound requests are addressed to; handlers read only the path. */
1027
+ const requestOrigin = "https://worker.test";
1028
+ /** Build the `Request` a drive entry describes. */
1029
+ function requestFor(r) {
1030
+ const headers = new Headers(r.headers);
1031
+ let body = null;
1032
+ if (r.body !== void 0) {
1033
+ if (typeof r.body === "string") body = r.body;
1034
+ else {
1035
+ body = JSON.stringify(r.body);
1036
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
1037
+ }
1038
+ }
1039
+ return new Request(`${requestOrigin}${r.path}`, {
1040
+ method: r.method,
1041
+ headers,
1042
+ body
1043
+ });
1044
+ }
1045
+ /** A compact record of a response for the effect log: status, ok, and a bounded body. */
1046
+ async function summarizeResponse(response) {
1047
+ const text = await response.clone().text();
1048
+ let body = text.length > 1e3 ? `${text.slice(0, 1e3)}…` : text;
1049
+ if (text && (response.headers.get("content-type") ?? "").includes("json")) try {
1050
+ body = JSON.parse(text);
1051
+ } catch {}
1052
+ return {
1053
+ status: response.status,
1054
+ ok: response.ok,
1055
+ body
1056
+ };
1057
+ }
1058
+ /** One attempt of an inbound request, under the caller's retry policy and deadline. */
1059
+ async function deliverRequest(event, hooks, spec, drive, invocation, worker) {
1060
+ const req = event.data;
1061
+ const target = `Http:${req.path}`;
1062
+ const inv = hooks.startInvocation(invocation);
1063
+ const started = Date.now();
1064
+ const background = [];
1065
+ const handler = worker.handler.fetch;
1066
+ if (!handler) throw new Error("the Worker has no fetch() handler");
1067
+ const args = {
1068
+ requestId: event.id,
1069
+ method: req.method,
1070
+ path: req.path
1071
+ };
1072
+ const deadline = drive.deadlineMs;
1073
+ const lateAt = deadline === void 0 ? void 0 : started + deadline;
1074
+ /** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */
1075
+ let decided = false;
1076
+ const giveUp = (at) => {
1077
+ if (decided) return;
1078
+ decided = true;
1079
+ const redeliveries = event.attempt - 1;
1080
+ if (redeliveries < drive.retries && redeliveries < spec.bounds.maxRedeliveries) {
1081
+ const resendAt = Math.max(at + retryDelayMs$1(drive, event.attempt), Date.now());
1082
+ hooks.enqueue({
1083
+ ...event,
1084
+ attempt: event.attempt + 1,
1085
+ ...resendAt > Date.now() ? { at: resendAt } : {}
1086
+ });
1087
+ } else hooks.effectSync({
1088
+ invocation: hooks.bookkeeping(),
1089
+ target,
1090
+ op: "gave_up",
1091
+ args: {
1092
+ requestId: event.id,
1093
+ attempts: event.attempt
1094
+ },
1095
+ allowed: []
1096
+ }, () => null, () => null);
1097
+ };
1098
+ const deadlineTimer = lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
1099
+ let response;
1100
+ const outcome = Promise.resolve().then(() => handler.call(worker.handler, requestFor(req), worker.env, executionContext(background))).then((r) => {
1101
+ response = r;
1102
+ return "completed";
1103
+ }, (err) => err instanceof CrashSignal ? "crashed" : "errored");
1104
+ let status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
1105
+ let summary = null;
1106
+ let read = "errored";
1107
+ if (status === "completed" && response) {
1108
+ read = await Promise.race([hooks.settle(summarizeResponse(response), invocation).then((s) => s, (err) => err instanceof CrashSignal ? "crashed" : "errored"), inv.crashed.then(() => "crashed")]);
1109
+ if (read === "crashed" || read === "errored") status = read;
1110
+ }
1111
+ let late = lateAt !== void 0 && Date.now() > lateAt;
1112
+ const allowed = deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE;
1113
+ if (status === "completed" && typeof read === "object") {
1114
+ const s = read;
1115
+ try {
1116
+ hooks.effectSync({
1117
+ invocation,
1118
+ target,
1119
+ op: "response",
1120
+ args,
1121
+ allowed
1122
+ }, () => s, (v) => v);
1123
+ summary = s;
1124
+ } catch (err) {
1125
+ if (err instanceof CrashSignal) status = "crashed";
1126
+ else if (err instanceof InjectedEffectError) {
1127
+ summary = s;
1128
+ late = true;
1129
+ } else throw err;
1130
+ }
1131
+ } else if (status === "errored") {
1132
+ const s = {
1133
+ status: 500,
1134
+ ok: false,
1135
+ body: ""
1136
+ };
1137
+ hooks.effectSync({
1138
+ invocation,
1139
+ target,
1140
+ op: "response",
1141
+ args,
1142
+ allowed: []
1143
+ }, () => s, (v) => v);
1144
+ summary = s;
1145
+ }
1146
+ if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
1147
+ if (summary !== null && !late && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok)) decided = true;
1148
+ else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
1149
+ if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
1150
+ return {
1151
+ status,
1152
+ followUps: []
1153
+ };
1154
+ }
1155
+ // packages/cloudflare/src/alarms.ts
1156
+ /** `EventRef.source` of an alarm event. */
1157
+ const alarmSource = "durable_object_alarm";
1158
+ /** Crash before: the handler never ran. Crash after: it ran and committed, but counts as failed. */
1159
+ const ALARM = [
1160
+ "crash_before",
1161
+ "crash_after",
1162
+ "error"
1163
+ ];
1164
+ /** Cloudflare retries a failed alarm handler up to six times, after 2 s, 4 s, 8 s, ... */
1165
+ const maxRetries = 6;
1166
+ const firstRetryMs = 2e3;
1167
+ /** The alarms of one namespace's objects; the platform clears it before each run. */
1168
+ var AlarmBook = class {
1169
+ entries = /* @__PURE__ */ new Map();
1170
+ clear() {
1171
+ this.entries.clear();
1172
+ }
1173
+ entry(id) {
1174
+ let e = this.entries.get(id);
1175
+ if (!e) {
1176
+ e = {
1177
+ time: null,
1178
+ seq: 0,
1179
+ gen: 0,
1180
+ firings: 0
1181
+ };
1182
+ this.entries.set(id, e);
1183
+ }
1184
+ return e;
1185
+ }
1186
+ };
1187
+ /** One alarm control per object: setting schedules an event at the alarm's virtual time. */
1188
+ function alarmControl(book, binding, id, object, hooks) {
1189
+ const entry = book.entry(id);
1190
+ return {
1191
+ get: () => entry.time,
1192
+ set: (time) => {
1193
+ entry.time = time;
1194
+ entry.seq++;
1195
+ entry.gen = entry.seq;
1196
+ const data = {
1197
+ binding,
1198
+ gen: entry.gen,
1199
+ id,
1200
+ object,
1201
+ time,
1202
+ retryCount: 0
1203
+ };
1204
+ const now = Date.now();
1205
+ hooks().enqueue({
1206
+ id: `alarm:${binding}:${object}:${entry.seq}`,
1207
+ attempt: 1,
1208
+ source: alarmSource,
1209
+ data,
1210
+ ...time > now ? { at: time } : {}
1211
+ });
1212
+ },
1213
+ delete: () => {
1214
+ entry.time = null;
1215
+ entry.seq++;
1216
+ entry.gen = entry.seq;
1217
+ },
1218
+ unsupported: (reason) => hooks().unsupported(`Durable Object ${binding} ${object}: ${reason}`)
1219
+ };
1220
+ }
1221
+ /** Storage objects whose alarm methods Eutaxy has taken over (one per live instance). */
1222
+ const takenOver = /* @__PURE__ */ new WeakSet();
1223
+ const timeOf = (time) => typeof time === "number" ? time : time.getTime();
1224
+ /** Storage objects whose alarm was read before Eutaxy took them over (in a constructor). */
1225
+ const readBeforeTakeover = /* @__PURE__ */ new WeakSet();
1226
+ /** Storage prototypes whose getAlarm records such reads. */
1227
+ const watched = /* @__PURE__ */ new WeakSet();
1228
+ /**
1229
+ * Record reads of the native alarm on storage not yet taken over: a rebuilt
1230
+ * object's constructor reads native storage, where Eutaxy's pending alarm is
1231
+ * not. The wrapper only records; it returns what the native method returns.
1232
+ */
1233
+ function watchReads(storage) {
1234
+ const proto = Object.getPrototypeOf(storage);
1235
+ if (!proto || watched.has(proto) || typeof proto.getAlarm !== "function") return;
1236
+ watched.add(proto);
1237
+ const native = proto.getAlarm;
1238
+ proto.getAlarm = function(...args) {
1239
+ if (!takenOver.has(this)) readBeforeTakeover.add(this);
1240
+ return native.apply(this, args);
1241
+ };
1242
+ }
1243
+ /**
1244
+ * Replace an object's alarm methods so no real alarm is ever scheduled. An
1245
+ * alarm the object set before the takeover (in its constructor) is moved
1246
+ * over: deleted from the runtime and set on the control, unless an alarm is
1247
+ * still pending, which the constructor could not see in native storage
1248
+ * (Eutaxy keeps it): then the pending one stays and the run is UNSUPPORTED.
1249
+ */
1250
+ async function takeOverAlarms(storage, alarm) {
1251
+ if (takenOver.has(storage)) return;
1252
+ watchReads(storage);
1253
+ takenOver.add(storage);
1254
+ if (readBeforeTakeover.has(storage) && alarm.get() !== null) alarm.unsupported("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");
1255
+ const existing = await storage.getAlarm();
1256
+ if (existing !== null) {
1257
+ await storage.deleteAlarm();
1258
+ if (alarm.get() === null) alarm.set(existing);
1259
+ else alarm.unsupported("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");
1260
+ }
1261
+ const s = storage;
1262
+ let inSync = false;
1263
+ const outsideSync = (op) => {
1264
+ if (inSync) alarm.unsupported(`${op} inside transactionSync() is not modelled`);
1265
+ };
1266
+ Object.assign(s, {
1267
+ setAlarm: async (time) => {
1268
+ outsideSync("setAlarm");
1269
+ alarm.set(timeOf(time));
1270
+ },
1271
+ getAlarm: async () => alarm.get(),
1272
+ deleteAlarm: async () => {
1273
+ outsideSync("deleteAlarm");
1274
+ alarm.delete();
1275
+ }
1276
+ });
1277
+ if (typeof s["transactionSync"] === "function") {
1278
+ const transactionSync = s["transactionSync"].bind(storage);
1279
+ s["transactionSync"] = (callback) => {
1280
+ inSync = true;
1281
+ try {
1282
+ return transactionSync(callback);
1283
+ } finally {
1284
+ inSync = false;
1285
+ }
1286
+ };
1287
+ }
1288
+ const transaction = s["transaction"].bind(storage);
1289
+ s["transaction"] = async (callback) => {
1290
+ let pending;
1291
+ let rolledBack = false;
1292
+ const held = {
1293
+ setAlarm: async (time) => {
1294
+ pending = { time: timeOf(time) };
1295
+ },
1296
+ getAlarm: async () => pending ? pending.time : alarm.get(),
1297
+ deleteAlarm: async () => {
1298
+ pending = { time: null };
1299
+ }
1300
+ };
1301
+ const result = await transaction((txn) => {
1302
+ pending = void 0;
1303
+ rolledBack = false;
1304
+ return callback(new Proxy(txn, { get(target, prop) {
1305
+ if (typeof prop === "string" && prop in held) return held[prop];
1306
+ const value = target[prop];
1307
+ if (prop === "rollback" && typeof value === "function") return (...args) => {
1308
+ rolledBack = true;
1309
+ return value.apply(target, args);
1310
+ };
1311
+ return typeof value === "function" ? value.bind(target) : value;
1312
+ } }));
1313
+ });
1314
+ if (pending && !rolledBack) {
1315
+ if (pending.time === null) alarm.delete();
1316
+ else alarm.set(pending.time);
1317
+ }
1318
+ return result;
1319
+ };
1320
+ }
1321
+ /**
1322
+ * Fire an alarm event: skip it when the object's alarm has since moved or
1323
+ * been deleted, run `alarm()` as one effect otherwise, and schedule a retry
1324
+ * with backoff when the handler fails, crashes, or a fault says it did.
1325
+ */
1326
+ async function deliverAlarm(event, hooks, maxRedeliveries, d) {
1327
+ const a = event.data;
1328
+ const entry = d.book.entry(a.id);
1329
+ if (entry.gen !== a.gen) return {
1330
+ status: "completed",
1331
+ followUps: []
1332
+ };
1333
+ if (a.retryCount === 0) {
1334
+ if (entry.time !== a.time) return {
1335
+ status: "completed",
1336
+ followUps: []
1337
+ };
1338
+ if (entry.firings >= d.limit) {
1339
+ entry.time = null;
1340
+ d.bookkeep("alarm_not_fired", {
1341
+ object: a.object,
1342
+ firings: entry.firings
1343
+ });
1344
+ return {
1345
+ status: "completed",
1346
+ followUps: []
1347
+ };
1348
+ }
1349
+ entry.firings++;
1350
+ }
1351
+ const invocation = `${event.id}#${event.attempt}`;
1352
+ const inv = hooks.startInvocation(invocation);
1353
+ const info = {
1354
+ retryCount: a.retryCount,
1355
+ isRetry: a.retryCount > 0
1356
+ };
1357
+ const outcome = hooks.effect({
1358
+ invocation,
1359
+ target: `DO:${d.binding}`,
1360
+ op: "alarm",
1361
+ args: {
1362
+ object: a.object,
1363
+ retryCount: a.retryCount
1364
+ },
1365
+ allowed: ALARM,
1366
+ hostsEffects: true
1367
+ }, async () => {
1368
+ await d.runAlarm(a.id, a.object, info, a.gen);
1369
+ return null;
1370
+ }, () => null, {
1371
+ onAbandon: () => d.abort(a.id),
1372
+ mayPark: () => d.mayPark(a.id)
1373
+ }).then(() => "completed", (err) => err instanceof CrashSignal ? "crashed" : "errored");
1374
+ const status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
1375
+ if (status === "crashed") await d.evict(a.id);
1376
+ if (status !== "completed") {
1377
+ if (a.retryCount < maxRetries && a.retryCount < maxRedeliveries) {
1378
+ const retryAt = Date.now() + firstRetryMs * 2 ** a.retryCount;
1379
+ const data = {
1380
+ ...a,
1381
+ retryCount: a.retryCount + 1
1382
+ };
1383
+ if (entry.gen === a.gen) entry.time = retryAt;
1384
+ hooks.enqueue({
1385
+ ...event,
1386
+ attempt: event.attempt + 1,
1387
+ data,
1388
+ at: retryAt
1389
+ });
1390
+ } else {
1391
+ if (entry.gen === a.gen) entry.time = null;
1392
+ d.bookkeep("alarm_gave_up", {
1393
+ object: a.object,
1394
+ retries: a.retryCount
1395
+ });
1396
+ }
1397
+ }
1398
+ return {
1399
+ status,
1400
+ followUps: []
1401
+ };
1402
+ }
1403
+ // packages/cloudflare/src/durable-objects.ts
1404
+ /**
1405
+ * The Durable Object namespace proxy. The objects are the real ones workerd
1406
+ * runs: storage, transactions and the input and output gates are the
1407
+ * runtime's own. Eutaxy proxies the boundary a Worker crosses to reach them:
1408
+ * every call on a stub is an effect point, so a call can fail before it
1409
+ * reaches the object (`crash_before`, `error`), or reach it, commit, and
1410
+ * lose its answer (`ambiguous`) or its caller (`crash_after`).
1411
+ *
1412
+ * Between runs every object is cleared, seeded from the scenario's setup
1413
+ * and evicted, so it starts from storage alone; after a run its storage is
1414
+ * snapshotted for state invariants. Both go through the Cloudflare Vitest
1415
+ * plugin's test helpers. Alarms are taken over on each object's storage and
1416
+ * fire in virtual time (see alarms.ts).
1417
+ */
1418
+ const CALL = [
1419
+ "crash_before",
1420
+ "crash_after",
1421
+ "ambiguous",
1422
+ "error"
1423
+ ];
1424
+ const typed = (helpers) => helpers;
1425
+ function isDurableObjectNamespace(value) {
1426
+ return typeof value === "object" && value !== null && typeof value.idFromName === "function" && typeof value.get === "function";
1427
+ }
1428
+ /** How deep each object state is inside blockConcurrencyWhile, while it is. */
1429
+ const gateDepth = /* @__PURE__ */ new WeakMap();
1430
+ /** Object-state prototypes whose blockConcurrencyWhile records that depth. */
1431
+ const gateWatched = /* @__PURE__ */ new WeakSet();
1432
+ /**
1433
+ * Record when an object holds its input gate with blockConcurrencyWhile,
1434
+ * on the state prototype so constructors are covered too; the wrapper only
1435
+ * records and calls the native method.
1436
+ */
1437
+ function watchGate(state) {
1438
+ const proto = Object.getPrototypeOf(state);
1439
+ if (!proto || gateWatched.has(proto) || typeof proto.blockConcurrencyWhile !== "function") return;
1440
+ gateWatched.add(proto);
1441
+ const native = proto.blockConcurrencyWhile;
1442
+ proto.blockConcurrencyWhile = function(callback) {
1443
+ return native.call(this, async () => {
1444
+ gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);
1445
+ try {
1446
+ return await callback();
1447
+ } finally {
1448
+ gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);
1449
+ }
1450
+ });
1451
+ };
1452
+ }
1453
+ /** Whether the object is inside blockConcurrencyWhile now. */
1454
+ function gateHeld(state) {
1455
+ return state !== void 0 && (gateDepth.get(state) ?? 0) > 0;
1456
+ }
1457
+ /** What Eutaxy keeps about one namespace during a run; the platform clears it before each run. */
1458
+ var BindingState = class {
1459
+ /** Names learned this run (seeded ones come back with the setup), so traces never depend on earlier runs. */
1460
+ names = /* @__PURE__ */ new Map();
1461
+ /** Ids of the objects a call or an alarm reached this run. */
1462
+ touched = /* @__PURE__ */ new Set();
1463
+ /** The objects' alarms in virtual time. */
1464
+ alarms = new AlarmBook();
1465
+ /** Each reached object's live state, so an invocation that crashes inside it can reset it. */
1466
+ states = /* @__PURE__ */ new Map();
1467
+ /** Whether the object's own effects may wait for a turn: not while it holds its input gate. */
1468
+ mayPark(id) {
1469
+ return !gateHeld(this.states.get(id));
1470
+ }
1471
+ clear() {
1472
+ this.names.clear();
1473
+ this.touched.clear();
1474
+ this.alarms.clear();
1475
+ this.states.clear();
1476
+ }
1477
+ /**
1478
+ * Reset an object the way a crash does, with `ctx.abort()`, which
1479
+ * application code cannot catch: the runtime ends the requests inside it.
1480
+ * Called where an injected crash happens inside the object's own work,
1481
+ * which is the one place abort() works (from outside, workerd refuses).
1482
+ */
1483
+ abort(id) {
1484
+ const state = this.states.get(id);
1485
+ this.states.delete(id);
1486
+ try {
1487
+ state?.abort("Eutaxy: the invocation crashed inside this object");
1488
+ } catch {}
1489
+ }
1490
+ };
1491
+ /** The storage's own alarm deletion, even after Eutaxy replaced the method on it. */
1492
+ async function deleteRealAlarm(storage) {
1493
+ const proto = Object.getPrototypeOf(storage);
1494
+ await (Object.hasOwn(storage, "deleteAlarm") ? proto.deleteAlarm : storage.deleteAlarm)?.call(storage);
1495
+ }
1496
+ /** An RPC argument as effect-log data; a Request becomes its method and URL. */
1497
+ function argument(value) {
1498
+ if (value instanceof Request) return {
1499
+ method: value.method,
1500
+ url: value.url
1501
+ };
1502
+ return toJson(value);
1503
+ }
1504
+ /**
1505
+ * Whether a result is data the caller holds by value. Anything else (an RPC
1506
+ * capability, an object with methods) would let later calls bypass the
1507
+ * proxy, so it makes the run UNSUPPORTED.
1508
+ */
1509
+ function isPlainData(value, depth = 0) {
1510
+ if (value === null || value === void 0) return true;
1511
+ if (typeof value === "function") return false;
1512
+ if (typeof value !== "object") return true;
1513
+ if (depth > 8) return false;
1514
+ if (value instanceof Response || value instanceof Date) return true;
1515
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;
1516
+ const proto = Object.getPrototypeOf(value);
1517
+ if (Array.isArray(value)) return value.every((v) => isPlainData(v, depth + 1));
1518
+ if (proto !== Object.prototype && proto !== null) return false;
1519
+ return Object.values(value).every((v) => isPlainData(v, depth + 1));
1520
+ }
1521
+ /** An RPC result as effect-log data; a Response becomes its status. */
1522
+ function summarize(result) {
1523
+ if (result instanceof Response) return {
1524
+ status: result.status,
1525
+ ok: result.ok
1526
+ };
1527
+ return toJson(result);
1528
+ }
1529
+ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
1530
+ const target = `DO:${binding}`;
1531
+ const { names, touched, alarms: book } = state;
1532
+ const nameOf = (id) => names.get(id.toString()) ?? id.toString();
1533
+ function stubFor(stub, id, object) {
1534
+ /** Make sure the call may reach the object, and take over its alarms first. */
1535
+ async function reach(real) {
1536
+ if (!helpers) ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`);
1537
+ else if (!isReset()) ctx.hooks.unsupported(`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`);
1538
+ else {
1539
+ touched.add(id);
1540
+ await typed(helpers).runInDurableObject(real, (_instance, live) => {
1541
+ watchGate(live);
1542
+ state.states.set(id, live);
1543
+ return takeOverAlarms(live.storage, alarmControl(book, binding, id, object, () => ctx.hooks));
1544
+ });
1545
+ }
1546
+ }
1547
+ /** A result passed back to the Worker; one that is not plain data cannot be followed. */
1548
+ function plain(result) {
1549
+ if (!isPlainData(result)) ctx.hooks.unsupported(`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`);
1550
+ return result;
1551
+ }
1552
+ /**
1553
+ * The promise a call returns. On a real stub it is an RPC promise that
1554
+ * pipelines property reads (`stub.getData().value`); this one is not, so
1555
+ * a read on it makes the run UNSUPPORTED instead of yielding undefined.
1556
+ */
1557
+ function pipelineGuard(promise) {
1558
+ return new Proxy(promise, { get(target, prop) {
1559
+ if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
1560
+ const value = Reflect.get(target, prop, target);
1561
+ return typeof value === "function" ? value.bind(target) : value;
1562
+ }
1563
+ ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop} on a call's promise) is not supported; await the call first`);
1564
+ } });
1565
+ }
1566
+ /** One effect on the object: a method call, or awaiting an RPC property. */
1567
+ function onObject(op, args, perform) {
1568
+ return ctx.hooks.effect({
1569
+ invocation: ctx.currentInvocation(),
1570
+ target,
1571
+ op,
1572
+ args,
1573
+ allowed: CALL,
1574
+ hostsEffects: true
1575
+ }, perform, summarize, {
1576
+ onAbandon: () => state.abort(id),
1577
+ mayPark: () => state.mayPark(id)
1578
+ });
1579
+ }
1580
+ return new Proxy(stub, { get(real, prop, receiver) {
1581
+ if (prop === "then") return void 0;
1582
+ if (typeof prop !== "string" || prop === "id" || prop === "name") return Reflect.get(real, prop, receiver);
1583
+ const call = (...args) => pipelineGuard(onObject(prop, {
1584
+ object,
1585
+ args: args.map(argument)
1586
+ }, async () => {
1587
+ await reach(real);
1588
+ const method = real[prop];
1589
+ if (typeof method !== "function") throw new TypeError(`${binding} stub has no ${prop}`);
1590
+ return plain(await Reflect.apply(method, real, args));
1591
+ }));
1592
+ const read = () => onObject(prop, {
1593
+ object,
1594
+ property: true
1595
+ }, async () => {
1596
+ await reach(real);
1597
+ return plain(await real[prop]);
1598
+ });
1599
+ const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
1600
+ return new Proxy(call, { get(target, key) {
1601
+ if (key === "then") return awaitable;
1602
+ if (typeof key === "symbol") return Reflect.get(target, key);
1603
+ ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop}.${key}) is not supported; await .${prop} first`);
1604
+ } });
1605
+ } });
1606
+ }
1607
+ function idFromName(name) {
1608
+ const id = real.idFromName(name);
1609
+ names.set(id.toString(), name);
1610
+ return id;
1611
+ }
1612
+ return new Proxy(real, { get(target, prop, receiver) {
1613
+ switch (prop) {
1614
+ case "idFromName": return idFromName;
1615
+ case "idFromString": return (hex) => target.idFromString(hex);
1616
+ case "newUniqueId": return (options) => {
1617
+ ctx.hooks.unsupported(`${binding}.newUniqueId() is random and differs on replay; use idFromName`);
1618
+ return target.newUniqueId(options);
1619
+ };
1620
+ case "get": return (id, options) => stubFor(target.get(id, options), id.toString(), nameOf(id));
1621
+ case "getByName": return (name) => {
1622
+ const id = idFromName(name);
1623
+ return stubFor(target.get(id), id.toString(), name);
1624
+ };
1625
+ case "jurisdiction": return (jurisdiction) => {
1626
+ ctx.hooks.unsupported(`${binding}.jurisdiction() namespaces are not proxied or reset; use the namespace itself`);
1627
+ return target.jurisdiction(jurisdiction);
1628
+ };
1629
+ default: {
1630
+ const value = Reflect.get(target, prop, receiver);
1631
+ return typeof value === "function" ? value.bind(target) : value;
1632
+ }
1633
+ }
1634
+ } });
1635
+ }
1636
+ /** Drop an object's instance from outside it; one that is not running has nothing to drop. */
1637
+ async function evictObject(real, helpers, id) {
1638
+ if (!helpers) return;
1639
+ await typed(helpers).evictDurableObject(real.get(real.idFromString(id))).catch(() => {});
1640
+ }
1641
+ /**
1642
+ * Run an object's `alarm()` handler inside it, after taking over its alarms
1643
+ * (the instance may be new since the alarm was set).
1644
+ */
1645
+ function alarmRunner(real, binding, ctx, helpers, state) {
1646
+ return async (id, object, info, gen) => {
1647
+ if (!helpers) {
1648
+ ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);
1649
+ return;
1650
+ }
1651
+ state.touched.add(id);
1652
+ await typed(helpers).runInDurableObject(real.get(real.idFromString(id)), async (instance, live) => {
1653
+ watchGate(live);
1654
+ state.states.set(id, live);
1655
+ await takeOverAlarms(live.storage, alarmControl(state.alarms, binding, id, object, () => ctx.hooks));
1656
+ const entry = state.alarms.entry(id);
1657
+ if (entry.gen !== gen) return;
1658
+ entry.time = null;
1659
+ const handler = instance.alarm;
1660
+ if (typeof handler !== "function") {
1661
+ ctx.hooks.unsupported(`Durable Object ${binding} ${object} set an alarm but has no alarm() handler`);
1662
+ return;
1663
+ }
1664
+ await handler.call(instance, info);
1665
+ });
1666
+ };
1667
+ }
1668
+ /** The objects to reset: every id the namespace has created, plus the setup's named ones. */
1669
+ async function objectIds(real, helpers, names, seeded) {
1670
+ const ids = /* @__PURE__ */ new Map();
1671
+ for (const id of await typed(helpers).listDurableObjectIds(real)) ids.set(id.toString(), id);
1672
+ for (const name of seeded) {
1673
+ const id = real.idFromName(name);
1674
+ names.set(id.toString(), name);
1675
+ ids.set(id.toString(), id);
1676
+ }
1677
+ return [...ids.values()].sort((a, b) => a.toString() < b.toString() ? -1 : 1);
1678
+ }
1679
+ /**
1680
+ * Clear every object of the namespace, write the seeded entries, and evict
1681
+ * them all, so each run's first call constructs the object from storage.
1682
+ */
1683
+ async function resetNamespace(real, helpers, names, objects) {
1684
+ const { requested } = await withoutNetwork(() => clearAndSeed(real, helpers, names, objects));
1685
+ if (requested) throw new Error("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");
1686
+ }
1687
+ async function clearAndSeed(real, helpers, names, objects) {
1688
+ const ids = await objectIds(real, helpers, names, Object.keys(objects));
1689
+ for (const id of ids) {
1690
+ const stub = real.get(id);
1691
+ const name = names.get(id.toString());
1692
+ const entries = name !== void 0 && Object.hasOwn(objects, name) ? objects[name] : void 0;
1693
+ await typed(helpers).runInDurableObject(stub, async (_instance, state) => {
1694
+ watchGate(state);
1695
+ await state.storage.deleteAll();
1696
+ await deleteRealAlarm(state.storage);
1697
+ if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);
1698
+ });
1699
+ await typed(helpers).evictDurableObject(stub);
1700
+ }
1701
+ }
1702
+ /**
1703
+ * Each object's storage as rows `{ key, value }`, sorted by key, one table
1704
+ * per object name. An object no call reached this run still holds exactly
1705
+ * its seed (reset left it evicted), so its rows come from the seed and it is
1706
+ * not constructed: its constructor would run outside the simulation. Such an
1707
+ * object that is running anyway was reached some other way (through another
1708
+ * object's own binding): `onIndirect` is told, and the seed is not its state.
1709
+ * The tables are the seeded objects and those a call reached, never objects
1710
+ * only earlier runs created, so a snapshot depends on this run alone.
1711
+ */
1712
+ async function snapshotNamespace(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
1713
+ const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported));
1714
+ if (requested) onUnsupported("a Durable Object made a request while its storage was being snapshotted");
1715
+ return value;
1716
+ }
1717
+ async function readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
1718
+ const out = {};
1719
+ for (const id of await objectIds(real, helpers, names, Object.keys(objects))) {
1720
+ const name = names.get(id.toString()) ?? id.toString();
1721
+ if (!touched.has(id.toString())) {
1722
+ if (await typed(helpers).evictDurableObject(real.get(id)).then(() => true, () => false)) onIndirect(name);
1723
+ if (!Object.hasOwn(objects, name)) continue;
1724
+ }
1725
+ const entries = touched.has(id.toString()) ? [...await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {
1726
+ if (!takenOver.has(state.storage)) onUnsupported(`Durable Object ${name} was reset during the run and reconstructed for the snapshot; its constructor ran outside the simulation`);
1727
+ return state.storage.list();
1728
+ })] : Object.entries(Object.hasOwn(objects, name) ? objects[name] ?? {} : {});
1729
+ Object.defineProperty(out, name, {
1730
+ value: entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => ({
1731
+ key,
1732
+ value: toJson(value)
1733
+ })),
1734
+ enumerable: true,
1735
+ writable: true,
1736
+ configurable: true
1737
+ });
1738
+ }
1739
+ return out;
1740
+ }
1741
+ // packages/cloudflare/src/queues.ts
1742
+ const ACK = ["crash_before", "crash_after"];
1743
+ /** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */
1744
+ function cloneJson(value) {
1745
+ return JSON.parse(JSON.stringify(value));
1746
+ }
1747
+ /** One delivery of a queue message, with Queues' at-least-once semantics. */
1748
+ async function deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries) {
1749
+ const queueTarget = `Queue:${drive.queue}`;
1750
+ const inv = hooks.startInvocation(invocation);
1751
+ /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */
1752
+ const state = { decision: null };
1753
+ const background = [];
1754
+ /** Records the call; the result says whether it took effect (the first decision wins). */
1755
+ const decide = (op, args) => {
1756
+ hooks.effectSync({
1757
+ invocation,
1758
+ target: queueTarget,
1759
+ op,
1760
+ args,
1761
+ allowed: ACK
1762
+ }, () => {
1763
+ if (state.decision !== null) return false;
1764
+ state.decision = op;
1765
+ return true;
1766
+ }, (effective) => ({ effective }));
1767
+ };
1768
+ const message = {
1769
+ id: event.id,
1770
+ timestamp: /* @__PURE__ */ new Date(),
1771
+ body: cloneJson(event.data),
1772
+ attempts: event.attempt,
1773
+ ack: () => decide("ack", {
1774
+ messageId: event.id,
1775
+ implicit: false,
1776
+ body: event.data
1777
+ }),
1778
+ retry: () => decide("retry", {
1779
+ messageId: event.id,
1780
+ body: event.data
1781
+ })
1782
+ };
1783
+ const batch = {
1784
+ queue: drive.queue,
1785
+ messages: [message],
1786
+ metadata: { metrics: {
1787
+ backlogCount: 0,
1788
+ backlogBytes: 0
1789
+ } },
1790
+ ackAll: () => message.ack(),
1791
+ retryAll: () => message.retry()
1792
+ };
1793
+ const execution = executionContext(background);
1794
+ const handler = worker.handler.queue;
1795
+ if (!handler) throw new Error("the Worker has no queue() handler");
1796
+ const outcome = Promise.resolve().then(() => handler.call(worker.handler, batch, worker.env, execution)).then(() => "completed", (err) => err instanceof CrashSignal ? "crashed" : "errored");
1797
+ let status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
1798
+ if (status === "completed" && state.decision === null) try {
1799
+ decide("ack", {
1800
+ messageId: event.id,
1801
+ implicit: true,
1802
+ body: event.data
1803
+ });
1804
+ } catch (err) {
1805
+ if (err instanceof CrashSignal) status = "crashed";
1806
+ else throw err;
1807
+ }
1808
+ if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = "crashed";
1809
+ const followUps = [];
1810
+ if (state.decision !== "ack") {
1811
+ const redeliveries = event.attempt - 1;
1812
+ if (event.attempt <= maxRetries && redeliveries < spec.bounds.maxRedeliveries) followUps.push({
1813
+ ...event,
1814
+ attempt: event.attempt + 1
1815
+ });
1816
+ else hooks.effectSync({
1817
+ invocation: hooks.bookkeeping(),
1818
+ target: queueTarget,
1819
+ op: "dead_letter",
1820
+ args: {
1821
+ messageId: event.id,
1822
+ attempts: event.attempt
1823
+ },
1824
+ allowed: []
1825
+ }, () => null, () => null);
1826
+ }
1827
+ return {
1828
+ status,
1829
+ followUps
1830
+ };
1831
+ }
1832
+ // packages/cloudflare/src/r2.ts
1833
+ /**
1834
+ * The R2 binding proxy. Every `put`, `delete`, `get`, `head` and `list` is
1835
+ * an effect point against the real Miniflare-backed bucket. A body is read
1836
+ * inside its `get`'s effect and handed back in an object with the same
1837
+ * fields and body methods: reading it later would be I/O the run cannot
1838
+ * see. An object's random `version` and wall-clock `uploaded` are replaced
1839
+ * by stand-ins (see `VersionBook`), so traces stay byte-identical.
1840
+ */
1841
+ const WRITE = [
1842
+ "crash_before",
1843
+ "crash_after",
1844
+ "ambiguous",
1845
+ "error"
1846
+ ];
1847
+ const READ = [
1848
+ "crash_before",
1849
+ "crash_after",
1850
+ "error"
1851
+ ];
1852
+ /** Whether a binding is an R2 bucket (Miniflare's `R2Bucket`). */
1853
+ function isR2(value) {
1854
+ if (typeof value !== "object" || value === null) return false;
1855
+ const v = value;
1856
+ return [
1857
+ "head",
1858
+ "get",
1859
+ "put",
1860
+ "delete",
1861
+ "list",
1862
+ "createMultipartUpload"
1863
+ ].every((m) => typeof v[m] === "function");
1864
+ }
1865
+ /**
1866
+ * Stand-ins for the version and upload time of each object version the run
1867
+ * sees, in the order it first sees them: versions count up, and the time is
1868
+ * the virtual time it was first seen.
1869
+ */
1870
+ var VersionBook = class {
1871
+ seen = /* @__PURE__ */ new Map();
1872
+ clear() {
1873
+ this.seen.clear();
1874
+ }
1875
+ standIn(realVersion, at) {
1876
+ let s = this.seen.get(realVersion);
1877
+ if (!s) {
1878
+ s = {
1879
+ version: (this.seen.size + 1).toString(16).padStart(32, "0"),
1880
+ uploaded: new Date(at)
1881
+ };
1882
+ this.seen.set(realVersion, s);
1883
+ }
1884
+ return {
1885
+ version: s.version,
1886
+ uploaded: new Date(s.uploaded.getTime())
1887
+ };
1888
+ }
1889
+ };
1890
+ /** An object's metadata, with stand-ins for its version and upload time. */
1891
+ function metadata(real, book, at) {
1892
+ const { version, uploaded } = book.standIn(real.version, at);
1893
+ return {
1894
+ key: real.key,
1895
+ version,
1896
+ size: real.size,
1897
+ etag: real.etag,
1898
+ httpEtag: real.httpEtag,
1899
+ uploaded,
1900
+ httpMetadata: real.httpMetadata,
1901
+ customMetadata: real.customMetadata,
1902
+ range: real.range,
1903
+ checksums: real.checksums,
1904
+ storageClass: real.storageClass,
1905
+ ssecKeyMd5: real.ssecKeyMd5,
1906
+ writeHttpMetadata: (headers) => real.writeHttpMetadata(headers)
1907
+ };
1908
+ }
1909
+ /**
1910
+ * The bytes behind each body stream the proxy hands out. The stream itself
1911
+ * has no known length, which the runtime's put requires, so a put given one
1912
+ * (copying an object) is given its bytes instead.
1913
+ */
1914
+ const buffered = /* @__PURE__ */ new WeakMap();
1915
+ /**
1916
+ * An object with its body, already read: the stream and the body methods
1917
+ * share one consumption, as a real body's do. A method fails once the
1918
+ * stream is read, cancelled or locked by a reader; the stream ends empty
1919
+ * once a method has read the body.
1920
+ */
1921
+ function withBody(meta, bytes) {
1922
+ let used = false;
1923
+ let stream;
1924
+ const take = () => {
1925
+ if (used || stream?.locked) throw new TypeError("Body has already been used");
1926
+ used = true;
1927
+ return bytes.slice();
1928
+ };
1929
+ return Object.defineProperties(meta, {
1930
+ body: {
1931
+ enumerable: true,
1932
+ get: () => {
1933
+ stream ??= new ReadableStream({
1934
+ pull(controller) {
1935
+ if (!used) controller.enqueue(bytes.slice());
1936
+ used = true;
1937
+ controller.close();
1938
+ },
1939
+ cancel() {
1940
+ used = true;
1941
+ }
1942
+ }, { highWaterMark: 0 });
1943
+ buffered.set(stream, take);
1944
+ return stream;
1945
+ }
1946
+ },
1947
+ bodyUsed: {
1948
+ enumerable: true,
1949
+ get: () => used
1950
+ },
1951
+ arrayBuffer: { value: async () => take().buffer },
1952
+ bytes: { value: async () => take() },
1953
+ text: { value: async () => new TextDecoder().decode(take()) },
1954
+ json: { value: async () => JSON.parse(new TextDecoder().decode(take())) },
1955
+ blob: { value: async () => new Blob([take()]) }
1956
+ });
1957
+ }
1958
+ /** Conditions as the trace keeps them: a `Headers` object by its entries. */
1959
+ function conditions(onlyIf) {
1960
+ if (onlyIf === void 0) return {};
1961
+ return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };
1962
+ }
1963
+ /** What the trace keeps of a get's options: the conditions and range, never an encryption key. */
1964
+ function getArgs(key, options) {
1965
+ return toJson({
1966
+ key,
1967
+ ...conditions(options?.onlyIf),
1968
+ ...options?.range === void 0 ? {} : { range: options.range }
1969
+ });
1970
+ }
1971
+ /** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */
1972
+ function putArgs(options) {
1973
+ if (!options) return {};
1974
+ return toJson({
1975
+ ...conditions(options.onlyIf),
1976
+ ...options.customMetadata === void 0 ? {} : { customMetadata: options.customMetadata },
1977
+ ...options.httpMetadata === void 0 ? {} : { httpMetadata: options.httpMetadata }
1978
+ });
1979
+ }
1980
+ function proxyR2(real, binding, ctx, book) {
1981
+ const target = `R2:${binding}`;
1982
+ const point = (op, args, allowed) => ({
1983
+ invocation: ctx.currentInvocation(),
1984
+ target,
1985
+ op,
1986
+ args,
1987
+ allowed
1988
+ });
1989
+ const notModelled = (what) => {
1990
+ const reason = `R2 ${binding}: ${what} is not modelled`;
1991
+ ctx.hooks.unsupported(reason);
1992
+ throw new Error(`eutaxy: ${reason}`);
1993
+ };
1994
+ /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
1995
+ const checkConditions = (onlyIf) => {
1996
+ if (onlyIf instanceof Headers ? ["if-modified-since", "if-unmodified-since"].some((h) => onlyIf.has(h)) : typeof onlyIf === "object" && onlyIf !== null && ("uploadedBefore" in onlyIf || "uploadedAfter" in onlyIf)) ctx.hooks.unsupported(`R2 ${binding}: conditions on the upload time are not modelled`);
1997
+ };
1998
+ const described = (o) => o === null ? { found: false } : {
1999
+ found: true,
2000
+ key: o.key,
2001
+ size: o.size,
2002
+ etag: o.etag
2003
+ };
2004
+ return {
2005
+ put: (key, value, options) => ctx.hooks.effect(point("put", {
2006
+ key,
2007
+ ...putArgs(options)
2008
+ }, WRITE), async () => {
2009
+ checkConditions(options?.onlyIf);
2010
+ const read = value instanceof ReadableStream ? buffered.get(value) : void 0;
2011
+ const stored = await real.put(key, read ? read() : value, options);
2012
+ return stored === null ? null : metadata(stored, book, Date.now());
2013
+ }, (o) => o === null ? { stored: false } : {
2014
+ stored: true,
2015
+ size: o.size,
2016
+ etag: o.etag
2017
+ }),
2018
+ delete: (keys) => ctx.hooks.effect(point("delete", { keys: typeof keys === "string" ? [keys] : [...keys] }, WRITE), () => real.delete(keys), () => null),
2019
+ get: (key, options) => ctx.hooks.effect(point("get", getArgs(key, options), READ), async () => {
2020
+ checkConditions(options?.onlyIf);
2021
+ const o = await real.get(key, options);
2022
+ if (o === null) return null;
2023
+ const meta = metadata(o, book, Date.now());
2024
+ if (!("body" in o)) return meta;
2025
+ return withBody(meta, new Uint8Array(await o.arrayBuffer()));
2026
+ }, (o) => ({
2027
+ ...described(o),
2028
+ ...o !== null ? { body: "body" in o } : {}
2029
+ })),
2030
+ head: (key) => ctx.hooks.effect(point("head", { key }, READ), async () => {
2031
+ const o = await real.head(key);
2032
+ return o === null ? null : metadata(o, book, Date.now());
2033
+ }, described),
2034
+ list: (options) => ctx.hooks.effect(point("list", toJson(options ?? {}), READ), async () => {
2035
+ const listed = await real.list(options);
2036
+ const at = Date.now();
2037
+ return {
2038
+ ...listed,
2039
+ objects: listed.objects.map((o) => metadata(o, book, at))
2040
+ };
2041
+ }, (l) => ({
2042
+ keys: l.objects.map((o) => o.key),
2043
+ truncated: l.truncated,
2044
+ delimitedPrefixes: l.delimitedPrefixes
2045
+ })),
2046
+ createMultipartUpload: () => notModelled("createMultipartUpload()"),
2047
+ resumeMultipartUpload: () => notModelled("resumeMultipartUpload()")
2048
+ };
2049
+ }
2050
+ /** Every object of the bucket, through all pages of a listing. */
2051
+ async function allObjects(real) {
2052
+ const out = [];
2053
+ let cursor;
2054
+ for (;;) {
2055
+ const page = await real.list({
2056
+ include: ["customMetadata", "httpMetadata"],
2057
+ ...cursor === void 0 ? {} : { cursor }
2058
+ });
2059
+ out.push(...page.objects);
2060
+ if (!page.truncated) return out;
2061
+ cursor = page.cursor;
2062
+ }
2063
+ }
2064
+ /** Empty the bucket and put its seeds, before a run. */
2065
+ async function resetR2(real, seeds) {
2066
+ const keys = (await allObjects(real)).map((o) => o.key);
2067
+ for (let i = 0; i < keys.length; i += 1e3) await real.delete(keys.slice(i, i + 1e3));
2068
+ for (const [key, seed] of Object.entries(seeds)) if (typeof seed === "string") await real.put(key, seed);
2069
+ else await real.put(key, seed.value, {
2070
+ ...seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {},
2071
+ ...seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}
2072
+ });
2073
+ }
2074
+ /** Largest object whose text the snapshot keeps. */
2075
+ const snapshotTextLimit = 4096;
2076
+ /**
2077
+ * The bucket's objects as rows `{ key, size, etag, customMetadata,
2078
+ * httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is
2079
+ * valid UTF-8. Versions and upload times are left out: they are the store's,
2080
+ * not the Worker's.
2081
+ */
2082
+ async function snapshotR2(real) {
2083
+ const rows = [];
2084
+ const objects = (await allObjects(real)).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
2085
+ for (const o of objects) {
2086
+ let text;
2087
+ if (o.size <= snapshotTextLimit) {
2088
+ const body = await real.get(o.key);
2089
+ if (body && "body" in body) try {
2090
+ text = new TextDecoder("utf-8", {
2091
+ fatal: true,
2092
+ ignoreBOM: false
2093
+ }).decode(await body.arrayBuffer());
2094
+ } catch {}
2095
+ }
2096
+ rows.push(toJson({
2097
+ key: o.key,
2098
+ size: o.size,
2099
+ etag: o.etag,
2100
+ customMetadata: o.customMetadata ?? {},
2101
+ httpMetadata: o.httpMetadata ?? {},
2102
+ ...text === void 0 ? {} : { text }
2103
+ }));
2104
+ }
2105
+ return rows;
2106
+ }
2107
+ // packages/cloudflare/src/workflows.ts
2108
+ /**
2109
+ * Workflows, modelled: the binding's `create`/`get`, and each instance run
2110
+ * as invocations of its class's `run(event, step)` against a model of the
2111
+ * engine (persisted step results, retries in virtual time, restarts that
2112
+ * re-run `run` from the start). The real local engine is never called: it
2113
+ * runs on its own real-time clock and retry loop, which Eutaxy can neither
2114
+ * fault nor schedule. See docs/design.md, "Workflows".
2115
+ */
2116
+ /** The `EventRef.source` of a Workflow instance's run. */
2117
+ const workflowSource = "workflow";
2118
+ /** `create` is a call to the engine: it may never arrive, or arrive with its answer lost. */
2119
+ const CREATE = [
2120
+ "crash_before",
2121
+ "crash_after",
2122
+ "ambiguous",
2123
+ "error"
2124
+ ];
2125
+ /** Before a step's callback: the engine restarts before the step runs. */
2126
+ const STEP_START = ["crash_before"];
2127
+ /**
2128
+ * After it: the engine restarts after the step ran but before its result
2129
+ * was persisted (`crash_after`), or the attempt ran and counted as failed,
2130
+ * as a timeout does (`ambiguous`).
2131
+ */
2132
+ const STEP_RESULT = ["crash_after", "ambiguous"];
2133
+ /**
2134
+ * Cloudflare's defaults for a step without a config (Workflows, Sleeping
2135
+ * and retrying). A partial config is merged with them field by field, as
2136
+ * the engine does. Miniflare's local engine waits 1 s by default; the
2137
+ * model keeps the documented 10 s.
2138
+ */
2139
+ const defaultRetries = {
2140
+ limit: 5,
2141
+ delay: 1e4,
2142
+ backoff: "exponential"
2143
+ };
2144
+ /** One binding's instances in the current run. */
2145
+ var WorkflowRegistry = class {
2146
+ instances = /* @__PURE__ */ new Map();
2147
+ clear() {
2148
+ this.instances.clear();
2149
+ }
2150
+ /** The instances as rows for the end-of-run snapshot, by id. */
2151
+ rows() {
2152
+ return [...this.instances.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).map((i) => ({
2153
+ id: i.id,
2154
+ status: i.status,
2155
+ params: toJson(i.params),
2156
+ ...i.output === void 0 ? {} : { output: toJson(i.output) },
2157
+ ...i.error === void 0 ? {} : { error: `${i.error.name}: ${i.error.message}` }
2158
+ }));
2159
+ }
2160
+ };
2161
+ /** A Workflow binding as the env shows it (Miniflare's `WorkflowImpl`). */
2162
+ function isWorkflowBinding(value) {
2163
+ if (typeof value !== "object" || value === null) return false;
2164
+ const v = value;
2165
+ return typeof v["create"] === "function" && typeof v["createBatch"] === "function" && typeof v["get"] === "function";
2166
+ }
2167
+ /** The binding's proxy: instances live in the registry and run as events, never in the real engine. */
2168
+ function proxyWorkflow(binding, ctx, registry) {
2169
+ const target = `Workflow:${binding}`;
2170
+ const unsupported = (what) => {
2171
+ const reason = `Workflow ${binding}: ${what} is not modelled`;
2172
+ ctx.hooks.unsupported(reason);
2173
+ throw new Error(`eutaxy: ${reason}`);
2174
+ };
2175
+ const handle = (id) => ({
2176
+ id,
2177
+ status: () => ctx.hooks.effect({
2178
+ invocation: ctx.currentInvocation(),
2179
+ target,
2180
+ op: "status",
2181
+ args: { id },
2182
+ allowed: []
2183
+ }, async () => {
2184
+ const i = registry.instances.get(id);
2185
+ if (!i) throw new Error("instance.not_found");
2186
+ return {
2187
+ status: i.status,
2188
+ output: i.output === void 0 ? null : structuredClone(i.output),
2189
+ ...i.error === void 0 ? {} : { error: { ...i.error } }
2190
+ };
2191
+ }, (s) => toJson(s)),
2192
+ pause: () => unsupported("pause()"),
2193
+ resume: () => unsupported("resume()"),
2194
+ terminate: () => unsupported("terminate()"),
2195
+ restart: () => unsupported("restart()"),
2196
+ sendEvent: () => unsupported("sendEvent()"),
2197
+ delete: () => unsupported("delete()"),
2198
+ subscribe: () => unsupported("subscribe()")
2199
+ });
2200
+ return {
2201
+ async create(options = {}) {
2202
+ const id = options.id ?? crypto.randomUUID();
2203
+ const params = structuredClone(options.params === void 0 ? {} : options.params);
2204
+ return ctx.hooks.effect({
2205
+ invocation: ctx.currentInvocation(),
2206
+ target,
2207
+ op: "create",
2208
+ args: {
2209
+ id,
2210
+ params: toJson(params)
2211
+ },
2212
+ allowed: CREATE
2213
+ }, async () => {
2214
+ if (!validInstanceId(id)) throw new Error("Workflow instance has invalid id");
2215
+ if (registry.instances.has(id)) throw new Error(`(instance.already_exists) Workflow instance with id "${id}" already exists`);
2216
+ registry.instances.set(id, {
2217
+ id,
2218
+ params,
2219
+ createdAt: Date.now(),
2220
+ status: "queued",
2221
+ persisted: /* @__PURE__ */ new Map(),
2222
+ attempts: /* @__PURE__ */ new Map(),
2223
+ configs: /* @__PURE__ */ new Map(),
2224
+ deadlines: /* @__PURE__ */ new Map()
2225
+ });
2226
+ ctx.hooks.enqueue({
2227
+ id: `workflow:${binding}:${id}`,
2228
+ attempt: 1,
2229
+ source: workflowSource,
2230
+ data: {
2231
+ binding,
2232
+ id
2233
+ }
2234
+ });
2235
+ return handle(id);
2236
+ }, () => ({ id }));
2237
+ },
2238
+ async get(id) {
2239
+ return ctx.hooks.effect({
2240
+ invocation: ctx.currentInvocation(),
2241
+ target,
2242
+ op: "get",
2243
+ args: { id },
2244
+ allowed: []
2245
+ }, async () => {
2246
+ if (!registry.instances.has(id)) throw new Error("instance.not_found");
2247
+ return handle(id);
2248
+ }, () => ({ id }));
2249
+ },
2250
+ createBatch: () => unsupported("createBatch()"),
2251
+ deleteBatch: () => unsupported("deleteBatch()")
2252
+ };
2253
+ }
2254
+ /** The binding's rule for an instance id (Miniflare): up to 100 of these characters. */
2255
+ function validInstanceId(id) {
2256
+ return typeof id === "string" && id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(id);
2257
+ }
2258
+ /** Sets `ctx` and `env` as `WorkflowEntrypoint` does, for the one `new` workerd would refuse. */
2259
+ var StandInEntrypoint = class {
2260
+ ctx;
2261
+ env;
2262
+ constructor(ctx, env) {
2263
+ this.ctx = ctx;
2264
+ this.env = env;
2265
+ }
2266
+ };
2267
+ /**
2268
+ * Construct a `WorkflowEntrypoint` subclass outside the runtime. workerd's
2269
+ * base constructor accepts only a native ExecutionContext, so for this one
2270
+ * synchronous `new` the class that extends it directly extends a stand-in
2271
+ * instead; its own constructor and field initialisers run as written, and
2272
+ * the base is put back before anything else can run.
2273
+ */
2274
+ function constructWorkflow(cls, ctx, env) {
2275
+ if (typeof cls !== "function") throw new TypeError("not a class");
2276
+ let direct = cls;
2277
+ for (;;) {
2278
+ const parent = Object.getPrototypeOf(direct);
2279
+ if (typeof parent !== "function" || parent === Function.prototype) throw new TypeError(`${cls.name} does not extend WorkflowEntrypoint`);
2280
+ if (parent.name === "WorkflowEntrypoint") break;
2281
+ direct = parent;
2282
+ }
2283
+ const base = Object.getPrototypeOf(direct);
2284
+ Object.setPrototypeOf(direct, StandInEntrypoint);
2285
+ try {
2286
+ return Reflect.construct(cls, [ctx, env]);
2287
+ } finally {
2288
+ Object.setPrototypeOf(direct, base);
2289
+ }
2290
+ }
2291
+ /** The engine's conversion (itty-time): a year is 365.25 days, a month 30; an unknown unit counts 1. */
2292
+ const units = {
2293
+ year: 315576e5,
2294
+ month: 2592e6,
2295
+ week: 6048e5,
2296
+ day: 864e5,
2297
+ hour: 36e5,
2298
+ minute: 6e4,
2299
+ second: 1e3,
2300
+ m: 1
2301
+ };
2302
+ /** The engine's reading of a duration, NaN where it reads none. */
2303
+ function engineDuration(d) {
2304
+ if (!Number.isNaN(Number(d)) && typeof d !== "object") return Number(d);
2305
+ if (typeof d !== "string") return NaN;
2306
+ const m = /^([^ ]+) +(\w\w*?)s?$/.exec(d);
2307
+ if (!m) return NaN;
2308
+ return Number(m[1]) * (units[m[2]] ?? 1);
2309
+ }
2310
+ /** A Workflows duration in milliseconds, read as the engine reads it. */
2311
+ function durationMs(d) {
2312
+ const ms = engineDuration(d);
2313
+ if (Number.isNaN(ms) || ms < 0) throw new TypeError(`not a Workflows duration: ${String(d)}`);
2314
+ return ms;
2315
+ }
2316
+ /** Miniflare's `isValidStepConfig`, exactly: its schema is strict, and a timeout `== 0` is refused. */
2317
+ function validStepConfig(config) {
2318
+ const only = (o, keys) => Object.keys(o).every((k) => keys.includes(k));
2319
+ const durationOk = (v) => !Number.isNaN(engineDuration(v));
2320
+ if (typeof config !== "object" || config === null || !only(config, [
2321
+ "retries",
2322
+ "timeout",
2323
+ "sensitive"
2324
+ ])) return false;
2325
+ const c = config;
2326
+ const r = c["retries"];
2327
+ if (r !== void 0) {
2328
+ if (typeof r !== "object" || r === null || !only(r, [
2329
+ "delay",
2330
+ "limit",
2331
+ "backoff"
2332
+ ])) return false;
2333
+ const delay = r["delay"];
2334
+ if (!(typeof delay === "function" || typeof delay === "string" || typeof delay === "number" && delay >= 0)) return false;
2335
+ if (typeof r["limit"] !== "number" || r["limit"] < 0) return false;
2336
+ if (r["backoff"] !== void 0 && ![
2337
+ "constant",
2338
+ "linear",
2339
+ "exponential"
2340
+ ].includes(r["backoff"])) return false;
2341
+ if (typeof delay !== "function" && !durationOk(delay)) return false;
2342
+ }
2343
+ const t = c["timeout"];
2344
+ if (t !== void 0) {
2345
+ if (!(typeof t === "string" || typeof t === "number" && t >= 0)) return false;
2346
+ if (t == 0 || !durationOk(t)) return false;
2347
+ }
2348
+ if (c["sensitive"] !== void 0 && c["sensitive"] !== "output") return false;
2349
+ return true;
2350
+ }
2351
+ const utf8 = new TextEncoder();
2352
+ /** About how many bytes a value takes stored, walking it as structured cloning does. */
2353
+ function approximateBytes(value, seen = /* @__PURE__ */ new Set()) {
2354
+ if (value === null || value === void 0) return 1;
2355
+ switch (typeof value) {
2356
+ case "string": return utf8.encode(value).length;
2357
+ case "number":
2358
+ case "bigint": return 8;
2359
+ case "boolean": return 1;
2360
+ case "object": break;
2361
+ default: return 0;
2362
+ }
2363
+ const o = value;
2364
+ if (seen.has(o)) return 0;
2365
+ seen.add(o);
2366
+ if (o instanceof ArrayBuffer || ArrayBuffer.isView(o)) return o.byteLength;
2367
+ if (o instanceof Date) return 8;
2368
+ let total = 0;
2369
+ if (o instanceof Map) for (const [k, v] of o) total += approximateBytes(k, seen) + approximateBytes(v, seen);
2370
+ else if (o instanceof Set) for (const v of o) total += approximateBytes(v, seen);
2371
+ else for (const [k, v] of Object.entries(o)) total += utf8.encode(k).length + approximateBytes(v, seen);
2372
+ return total;
2373
+ }
2374
+ function sleep(ms) {
2375
+ return new Promise((resolve) => setTimeout(resolve, ms));
2376
+ }
2377
+ /**
2378
+ * One engine attempt of an instance: construct its class and call `run`.
2379
+ * Steps whose results were persisted return them without running; a crash
2380
+ * restarts the instance (a new attempt, from the start of `run`).
2381
+ */
2382
+ async function deliverWorkflow(event, hooks, d) {
2383
+ const invocation = `${event.id}#${event.attempt}`;
2384
+ const inv = hooks.startInvocation(invocation);
2385
+ const target = `Workflow:${d.binding}`;
2386
+ const instance = d.instance;
2387
+ instance.status = "running";
2388
+ const background = [];
2389
+ const counts = /* @__PURE__ */ new Map();
2390
+ const key = (kind, name) => {
2391
+ const count = (counts.get(`${kind}:${name}`) ?? 0) + 1;
2392
+ counts.set(`${kind}:${name}`, count);
2393
+ return `${kind}:${name}#${count}`;
2394
+ };
2395
+ const replay = (o) => {
2396
+ if (o.ok) return structuredClone(o.value);
2397
+ throw structuredClone(o.error);
2398
+ };
2399
+ const step = {
2400
+ do: async (name, a, b, c) => {
2401
+ const [config, fn, options] = typeof a === "function" ? [
2402
+ {},
2403
+ a,
2404
+ b
2405
+ ] : [
2406
+ a ?? {},
2407
+ b,
2408
+ c
2409
+ ];
2410
+ if (options?.rollback !== void 0) {
2411
+ hooks.unsupported(`Workflow ${d.binding}: rollback handlers are not modelled`);
2412
+ throw new Error("eutaxy: rollback handlers are not modelled");
2413
+ }
2414
+ const fatal = (message) => {
2415
+ hooks.unsupported(`Workflow ${d.binding}: ${message}`);
2416
+ const err = new Error(message);
2417
+ err.name = "WorkflowFatalError";
2418
+ throw err;
2419
+ };
2420
+ if (name.length > 256 || [...name].some((c) => c.charCodeAt(0) < 32)) fatal(`Step name "${name}" exceeds max length (256 chars) or invalid characters found`);
2421
+ if (!validStepConfig(config)) fatal(`Step config for "${name}" is in a invalid format. See https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/`);
2422
+ const k = key("do", name);
2423
+ const count = counts.get(`do:${name}`);
2424
+ const done = instance.persisted.get(k);
2425
+ if (done) return replay(done);
2426
+ const live = {
2427
+ ...defaultRetries,
2428
+ ...config.retries
2429
+ };
2430
+ const first = instance.configs.get(k);
2431
+ if (!first) instance.configs.set(k, {
2432
+ retries: live,
2433
+ timeout: config.timeout ?? "10 minutes",
2434
+ ...config.sensitive === void 0 ? {} : { sensitive: config.sensitive }
2435
+ });
2436
+ const sensitive = first ? first.sensitive : config.sensitive;
2437
+ const stored = first?.retries;
2438
+ const retries = stored && typeof stored.delay === "function" ? {
2439
+ ...stored,
2440
+ delay: typeof live.delay === "function" ? live.delay : defaultRetries.delay
2441
+ } : stored ?? live;
2442
+ const limit = Math.min(retries.limit, d.maxRedeliveries);
2443
+ const { delay, ...shown } = retries;
2444
+ const resolved = {
2445
+ retries: typeof delay === "function" ? shown : retries,
2446
+ timeout: first ? first.timeout : config.timeout ?? "10 minutes",
2447
+ ...sensitive === void 0 ? {} : { sensitive }
2448
+ };
2449
+ for (let attempt = (instance.attempts.get(k) ?? 0) + 1;; attempt++) {
2450
+ const due = instance.deadlines.get(`retry:${k}`);
2451
+ if (due !== void 0) {
2452
+ await sleep(Math.max(0, due - Date.now()));
2453
+ instance.deadlines.delete(`retry:${k}`);
2454
+ }
2455
+ const stepContext = {
2456
+ step: {
2457
+ name,
2458
+ count
2459
+ },
2460
+ attempt,
2461
+ config: {
2462
+ ...resolved,
2463
+ retries: { ...resolved.retries }
2464
+ }
2465
+ };
2466
+ const args = {
2467
+ instance: instance.id,
2468
+ step: name,
2469
+ count,
2470
+ attempt
2471
+ };
2472
+ await hooks.effect({
2473
+ invocation,
2474
+ target,
2475
+ op: "step",
2476
+ args,
2477
+ allowed: STEP_START
2478
+ }, async () => null, () => null);
2479
+ instance.attempts.set(k, attempt);
2480
+ let failed = false;
2481
+ let thrown;
2482
+ let value;
2483
+ let returned;
2484
+ try {
2485
+ returned = { value: await fn(stepContext) };
2486
+ } catch (err) {
2487
+ if (err instanceof CrashSignal || inv.isCrashed()) throw err;
2488
+ failed = true;
2489
+ thrown = err;
2490
+ try {
2491
+ hooks.effectSync({
2492
+ invocation,
2493
+ target,
2494
+ op: "step_result",
2495
+ args,
2496
+ allowed: []
2497
+ }, () => {
2498
+ throw err;
2499
+ }, () => null);
2500
+ } catch {}
2501
+ }
2502
+ if (returned !== void 0) {
2503
+ const notModelled = (reason) => {
2504
+ hooks.unsupported(`Workflow ${d.binding}: step "${name}" ${reason}`);
2505
+ throw new Error(`eutaxy: step "${name}" ${reason}`);
2506
+ };
2507
+ try {
2508
+ value = structuredClone(returned.value);
2509
+ } catch {
2510
+ notModelled("returned a value that is not structured-cloneable (a ReadableStream is not modelled)");
2511
+ }
2512
+ if (approximateBytes(value) > 1048576) notModelled("returned more than about 1 MiB, which the engine refuses (\"output is too large\"); Eutaxy cannot measure the stored size exactly");
2513
+ }
2514
+ if (!failed) try {
2515
+ await hooks.effect({
2516
+ invocation,
2517
+ target,
2518
+ op: "step_result",
2519
+ args,
2520
+ allowed: STEP_RESULT
2521
+ }, async () => value, (v) => ({ output: sensitive === "output" ? "[REDACTED]" : toJson(v) }));
2522
+ instance.persisted.set(k, {
2523
+ ok: true,
2524
+ value
2525
+ });
2526
+ return structuredClone(value);
2527
+ } catch (err) {
2528
+ if (err instanceof CrashSignal || !(err instanceof InjectedEffectError)) throw err;
2529
+ thrown = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${durationMs(resolved.timeout)}ms`), { name: "WorkflowTimeoutError" });
2530
+ }
2531
+ if (thrown instanceof Error && (thrown.name === "NonRetryableError" || thrown.message.startsWith("NonRetryableError"))) throw thrown;
2532
+ if (attempt > limit) {
2533
+ let kept;
2534
+ try {
2535
+ kept = structuredClone(thrown);
2536
+ } catch {
2537
+ kept = new Error(String(thrown));
2538
+ }
2539
+ instance.persisted.set(k, {
2540
+ ok: false,
2541
+ error: kept
2542
+ });
2543
+ throw thrown;
2544
+ }
2545
+ let wait;
2546
+ try {
2547
+ const delayContext = {
2548
+ step: {
2549
+ name,
2550
+ count
2551
+ },
2552
+ attempt,
2553
+ config: {
2554
+ ...resolved,
2555
+ retries: { ...resolved.retries }
2556
+ }
2557
+ };
2558
+ wait = await retryDelayMs(retries, attempt, delayContext, thrown);
2559
+ } catch (err) {
2560
+ hooks.unsupported(`Workflow ${d.binding}: step "${name}"'s retry delay function threw (${String(err)})`);
2561
+ throw err;
2562
+ }
2563
+ instance.deadlines.set(`retry:${k}`, Date.now() + wait);
2564
+ await sleep(wait);
2565
+ instance.deadlines.delete(`retry:${k}`);
2566
+ }
2567
+ },
2568
+ sleep: async (name, duration) => {
2569
+ const ms = durationMs(duration);
2570
+ await sleepStep(key("sleep", `${name}\u0000${ms}`), name, ms);
2571
+ },
2572
+ sleepUntil: async (name, timestamp) => {
2573
+ const at = timestamp instanceof Date ? timestamp.getTime() : Number(timestamp);
2574
+ const k = key("sleepUntil", `${name}\u0000${at}`);
2575
+ if (instance.persisted.has(k)) {
2576
+ if (at < Date.now()) hooks.unsupported(`Workflow ${d.binding}: step.sleepUntil "${name}" replayed after its time, where Miniflare's engine throws`);
2577
+ return;
2578
+ }
2579
+ if (at < Date.now() && !instance.deadlines.has(k)) throw new Error("You can't sleep until a time in the past, time-traveler");
2580
+ await sleepStep(k, name, Math.max(0, at - Date.now()), at);
2581
+ },
2582
+ waitForEvent: () => {
2583
+ hooks.unsupported(`Workflow ${d.binding}: step.waitForEvent is not modelled`);
2584
+ throw new Error("eutaxy: step.waitForEvent is not modelled");
2585
+ }
2586
+ };
2587
+ async function sleepStep(k, name, ms, until) {
2588
+ if (instance.persisted.has(k)) return;
2589
+ const pending = instance.deadlines.get(k);
2590
+ if (pending !== void 0) {
2591
+ await sleep(Math.max(0, pending - Date.now()));
2592
+ instance.persisted.set(k, {
2593
+ ok: true,
2594
+ value: null
2595
+ });
2596
+ return;
2597
+ }
2598
+ instance.deadlines.set(k, Date.now() + ms);
2599
+ hooks.effectSync({
2600
+ invocation,
2601
+ target,
2602
+ op: "sleep",
2603
+ args: {
2604
+ instance: instance.id,
2605
+ step: name,
2606
+ ms,
2607
+ ...until === void 0 ? {} : { until }
2608
+ },
2609
+ allowed: []
2610
+ }, () => null, () => null);
2611
+ await sleep(ms);
2612
+ instance.persisted.set(k, {
2613
+ ok: true,
2614
+ value: null
2615
+ });
2616
+ }
2617
+ const outcome = Promise.resolve().then(() => {
2618
+ const flow = constructWorkflow(d.cls, executionContext(background), d.env);
2619
+ const workflowEvent = {
2620
+ payload: structuredClone(instance.params),
2621
+ timestamp: new Date(instance.createdAt),
2622
+ instanceId: instance.id
2623
+ };
2624
+ if (d.name !== void 0) workflowEvent["workflowName"] = d.name;
2625
+ else Object.defineProperty(workflowEvent, "workflowName", {
2626
+ enumerable: true,
2627
+ get: () => {
2628
+ hooks.unsupported(`Workflow ${d.binding}: event.workflowName needs the Workflow's name, workflow(binding, className, { name })`);
2629
+ }
2630
+ });
2631
+ return flow.run(workflowEvent, step);
2632
+ }).then((value) => {
2633
+ try {
2634
+ return {
2635
+ status: "completed",
2636
+ value: structuredClone(value)
2637
+ };
2638
+ } catch {
2639
+ hooks.unsupported(`Workflow ${d.binding}: run() returned a value that is not structured-cloneable`);
2640
+ return {
2641
+ status: "errored",
2642
+ error: /* @__PURE__ */ new Error("run() returned a value that is not structured-cloneable")
2643
+ };
2644
+ }
2645
+ }, (error) => error instanceof CrashSignal ? { status: "crashed" } : {
2646
+ status: "errored",
2647
+ error
2648
+ });
2649
+ const result = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => ({ status: "crashed" }))]);
2650
+ let status = result.status;
2651
+ if (result.status === "completed") {
2652
+ instance.status = "complete";
2653
+ instance.output = result.value;
2654
+ hooks.effectSync({
2655
+ invocation,
2656
+ target,
2657
+ op: "complete",
2658
+ args: {
2659
+ instance: instance.id,
2660
+ output: toJson(instance.output)
2661
+ },
2662
+ allowed: []
2663
+ }, () => null, () => null);
2664
+ } else if (result.status === "errored") {
2665
+ instance.status = "errored";
2666
+ const e = result.error;
2667
+ instance.error = e instanceof Error ? {
2668
+ name: e.name,
2669
+ message: e.message
2670
+ } : {
2671
+ name: "Error",
2672
+ message: String(e)
2673
+ };
2674
+ hooks.effectSync({
2675
+ invocation,
2676
+ target,
2677
+ op: "errored",
2678
+ args: {
2679
+ instance: instance.id,
2680
+ error: `${instance.error.name}: ${instance.error.message}`
2681
+ },
2682
+ allowed: []
2683
+ }, () => null, () => null);
2684
+ }
2685
+ if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
2686
+ const followUps = status === "crashed" && instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
2687
+ ...event,
2688
+ attempt: event.attempt + 1
2689
+ }] : [];
2690
+ return {
2691
+ status,
2692
+ followUps
2693
+ };
2694
+ }
2695
+ /** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */
2696
+ async function retryDelayMs(retries, attempt, ctx, error) {
2697
+ const base = durationMs(typeof retries.delay === "function" ? await retries.delay({
2698
+ ctx,
2699
+ error
2700
+ }) : retries.delay);
2701
+ switch (retries.backoff) {
2702
+ case "linear": return base * attempt;
2703
+ case "exponential": return base * 2 ** (attempt - 1);
2704
+ default: return base;
2705
+ }
2706
+ }
2707
+ // packages/cloudflare/src/platform.ts
2708
+ function isBindingLike(value) {
2709
+ if (typeof value === "function") return true;
2710
+ if (typeof value !== "object" || value === null) return false;
2711
+ const proto = Object.getPrototypeOf(value);
2712
+ return [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})].some((k) => k !== "constructor" && typeof value[k] === "function");
2713
+ }
2714
+ const assumptions = [
2715
+ "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",
2716
+ "D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
2717
+ "message.timestamp is the virtual clock's time at delivery",
2718
+ "only D1, Durable Object, R2 and Workflow bindings are proxied; touching any other binding makes the run UNSUPPORTED",
2719
+ "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",
2720
+ "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/)",
2721
+ "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)",
2722
+ "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/)",
2723
+ "state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
2724
+ "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",
2725
+ "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/)",
2726
+ "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"
2727
+ ];
2728
+ function createCloudflarePlatform(options) {
2729
+ const env = options.env;
2730
+ const maxRetries = options.maxRetries ?? 3;
2731
+ let hooksRef = null;
2732
+ const ctx = {
2733
+ get hooks() {
2734
+ if (!hooksRef) throw new Error("no run in progress");
2735
+ return hooksRef;
2736
+ },
2737
+ currentInvocation: () => ctx.hooks.running()
2738
+ };
2739
+ const d1Proxies = /* @__PURE__ */ new Map();
2740
+ const doProxies = /* @__PURE__ */ new Map();
2741
+ /** The Durable Object bindings the current scenario's setup resets before each run. */
2742
+ let resetBindings = /* @__PURE__ */ new Set();
2743
+ /** Per binding, what the current run knows about its objects. */
2744
+ const bindingStates = /* @__PURE__ */ new Map();
2745
+ const stateFor = (binding) => {
2746
+ let state = bindingStates.get(binding);
2747
+ if (!state) {
2748
+ state = new BindingState();
2749
+ bindingStates.set(binding, state);
2750
+ }
2751
+ return state;
2752
+ };
2753
+ /** Per binding, alarm firings allowed per object in the current run. */
2754
+ let alarmLimits = /* @__PURE__ */ new Map();
2755
+ /** The Workflow bindings the current scenario sets up, with the class each runs. */
2756
+ let workflowClasses = /* @__PURE__ */ new Map();
2757
+ const registries = /* @__PURE__ */ new Map();
2758
+ const registryFor = (binding) => {
2759
+ let r = registries.get(binding);
2760
+ if (!r) {
2761
+ r = new WorkflowRegistry();
2762
+ registries.set(binding, r);
2763
+ }
2764
+ return r;
2765
+ };
2766
+ const workflowProxies = /* @__PURE__ */ new Map();
2767
+ /** The R2 buckets the current scenario sets up, and their proxies' version stand-ins. */
2768
+ let r2Bindings = /* @__PURE__ */ new Set();
2769
+ const r2Proxies = /* @__PURE__ */ new Map();
2770
+ const versions = new VersionBook();
2771
+ const namespace = (binding) => {
2772
+ const real = env[binding];
2773
+ if (!isDurableObjectNamespace(real)) throw new Error(`env.${binding} is not a Durable Object namespace`);
2774
+ return real;
2775
+ };
2776
+ const helpers = () => {
2777
+ if (!options.durableObjects) throw new Error("Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })");
2778
+ return options.durableObjects;
2779
+ };
2780
+ const proxiedEnv = new Proxy(env, { get(target, prop, receiver) {
2781
+ const value = Reflect.get(target, prop, receiver);
2782
+ if (typeof prop !== "string") return value;
2783
+ if (isD1(value)) {
2784
+ let p = d1Proxies.get(prop);
2785
+ if (!p) {
2786
+ p = proxyD1(value, prop, ctx);
2787
+ d1Proxies.set(prop, p);
2788
+ }
2789
+ return p;
2790
+ }
2791
+ if (isDurableObjectNamespace(value)) {
2792
+ let p = doProxies.get(prop);
2793
+ if (!p) {
2794
+ p = proxyNamespace(value, prop, ctx, stateFor(prop), options.durableObjects, () => resetBindings.has(prop));
2795
+ doProxies.set(prop, p);
2796
+ }
2797
+ return p;
2798
+ }
2799
+ if (isR2(value)) {
2800
+ if (!r2Bindings.has(prop)) ctx.hooks.unsupported(`R2 binding ${prop} needs an r2Bucket() setup step, which empties it before each run`);
2801
+ let p = r2Proxies.get(prop);
2802
+ if (!p) {
2803
+ p = proxyR2(value, prop, ctx, versions);
2804
+ r2Proxies.set(prop, p);
2805
+ }
2806
+ return p;
2807
+ }
2808
+ if (isWorkflowBinding(value)) {
2809
+ if (!workflowClasses.has(prop)) {
2810
+ ctx.hooks.unsupported(`Workflow binding ${prop} needs a workflow() setup step naming its class`);
2811
+ return proxyWorkflow(prop, ctx, new WorkflowRegistry());
2812
+ }
2813
+ let p = workflowProxies.get(prop);
2814
+ if (!p) {
2815
+ p = proxyWorkflow(prop, ctx, registryFor(prop));
2816
+ workflowProxies.set(prop, p);
2817
+ }
2818
+ return p;
2819
+ }
2820
+ if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);
2821
+ return value;
2822
+ } });
2823
+ const worker = {
2824
+ handler: options.handler,
2825
+ env: proxiedEnv
2826
+ };
2827
+ return {
2828
+ name: "cloudflare",
2829
+ assumptions,
2830
+ concurrent: true,
2831
+ async reset(spec) {
2832
+ resetBindings = /* @__PURE__ */ new Set();
2833
+ alarmLimits = /* @__PURE__ */ new Map();
2834
+ workflowClasses = /* @__PURE__ */ new Map();
2835
+ r2Bindings = /* @__PURE__ */ new Set();
2836
+ versions.clear();
2837
+ for (const state of bindingStates.values()) state.clear();
2838
+ for (const registry of registries.values()) registry.clear();
2839
+ for (const step of spec.setup) {
2840
+ if (step.kind === "workflow") {
2841
+ const setup = step;
2842
+ workflowClasses.set(setup.binding, setup);
2843
+ continue;
2844
+ }
2845
+ if (step.kind === "r2") {
2846
+ const setup = step;
2847
+ const real = env[setup.binding];
2848
+ if (!isR2(real)) throw new Error(`env.${setup.binding} is not an R2 bucket`);
2849
+ r2Bindings.add(setup.binding);
2850
+ await resetR2(real, setup.objects);
2851
+ continue;
2852
+ }
2853
+ if (step.kind === "durable_object") {
2854
+ const setup = step;
2855
+ resetBindings.add(setup.binding);
2856
+ alarmLimits.set(setup.binding, setup.alarmsPerObject ?? 3);
2857
+ await resetNamespace(namespace(setup.binding), helpers(), stateFor(setup.binding).names, setup.objects);
2858
+ continue;
2859
+ }
2860
+ if (step.kind !== "d1") continue;
2861
+ const binding = String(step["binding"]);
2862
+ const schema = options.schemas[binding];
2863
+ if (schema === void 0) throw new Error(`no schema provided for D1 binding ${binding}`);
2864
+ const real = env[binding];
2865
+ if (!isD1(real)) throw new Error(`env.${binding} is not a D1 binding`);
2866
+ await resetD1(real, schema);
2867
+ }
2868
+ },
2869
+ restrictEvents(spec, keepIds) {
2870
+ const drive = spec.drive;
2871
+ if (drive.kind === "http") return {
2872
+ ...spec,
2873
+ drive: {
2874
+ ...drive,
2875
+ requests: drive.requests.filter((r) => keepIds.includes(r.id))
2876
+ }
2877
+ };
2878
+ return {
2879
+ ...spec,
2880
+ drive: {
2881
+ ...drive,
2882
+ messages: drive.messages.filter((m) => keepIds.includes(m.id))
2883
+ }
2884
+ };
2885
+ },
2886
+ async finish(spec, hooks) {
2887
+ for (const step of spec.setup) {
2888
+ if (step.kind === "r2") {
2889
+ const binding = step.binding;
2890
+ const real = env[binding];
2891
+ if (isR2(real)) hooks.snapshot(hooks.bookkeeping(), `R2:${binding}`, { tables: { objects: await snapshotR2(real) } });
2892
+ continue;
2893
+ }
2894
+ if (step.kind === "workflow") {
2895
+ const binding = step.binding;
2896
+ hooks.snapshot(hooks.bookkeeping(), `Workflow:${binding}`, { tables: { instances: registryFor(binding).rows() } });
2897
+ continue;
2898
+ }
2899
+ if (step.kind === "durable_object") {
2900
+ const setup = step;
2901
+ const binding = setup.binding;
2902
+ const tables = await snapshotNamespace(namespace(binding), helpers(), stateFor(binding).names, stateFor(binding).touched, setup.objects, (object) => hooks.unsupported(`Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`), (reason) => hooks.unsupported(reason));
2903
+ hooks.snapshot(hooks.bookkeeping(), `DO:${binding}`, { tables });
2904
+ continue;
2905
+ }
2906
+ if (step.kind !== "d1") continue;
2907
+ const binding = String(step["binding"]);
2908
+ const real = env[binding];
2909
+ if (!isD1(real)) continue;
2910
+ const tables = await snapshotD1(real);
2911
+ hooks.snapshot(hooks.bookkeeping(), `D1:${binding}`, { tables });
2912
+ }
2913
+ },
2914
+ initialEvents(spec) {
2915
+ const drive = spec.drive;
2916
+ if (drive.kind === "http") return drive.requests.map((r) => ({
2917
+ id: r.id,
2918
+ attempt: 1,
2919
+ data: r
2920
+ }));
2921
+ return drive.messages.map((m) => ({
2922
+ id: m.id,
2923
+ attempt: 1,
2924
+ data: m.body
2925
+ }));
2926
+ },
2927
+ async deliver(event, hooks, spec) {
2928
+ const drive = spec.drive;
2929
+ const invocation = `${event.id}#${event.attempt}`;
2930
+ hooksRef = hooks;
2931
+ if (event.source === "workflow") {
2932
+ const { binding, id } = event.data;
2933
+ const setup = workflowClasses.get(binding);
2934
+ if (!setup) return {
2935
+ status: "errored",
2936
+ followUps: []
2937
+ };
2938
+ const className = setup.className;
2939
+ const cls = options.exports?.[className];
2940
+ const instance = registryFor(binding).instances.get(id);
2941
+ if (typeof cls !== "function" || !instance) {
2942
+ hooks.unsupported(`Workflow ${binding}: class ${className} is not among the Worker module's exports; pass them as createCloudflarePlatform({ ..., exports })`);
2943
+ return {
2944
+ status: "errored",
2945
+ followUps: []
2946
+ };
2947
+ }
2948
+ return deliverWorkflow(event, hooks, {
2949
+ binding,
2950
+ ...setup.name === void 0 ? {} : { name: setup.name },
2951
+ instance,
2952
+ cls,
2953
+ env: proxiedEnv,
2954
+ maxFaultsPerRun: spec.bounds.maxFaultsPerRun,
2955
+ maxRedeliveries: spec.bounds.maxRedeliveries
2956
+ });
2957
+ }
2958
+ if (event.source === "durable_object_alarm") {
2959
+ const binding = String(event.data.binding ?? "");
2960
+ return deliverAlarm(event, hooks, spec.bounds.maxRedeliveries, {
2961
+ binding,
2962
+ book: stateFor(binding).alarms,
2963
+ limit: alarmLimits.get(binding) ?? 3,
2964
+ runAlarm: alarmRunner(namespace(binding), binding, ctx, options.durableObjects, stateFor(binding)),
2965
+ abort: (id) => stateFor(binding).abort(id),
2966
+ mayPark: (id) => stateFor(binding).mayPark(id),
2967
+ evict: (id) => evictObject(namespace(binding), options.durableObjects, id),
2968
+ bookkeep: (op, args) => hooks.effectSync({
2969
+ invocation: hooks.bookkeeping(),
2970
+ target: `DO:${binding}`,
2971
+ op,
2972
+ args,
2973
+ allowed: []
2974
+ }, () => null, () => null)
2975
+ });
2976
+ }
2977
+ return drive.kind === "http" ? await deliverRequest(event, hooks, spec, drive, invocation, worker) : await deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries);
2978
+ }
2979
+ };
2980
+ }
2981
+ // packages/cloudflare/src/differential.ts
2982
+ /**
2983
+ * Differential check: the same fault-free scenario run once through Eutaxy's
2984
+ * proxies and once against the raw bindings, with the queue model (or the
2985
+ * HTTP caller's retry policy) applied by hand on the raw side. Any difference in the per-attempt decisions or in
2986
+ * the final D1 and R2 state is a bug in the proxies or the platform model, not in
2987
+ * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue
2988
+ * semantics; what it does not share is any proxy code.
2989
+ */
2990
+ /**
2991
+ * The raw side's only wrapper: counts D1 calls in flight (so the settle loop
2992
+ * knows real I/O is pending) and advances the clock as the proxies do. It
2993
+ * records nothing and injects nothing.
2994
+ */
2995
+ function countingD1(real, io, clock) {
2996
+ const realOf = /* @__PURE__ */ new WeakMap();
2997
+ const track = async (p) => {
2998
+ io.n++;
2999
+ try {
3000
+ return await p;
3001
+ } finally {
3002
+ io.n--;
3003
+ clock.advance(1);
3004
+ }
3005
+ };
3006
+ const wrapStatement = (s) => {
3007
+ const proxy = new Proxy(s, { get(t, prop, r) {
3008
+ const v = Reflect.get(t, prop, r);
3009
+ if (prop === "bind") return (...a) => wrapStatement(t.bind(...a));
3010
+ if (prop === "run" || prop === "all" || prop === "first" || prop === "raw") return (...a) => track(v.apply(t, a));
3011
+ return typeof v === "function" ? v.bind(t) : v;
3012
+ } });
3013
+ realOf.set(proxy, s);
3014
+ return proxy;
3015
+ };
3016
+ return new Proxy(real, { get(t, prop, r) {
3017
+ const v = Reflect.get(t, prop, r);
3018
+ if (prop === "prepare") return (sql) => wrapStatement(t.prepare(sql));
3019
+ if (prop === "batch") return (stmts) => track(t.batch(stmts.map((s) => realOf.get(s) ?? s)));
3020
+ if (prop === "exec") return (sql) => track(t.exec(sql));
3021
+ return typeof v === "function" ? v.bind(t) : v;
3022
+ } });
3023
+ }
3024
+ /**
3025
+ * The same for an R2 bucket: each call advances the clock as its proxied
3026
+ * effect does, and reading a body it gave counts as I/O in flight but does
3027
+ * not advance the clock (the proxy reads it inside the get). Reads through
3028
+ * the body's own stream are not counted: wrapping it would lose the known
3029
+ * length a copy's put needs, and Miniflare answers them within the settle
3030
+ * loop's real tick (checked with an 8 MB body).
3031
+ */
3032
+ function countingR2(real, io, clock) {
3033
+ const track = async (p, advance) => {
3034
+ io.n++;
3035
+ try {
3036
+ return await p;
3037
+ } finally {
3038
+ io.n--;
3039
+ if (advance) clock.advance(1);
3040
+ }
3041
+ };
3042
+ const reads = [
3043
+ "arrayBuffer",
3044
+ "bytes",
3045
+ "text",
3046
+ "json",
3047
+ "blob"
3048
+ ];
3049
+ const counted = (o) => {
3050
+ if (o === null || typeof o !== "object" || !("body" in o)) return o;
3051
+ return new Proxy(o, { get(t, prop) {
3052
+ const v = Reflect.get(t, prop);
3053
+ if (typeof prop === "string" && reads.includes(prop) && typeof v === "function") return (...a) => track(v.apply(t, a), false);
3054
+ return typeof v === "function" ? v.bind(t) : v;
3055
+ } });
3056
+ };
3057
+ return new Proxy(real, { get(t, prop, r) {
3058
+ const v = Reflect.get(t, prop, r);
3059
+ if (prop === "put" || prop === "delete" || prop === "get" || prop === "head" || prop === "list") return async (...a) => counted(await track(v.apply(t, a), true));
3060
+ return typeof v === "function" ? v.bind(t) : v;
3061
+ } });
3062
+ }
3063
+ async function snapshotAll(spec, options) {
3064
+ const env = options.env;
3065
+ const out = {};
3066
+ for (const step of spec.setup) {
3067
+ if (step.kind === "r2") {
3068
+ const binding = step.binding;
3069
+ const real = env[binding];
3070
+ if (isR2(real)) out[binding] = { objects: await snapshotR2(real) };
3071
+ continue;
3072
+ }
3073
+ if (step.kind !== "d1") continue;
3074
+ const binding = String(step["binding"]);
3075
+ const real = env[binding];
3076
+ if (isD1(real)) out[binding] = await snapshotD1(real);
3077
+ }
3078
+ return out;
3079
+ }
3080
+ /** The Eutaxy side, keeping each delivery's status and the decision it made. */
3081
+ async function eutaxySide(spec, options) {
3082
+ const { attempts, unsupported } = await proxiedSide(spec, createCloudflarePlatform(options), (event, result, entries) => {
3083
+ const invocation = `${event.id}#${event.attempt}`;
3084
+ const mine = entries.filter((e) => e.invocation === invocation);
3085
+ const decision = mine.find((e) => e.kind === "result" && (e.op === "ack" || e.op === "retry") && getPath(e.payload, "result.effective") === true)?.op;
3086
+ const response = mine.find((e) => e.kind === "result" && e.op === "response");
3087
+ return {
3088
+ event: event.id,
3089
+ attempt: event.attempt,
3090
+ status: result.status === "completed" ? "completed" : "errored",
3091
+ decision: decision ?? null,
3092
+ ...response ? { response: getPath(response.payload, "result.status") } : {}
3093
+ };
3094
+ });
3095
+ return {
3096
+ attempts,
3097
+ state: await snapshotAll(spec, options),
3098
+ unsupported
3099
+ };
3100
+ }
3101
+ /** Each binding's tables under `<binding>.<table>`, as the comparison names them. */
3102
+ function flatten(state) {
3103
+ const out = {};
3104
+ for (const [binding, tables] of Object.entries(state)) for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;
3105
+ return out;
3106
+ }
3107
+ /** The raw side: the handler called directly with the real bindings and plain message or Request objects. */
3108
+ async function rawSide(spec, options) {
3109
+ const env = options.env;
3110
+ const drive = spec.drive;
3111
+ const maxRetries = options.maxRetries ?? 3;
3112
+ for (const step of spec.setup) {
3113
+ if (step.kind === "r2") {
3114
+ const setup = step;
3115
+ const real = env[setup.binding];
3116
+ if (isR2(real)) await resetR2(real, setup.objects);
3117
+ continue;
3118
+ }
3119
+ if (step.kind !== "d1") continue;
3120
+ const binding = String(step["binding"]);
3121
+ const schema = options.schemas[binding];
3122
+ const real = env[binding];
3123
+ if (schema !== void 0 && isD1(real)) await resetD1(real, schema);
3124
+ }
3125
+ const attempts = [];
3126
+ const pending = drive.kind === "http" ? drive.requests.map((r) => ({
3127
+ id: r.id,
3128
+ attempt: 1,
3129
+ data: r
3130
+ })) : drive.messages.map((m) => ({
3131
+ id: m.id,
3132
+ attempt: 1,
3133
+ data: m.body
3134
+ }));
3135
+ const patched = patchGlobals(0);
3136
+ const unsupported = [];
3137
+ const restoreFetch = installScriptedFetch(spec.externals, null, (r) => unsupported.push(r), () => patched.clock.advance(1));
3138
+ const io = { n: 0 };
3139
+ const counting = /* @__PURE__ */ new Map();
3140
+ const countedEnv = new Proxy(env, { get(target, prop, receiver) {
3141
+ const value = Reflect.get(target, prop, receiver);
3142
+ if (typeof prop !== "string" || !(isD1(value) || isR2(value))) return value;
3143
+ let c = counting.get(prop);
3144
+ if (!c) {
3145
+ c = isD1(value) ? countingD1(value, io, patched.clock) : countingR2(value, io, patched.clock);
3146
+ counting.set(prop, c);
3147
+ }
3148
+ return c;
3149
+ } });
3150
+ const settle = (p) => settleOn(p, {
3151
+ clock: patched.clock,
3152
+ inFlight: () => io.n,
3153
+ crashed: () => false,
3154
+ stuck: () => {
3155
+ throw new DifferentialStuck();
3156
+ }
3157
+ });
3158
+ try {
3159
+ if (drive.kind === "http") {
3160
+ const handler = options.handler.fetch;
3161
+ if (!handler) throw new Error("the Worker has no fetch() handler");
3162
+ while (pending.length > 0) {
3163
+ const event = pending.shift();
3164
+ const req = event.data;
3165
+ const background = [];
3166
+ let status;
3167
+ let response = 500;
3168
+ try {
3169
+ const r = await settle(Promise.resolve().then(() => handler.call(options.handler, requestFor(req), countedEnv, executionContext(background))));
3170
+ await settle(r.clone().text());
3171
+ response = r.status;
3172
+ status = "completed";
3173
+ } catch (err) {
3174
+ if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
3175
+ status = "errored";
3176
+ }
3177
+ await settle(Promise.all(background));
3178
+ attempts.push({
3179
+ event: event.id,
3180
+ attempt: event.attempt,
3181
+ status,
3182
+ decision: null,
3183
+ response
3184
+ });
3185
+ if (!(drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300) && event.attempt - 1 < drive.retries && event.attempt - 1 < spec.bounds.maxRedeliveries) pending.push({
3186
+ ...event,
3187
+ attempt: event.attempt + 1
3188
+ });
3189
+ }
3190
+ } else {
3191
+ const handler = options.handler.queue;
3192
+ if (!handler) throw new Error("the Worker has no queue() handler");
3193
+ while (pending.length > 0) {
3194
+ const event = pending.shift();
3195
+ let decision = null;
3196
+ const background = [];
3197
+ const message = {
3198
+ id: event.id,
3199
+ timestamp: /* @__PURE__ */ new Date(),
3200
+ body: JSON.parse(JSON.stringify(event.data)),
3201
+ attempts: event.attempt,
3202
+ ack: () => {
3203
+ decision ??= "ack";
3204
+ },
3205
+ retry: () => {
3206
+ decision ??= "retry";
3207
+ }
3208
+ };
3209
+ const batch = {
3210
+ queue: drive.queue,
3211
+ messages: [message],
3212
+ metadata: { metrics: {
3213
+ backlogCount: 0,
3214
+ backlogBytes: 0
3215
+ } },
3216
+ ackAll: () => message.ack(),
3217
+ retryAll: () => message.retry()
3218
+ };
3219
+ const ctx = executionContext(background);
3220
+ let status;
3221
+ try {
3222
+ await settle(Promise.resolve().then(() => handler.call(options.handler, batch, countedEnv, ctx)));
3223
+ status = "completed";
3224
+ } catch (err) {
3225
+ if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
3226
+ status = "errored";
3227
+ }
3228
+ if (status === "completed") decision ??= "ack";
3229
+ await settle(Promise.all(background));
3230
+ attempts.push({
3231
+ event: event.id,
3232
+ attempt: event.attempt,
3233
+ status,
3234
+ decision
3235
+ });
3236
+ if (decision !== "ack" && event.attempt <= maxRetries && event.attempt - 1 < spec.bounds.maxRedeliveries) pending.push({
3237
+ ...event,
3238
+ attempt: event.attempt + 1
3239
+ });
3240
+ }
3241
+ }
3242
+ } finally {
3243
+ restoreFetch();
3244
+ patched.restore();
3245
+ }
3246
+ if (unsupported.length > 0) throw new DifferentialStuck(`raw side: ${unsupported.join("; ")}`);
3247
+ return {
3248
+ attempts,
3249
+ state: await snapshotAll(spec, options)
3250
+ };
3251
+ }
3252
+ /** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
3253
+ async function runDifferential(spec, options) {
3254
+ if (spec.drive.kind === "http" && ("delaysMs" in spec.drive || "deadlineMs" in spec.drive)) throw new Error("runDifferential does not model the caller's delaysMs or deadlineMs yet");
3255
+ const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
3256
+ const raw = await rawSide(spec, options);
3257
+ const differences = compareSides({
3258
+ attempts: eutaxy.attempts,
3259
+ state: flatten(eutaxy.state)
3260
+ }, {
3261
+ attempts: raw.attempts,
3262
+ state: flatten(raw.state)
3263
+ }, unsupported);
3264
+ return {
3265
+ equal: differences.length === 0,
3266
+ eutaxy,
3267
+ raw,
3268
+ differences,
3269
+ unsupported
3270
+ };
3271
+ }
3272
+ // packages/cli/src/workerd.ts
3273
+ /**
3274
+ * The half of `eutaxy check` that runs inside workerd: the generated test
3275
+ * passes its module globs here and stores what this returns in its task
3276
+ * meta, which the CLI reads back. It imports nothing that needs Node, so
3277
+ * the Cloudflare Vitest plugin can load it.
3278
+ */
3279
+ /** Each D1 binding's schema, read from the `.sql` files next to the scenario. */
3280
+ function schemasFor(scenario, sqlFiles) {
3281
+ const schemas = {};
3282
+ for (const step of scenario.setup) {
3283
+ if (step.kind !== "d1") continue;
3284
+ const file = String(step["schemaFile"]);
3285
+ const sql = sqlFiles[globKey(file)];
3286
+ if (sql === void 0) throw new Error(`schema file ${file} not found next to the scenario`);
3287
+ schemas[String(step["binding"])] = sql;
3288
+ }
3289
+ return schemas;
3290
+ }
3291
+ /**
3292
+ * The modules the scenario's `specs` name, loaded with their specs, and
3293
+ * every reason the check cannot go ahead: a module that is not there, an
3294
+ * annotation that does not parse, a function name observed in two modules
3295
+ * (decisions are logged by name, so it would be ambiguous).
3296
+ */
3297
+ async function selectSpecModules(scenario, modules, specLoaders) {
3298
+ const decisions = scenario.invariants.flatMap((i) => i.kind === "refines" ? [i.decision] : []);
3299
+ const specErrors = [];
3300
+ const selected = [];
3301
+ for (const path of scenario.specs ?? []) {
3302
+ const load = modules[globKey(path)];
3303
+ if (!load) {
3304
+ specErrors.push({
3305
+ module: path,
3306
+ line: 0,
3307
+ message: "no such module next to the scenario"
3308
+ });
3309
+ continue;
3310
+ }
3311
+ const namespace = await load();
3312
+ const key = specKey(path);
3313
+ const loadSpec = Object.hasOwn(specLoaders, key) ? specLoaders[key] : void 0;
3314
+ const entry = loadSpec ? await loadSpec() : void 0;
3315
+ const specs = entry?.specs ?? {
3316
+ functions: [],
3317
+ exports: [],
3318
+ errors: []
3319
+ };
3320
+ for (const e of specs.errors) specErrors.push({
3321
+ module: path,
3322
+ ...e
3323
+ });
3324
+ const exported = decisions.filter((d) => typeof namespace[d] === "function");
3325
+ const names = [.../* @__PURE__ */ new Set([...specs.functions.map((f) => f.name), ...exported])];
3326
+ const predicates = entry ? entry.predicates(namespace, lemmaBool, lemmaUnresolved) : {};
3327
+ selected.push({
3328
+ path,
3329
+ key,
3330
+ namespace,
3331
+ specs,
3332
+ predicates,
3333
+ names
3334
+ });
3335
+ }
3336
+ const observedIn = /* @__PURE__ */ new Map();
3337
+ for (const m of selected) for (const n of m.names) {
3338
+ const other = observedIn.get(n);
3339
+ if (other === void 0) observedIn.set(n, m.path);
3340
+ else specErrors.push({
3341
+ module: m.path,
3342
+ line: 0,
3343
+ message: `${n} is observed in both ${other} and ${m.path}; decisions of one name must come from one module`
3344
+ });
3345
+ }
3346
+ return {
3347
+ selected,
3348
+ specErrors
3349
+ };
3350
+ }
3351
+ /** Run the scenario's check, with its specs observed, and return what the CLI reads back. */
3352
+ async function checkInWorkerd(input) {
3353
+ const { scenario } = input;
3354
+ const schemas = schemasFor(scenario, input.sqlFiles);
3355
+ const load = input.modules[globKey(scenario.worker.entry)];
3356
+ if (!load) throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);
3357
+ const worker = await load();
3358
+ const platform = createCloudflarePlatform({
3359
+ env: input.env,
3360
+ handler: worker.default,
3361
+ schemas,
3362
+ durableObjects: input.durableObjects,
3363
+ exports: worker
3364
+ });
3365
+ const { selected, specErrors } = await selectSpecModules(scenario, input.modules, input.specLoaders);
3366
+ const transportBase = {
3367
+ worker: scenario.worker,
3368
+ setup: scenario.setup
3369
+ };
3370
+ if (specErrors.length > 0) return {
3371
+ report: null,
3372
+ specErrors,
3373
+ ...transportBase
3374
+ };
3375
+ const observers = selected.map((m) => observeCore(m.namespace, m.names));
3376
+ let verdict;
3377
+ try {
3378
+ verdict = await check(scenario, platform, {
3379
+ seed: input.seed,
3380
+ ...input.maxRuns === void 0 ? {} : { maxRuns: input.maxRuns },
3381
+ ...input.budgetMs === void 0 ? {} : { budgetMs: input.budgetMs },
3382
+ ...input.exhaustive ? { exhaustive: true } : {}
3383
+ });
3384
+ } finally {
3385
+ for (const o of observers) o.restore();
3386
+ }
3387
+ const specs = selected.flatMap((m, i) => checkSpecModule(m.key, m.specs, m.predicates, observers[i]));
3388
+ return {
3389
+ report: JSON.parse(renderJson(verdict, specs)),
3390
+ ...transportBase,
3391
+ observed: selected.map((m) => ({
3392
+ module: m.path,
3393
+ functions: m.names
3394
+ }))
3395
+ };
3396
+ }
3397
+ export { snapshotD1 as A, r2Rows as C, workflow as D, unique as E, expectHolds as M, main as N, workflowRows as O, cloudflareRegressionTest as P, r2Op as S, refines as T, httpResponse as _, d1Param as a, queueAck as b, d1Schema as c, durableObject as d, durableObjectRows as f, http as g, fetchCall as h, atLeastOncePerMessage as i, check as j, workflowStep as k, d1Write as l, external as m, runDifferential as n, d1Read as o, everyRow as p, createCloudflarePlatform as r, d1Rows as s, checkInWorkerd as t, defineScenario as u, implies as v, references as w, r2Bucket as x, queue as y };
3398
+
3399
+ //# sourceMappingURL=src-DKb-fkdb.mjs.map