eutaxy 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -8
- package/dist/aws.mjs +5 -5
- package/dist/bin.mjs +1 -2
- package/dist/bin.mjs.map +1 -1
- package/dist/{checksum-DJbbDJA0.mjs → checksum-75EliDEr.mjs} +5 -5
- package/dist/{checksum-DJbbDJA0.mjs.map → checksum-75EliDEr.mjs.map} +1 -1
- package/dist/{src-DIG0_CjU.mjs → cli-BppjMaqL.mjs} +690 -4113
- package/dist/cli-BppjMaqL.mjs.map +1 -0
- package/dist/cli.mjs +1 -2
- package/dist/cloudflare.d.mts +245 -84
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +3 -3
- package/dist/{delivery-invariants-Br29H7Rg.mjs → delivery-invariants-_T9ZMwOJ.mjs} +2 -2
- package/dist/{delivery-invariants-Br29H7Rg.mjs.map → delivery-invariants-_T9ZMwOJ.mjs.map} +1 -1
- package/dist/{event-streams-eH6Jim9p.mjs → event-streams-lXGVdHFn.mjs} +2 -2
- package/dist/{event-streams-eH6Jim9p.mjs.map → event-streams-lXGVdHFn.mjs.map} +1 -1
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -1
- package/dist/provers-DS44OeEm.mjs +83 -0
- package/dist/provers-DS44OeEm.mjs.map +1 -0
- package/dist/{src-CWVQEhTr.mjs → src-ClXnIi6O.mjs} +3 -83
- package/dist/src-ClXnIi6O.mjs.map +1 -0
- package/dist/{src-DGh7w877.mjs → src-DPCF2XGv.mjs} +103 -16
- package/dist/src-DPCF2XGv.mjs.map +1 -0
- package/dist/workerd-DVJ8eCLI.mjs +5200 -0
- package/dist/workerd-DVJ8eCLI.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/cli-BFTyLLRF.mjs +0 -2
- package/dist/src-CWVQEhTr.mjs.map +0 -1
- package/dist/src-DGh7w877.mjs.map +0 -1
- package/dist/src-DIG0_CjU.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-DIG0_CjU.mjs","names":["join","ident","fail","env","term","emitFunction","binderType","arrowTerm","installHint","run","candidates","ident","engineName","engineAssumptions","proven","unknown","prepare","proveModule","coreAtLeastOncePerMessage","retryDelayMs"],"sources":["../../cli/src/args.ts","../../prover/src/reader/compiler.ts","../../prover/src/reader/expressions.ts","../../prover/src/reader/types.ts","../../prover/src/reader/subset.ts","../../prover/src/reader/specs.ts","../../prover-lean/src/emit.ts","../../prover/src/toolchain.ts","../../prover-lean/src/lean.ts","../../prover-lean/src/supplied.ts","../../prover-lean/src/goals.ts","../../prover-lean/src/prove.ts","../../prover-smt/src/emit.ts","../../prover-smt/src/z3.ts","../../prover-smt/src/prove.ts","../../cli/src/generate.ts","../../cli/src/regression.ts","../../cli/src/keys.ts","../../cli/src/specs.ts","../../cli/src/check.ts","../../cli/src/archive.ts","../../cli/src/install.ts","../../cli/src/report.ts","../../cli/src/version.ts","../../cli/src/mcp.ts","../../cli/src/main.ts","../../cloudflare/src/check.ts","../../cloudflare/src/d1.ts","../../cloudflare/src/background.ts","../../cloudflare/src/alarms.ts","../../cloudflare/src/durable-objects.ts","../../cloudflare/src/r2.ts","../../cloudflare/src/cron.ts","../../cloudflare/src/scenario.ts","../../cloudflare/src/services.ts","../../cloudflare/src/entrypoint.ts","../../cloudflare/src/workflows.ts","../../cloudflare/src/bindings.ts","../../cloudflare/src/caller.ts","../../cloudflare/src/http.ts","../../cloudflare/src/queues.ts","../../cloudflare/src/rpc.ts","../../cloudflare/src/scheduled.ts","../../cloudflare/src/platform.ts","../../cloudflare/src/differential.ts","../../cli/src/workerd.ts"],"sourcesContent":["/** A small argument parser: positionals, `--flag value`, `--flag=value` and boolean `--flag`. */\n\nexport interface ParsedArgs {\n readonly positionals: readonly string[];\n readonly flags: Readonly<Record<string, string | true>>;\n}\n\nexport function parseArgs(argv: readonly string[], booleans: readonly string[] = []): ParsedArgs {\n const positionals: string[] = [];\n const flags: Record<string, string | true> = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i] as string;\n if (!a.startsWith(\"--\")) {\n positionals.push(a);\n continue;\n }\n const eq = a.indexOf(\"=\");\n if (eq !== -1) {\n flags[a.slice(2, eq)] = a.slice(eq + 1);\n continue;\n }\n const name = a.slice(2);\n const next = argv[i + 1];\n if (booleans.includes(name) || next === undefined || next.startsWith(\"--\")) {\n flags[name] = true;\n } else {\n flags[name] = next;\n i++;\n }\n }\n return { positionals, flags };\n}\n","/**\n * The TypeScript compiler, through its API (7.1): one compiler process per\n * Node process, started on first use; a program per read, over an\n * in-memory layer holding the files being read on top of the host's own\n * files, so imports resolve as the user's compiler resolves them; a\n * standalone source file for text that is not a module (a spec file's\n * arrow, read back from its text). Every handle the compiler process\n * holds for a read is released when the read ends. Nothing else in Eutaxy\n * imports the compiler API: a change to it lands here.\n */\n\nimport {\n type FunctionLikeBase,\n type Identifier,\n ModifierFlags,\n type ModifiersBase,\n type Node,\n NodeFlags,\n type SourceFile,\n SyntaxKind,\n type VariableDeclarationList,\n} from \"typescript/ast\";\nimport { createFileSystemLayer } from \"typescript/fs\";\nimport { API, type Checker, DiagnosticCategory, type Program } from \"typescript/sync\";\n\nlet api: API | undefined;\n\nfunction compiler(): API {\n api ??= new API({});\n return api;\n}\n\n/** Stop the compiler process; the next read starts another. */\nexport function closeCompiler(): void {\n api?.close();\n api = undefined;\n}\n\n/**\n * The options every read compiles under: strict, the latest language\n * level, bundler-style resolution with `.ts` imports allowed, and the\n * standard library alone (`types: []`), so a module's own types resolve\n * and nothing is emitted. The user's configuration is not read: a type\n * Eutaxy cannot resolve under these options is reported unknown, never\n * guessed.\n */\nconst options = {\n strict: true,\n target: 99, // ScriptTarget.ESNext\n module: 99, // ModuleKind.ESNext\n moduleResolution: 100, // ModuleResolutionKind.Bundler\n allowImportingTsExtensions: true,\n noEmit: true,\n skipLibCheck: true,\n types: [] as string[],\n lib: [\"es2023\"],\n};\n\n/** A file given to a read: its path, under which imports resolve, and its text, which stands in for the file on disk. */\nexport interface InputFile {\n readonly path: string;\n readonly text: string;\n}\n\n/** A program over the input files, with its checker. */\nexport interface Opened {\n readonly program: Program;\n readonly checker: Checker;\n /** The source file of an input path. */\n readonly file: (path: string) => SourceFile;\n /** The first parse error of an input file, if any. */\n readonly parseError: (path: string) => { line: number; message: string } | undefined;\n /** The compiler's errors in a file of the program: text ranges (offsets into the file), with the message and its line. */\n readonly typeErrors: (path: string) => readonly CompilerError[];\n /**\n * Whether an identifier names the global of its name: the compiler\n * resolves it to a symbol declared in its default library alone\n * (`lib.*.d.ts`). A declaration, import or block-scoped shadow of the\n * name in scope, a global declared by the project's own declaration\n * files, or a name the compiler cannot resolve is not; a type-only\n * import of the name is, since the compiler resolves a value past it,\n * and so is an interface augmentation of its type (`declare global {\n * interface Number { … } }`), which changes no value.\n */\n readonly standardGlobal: (id: Identifier) => boolean;\n}\n\n/** One compiler error in a file: its text range, message and 1-based line. */\nexport interface CompilerError {\n readonly pos: number;\n readonly end: number;\n readonly message: string;\n readonly line: number;\n}\n\n/** Run `fn` over a program whose root files are the inputs, released afterwards. */\nexport function withProgram<T>(files: readonly InputFile[], fn: (opened: Opened) => T): T {\n const snapshot = compiler().createSnapshot({\n fileSystem: createFileSystemLayer(files.map((f) => [f.path, f.text] as const)),\n createPrograms: [{ rootFiles: files.map((f) => f.path), compilerOptions: options }],\n });\n try {\n const program = snapshot.operation.createdPrograms[0];\n const checker = program.getProject().checker;\n const file = (path: string): SourceFile => {\n const sf = program.getSourceFile(path);\n if (!sf) throw new Error(`the compiler holds no source file for ${path}`);\n return sf;\n };\n const parseError = (path: string) => {\n const first = program.getSyntacticDiagnostics(path)[0];\n return first\n ? { line: (first.startPosition?.line ?? 0) + 1, message: first.text }\n : undefined;\n };\n const errors = new Map<string, readonly CompilerError[]>();\n const typeErrors = (path: string) => {\n let found = errors.get(path);\n if (!found) {\n found = program\n .getSemanticDiagnostics(path)\n .filter((d) => d.category === DiagnosticCategory.Error)\n .map((d) => ({\n pos: d.pos,\n end: d.end,\n message: d.text,\n line: (d.startPosition?.line ?? 0) + 1,\n }));\n errors.set(path, found);\n }\n return found;\n };\n // Answers by symbol: the global `Math` is one symbol however often it is named. Interface and\n // type alias declarations merge into a symbol without touching its value, so only the others decide.\n const standard = new Map<number, boolean>();\n const typeOnly = new Set([SyntaxKind.InterfaceDeclaration, SyntaxKind.TypeAliasDeclaration]);\n const standardGlobal = (id: Identifier): boolean => {\n const symbol = checker.getSymbolAtLocation(id);\n if (!symbol) return false;\n let known = standard.get(symbol.id);\n if (known === undefined) {\n const values = symbol.declarations.filter((d) => !typeOnly.has(d.kind));\n known =\n values.length > 0 &&\n values.every((d) => {\n const sf = d.resolve()?.getSourceFile();\n return sf !== undefined && program.isSourceFileDefaultLibrary(sf);\n });\n standard.set(symbol.id, known);\n }\n return known;\n };\n return fn({ program, checker, file, parseError, typeErrors, standardGlobal });\n } finally {\n snapshot.dispose();\n }\n}\n\n/** Run `fn` over a source file parsed from `text` alone (no program, no checker), released afterwards. */\nexport function withSourceFile<T>(text: string, fn: (sf: SourceFile) => T): T {\n const lease = compiler().createSourceFile(\"/eutaxy/reader/fragment.ts\", text);\n try {\n return fn(lease.sourceFile);\n } finally {\n lease.dispose();\n }\n}\n\n/** 1-based line of a node's first token. */\nexport function lineAt(sf: SourceFile, node: Node): number {\n return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n}\n\n/** A node's text, leading trivia excluded. */\nexport function textOf(sf: SourceFile, node: Node): string {\n return sf.text.slice(node.getStart(sf), node.end);\n}\n\nexport function isExported(node: ModifiersBase): boolean {\n return (node.modifierFlags & ModifierFlags.Export) !== 0;\n}\n\nexport function isAsync(node: ModifiersBase): boolean {\n return (node.modifierFlags & ModifierFlags.Async) !== 0;\n}\n\nexport function isConst(list: VariableDeclarationList): boolean {\n return (list.flags & NodeFlags.Const) !== 0;\n}\n\n/**\n * The offset of the `(` opening a function's parameter list: the\n * declaration's identity, as the spec reader and the subset reader both\n * record it. Undefined for an arrow written without parentheses.\n */\nexport function openParen(sf: SourceFile, fn: FunctionLikeBase): number | undefined {\n const at = fn.parameters.pos - 1;\n return sf.text[at] === \"(\" ? at : undefined;\n}\n\n/** The name of a syntax kind, for messages. */\nexport function kindName(kind: SyntaxKind): string {\n return SyntaxKind[kind] ?? String(kind);\n}\n","/**\n * Function bodies and spec arrows read from the compiler's syntax tree\n * into the subset's `Expr`: `const` bindings, `if` with early returns,\n * `return`, and expressions from arithmetic, comparisons, `&& || !`, the\n * conditional operator, record and array literals, field reads, list\n * methods and calls to the module's own functions. What a name stands\n * for comes from the scope (parameters and consts) and from `Names`: the\n * module's own functions when the text is the module, the spec file's\n * imports when it is an arrow. Anything else is `OutsideSubset` with the\n * construct named and its line.\n */\n\nimport {\n type ArrowFunction,\n type BinaryExpression,\n type Block,\n type CallExpression,\n type Expression,\n type Identifier,\n type Node,\n type ObjectLiteralExpression,\n type ReturnStatement,\n type SourceFile,\n type Statement,\n SyntaxKind,\n type TypeNode,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport { isAsync, isConst, kindName, lineAt, textOf } from \"./compiler.ts\";\nimport {\n type BinaryOp,\n type Expr,\n hasLoneSurrogate,\n insertNarrows,\n OutsideSubset,\n type SubsetType,\n type TypeContext,\n tagOf,\n typeOf,\n} from \"./subset.ts\";\nimport type { Refuse } from \"./types.ts\";\n\n/**\n * A call to a function the text cannot call by name (a generic one, or one\n * imported from another file) read as that function's body, bound to the\n * arguments: undefined when the callee is no such function, so the call is\n * refused as before. `readArgs` reads the arguments in the caller's scope,\n * a record literal argument typed as the parameter it is passed for when\n * that type is given; `fail` refuses at the call.\n */\nexport type Inline = (\n call: CallExpression,\n callee: Identifier,\n scope: Scope,\n readArgs: (types: readonly (SubsetType | undefined)[]) => Expr[],\n fail: (what: string) => never,\n) => Expr | undefined;\n\n/**\n * A name the text reads that is neither in scope nor a function: a\n * module-level `const` of the text's file or one it imports, read as its\n * initializer (a `const` holding a pure value is that value wherever it is\n * read). Undefined when the name is no such constant, so it is refused as\n * before; `fail` refuses at the name.\n */\nexport type Constant = (name: Identifier, fail: (what: string) => never) => Expr | undefined;\n\n/** What the bare names of the text being read stand for, outside any local scope. */\nexport interface Names {\n /** A function the subset may call under this name. */\n readonly callable: (name: string) => boolean;\n /** The module function a callable name stands for (a spec file's local name resolves to the module's). */\n readonly target: (name: string) => string;\n /** A function the text may name at all, in the subset or not: for messages. */\n readonly declared: (name: string) => boolean;\n /** Whether the text is a spec file's, whose names are its imports, never the module's. */\n readonly spec: boolean;\n /**\n * Whether an identifier is the global of its name (`Math`, `Number`):\n * for a module, the compiler resolves it to its standard library; for a\n * spec file's arrow, read from its text alone, every built-in it names\n * has been checked so by the spec reader, so any is.\n */\n readonly global: (id: Identifier) => boolean;\n}\n\n/** Where the types a body mentions come from: the compiler for the module, the module's own declared types for an arrow. */\nexport interface TypeSource {\n /** The subset type a `const` annotation names. */\n readonly annotation: (node: TypeNode, refuse: Refuse) => SubsetType;\n /** The type the context gives a record literal, when the compiler knows one the subset takes. */\n readonly contextual: (node: ObjectLiteralExpression) => SubsetType | undefined;\n}\n\nexport type Scope = ReadonlyMap<string, SubsetType>;\n\nconst binaryOps: Partial<Record<SyntaxKind, BinaryOp>> = {\n [SyntaxKind.PlusToken]: \"+\",\n [SyntaxKind.MinusToken]: \"-\",\n [SyntaxKind.AsteriskToken]: \"*\",\n [SyntaxKind.SlashToken]: \"/\",\n [SyntaxKind.LessThanToken]: \"<\",\n [SyntaxKind.LessThanEqualsToken]: \"<=\",\n [SyntaxKind.GreaterThanToken]: \">\",\n [SyntaxKind.GreaterThanEqualsToken]: \">=\",\n [SyntaxKind.EqualsEqualsEqualsToken]: \"===\",\n [SyntaxKind.ExclamationEqualsEqualsToken]: \"!==\",\n [SyntaxKind.AmpersandAmpersandToken]: \"&&\",\n [SyntaxKind.BarBarToken]: \"||\",\n};\n\nconst methods = new Set([\"slice\", \"map\", \"flatMap\", \"every\", \"some\", \"reduce\"]);\n\n/** The reader of one text: a function body, or an arrow of the spec file. */\nexport class ExprReader {\n readonly sf: SourceFile;\n readonly names: Names;\n readonly types: TypeSource;\n readonly ctx: TypeContext;\n /** The line a refusal reports for a node: the file's, or none for text whose position the caller knows. */\n private readonly lineOf: (node: Node) => number;\n private readonly inline: Inline | undefined;\n private readonly constant: Constant | undefined;\n /** Record literals typed by the call they are passed to, in place of the compiler's contextual type. */\n private readonly typedAs = new Map<Node, SubsetType>();\n\n constructor(\n sf: SourceFile,\n names: Names,\n types: TypeSource,\n ctx: TypeContext,\n lineOf: (node: Node) => number = (node) => lineAt(sf, node),\n inline?: Inline,\n constant?: Constant,\n ) {\n this.sf = sf;\n this.names = names;\n this.types = types;\n this.ctx = ctx;\n this.lineOf = lineOf;\n this.inline = inline;\n this.constant = constant;\n }\n\n /** Whether an identifier is the global of its name here: no scope or function shadows it, and the names confirm it. */\n private global(id: Identifier, scope: Scope): boolean {\n return !scope.has(id.text) && !this.names.declared(id.text) && this.names.global(id);\n }\n\n fail(what: string, at: Node): never {\n throw new OutsideSubset(what, this.lineOf(at));\n }\n\n /** `OutsideSubset` at a node, for a type read there. */\n refuseAt(at: Node): Refuse {\n return (what) => this.fail(what, at);\n }\n\n text(node: Node): string {\n return textOf(this.sf, node);\n }\n\n /** The expression with `narrow` nodes inserted where a null check guards a nullable name. */\n narrowed(e: Expr, scope: Scope, at: Node): Expr {\n return insertNarrows(e, scope, this.ctx, (m) => this.fail(m, at));\n }\n\n typeOfExpr(e: Expr, scope: Scope, at: Node, expected?: SubsetType): SubsetType {\n return typeOf(e, scope, this.ctx, (m) => this.fail(m, at), expected);\n }\n\n /**\n * A block's statements as one expression: `const` becomes `let`, `if (c)\n * return a; rest` a conditional, and the last statement must return:\n * every path ends in a `return`.\n */\n block(statements: readonly Statement[], scope: Scope, end: Node): Expr {\n return this.statements(statements, 0, scope, end);\n }\n\n private statements(statements: readonly Statement[], i: number, scope: Scope, end: Node): Expr {\n const s = statements[i];\n if (!s) this.fail(\"a path that does not return\", end);\n if (is.isEmptyStatement(s)) return this.statements(statements, i + 1, scope, end);\n if (is.isVariableStatement(s)) {\n const list = s.declarationList;\n if (!isConst(list)) this.fail(\"a mutable binding (use const)\", s);\n const [decl, second] = list.declarations;\n if (!decl || second) this.fail(\"several bindings in one const\", s);\n if (!is.isIdentifier(decl.name)) this.fail(\"a destructured const\", decl.name);\n const name = decl.name.text;\n // A const shadows a module function throughout its block, from before its own line (the temporal\n // dead zone): a call above it would throw where the reader would see the function. Refused outright.\n if (this.names.declared(name))\n this.fail(`const ${name} shadows the module's function ${name} in its block`, decl.name);\n if (scope.has(name))\n this.fail(`const ${name} redeclares a name already bound here`, decl.name);\n const annotated = decl.type\n ? this.types.annotation(decl.type, this.refuseAt(decl.type))\n : undefined;\n if (!decl.initializer) this.fail(`const ${name} without a value`, decl);\n const value = this.expression(decl.initializer, scope);\n // While reading, the scope carries names; types come from `typeOf` once null checks have narrowed\n // the tree, so an initializer under a guard is typed as the guard allows. The annotation is the\n // binding's type (a null initializer is then a nullable, not null); `typeOf` checks it fits.\n const inner = new Map(scope);\n inner.set(name, annotated ?? { kind: \"null\" });\n const body = this.statements(statements, i + 1, inner, end);\n return { kind: \"let\", name, value, body, ...(annotated ? { type: annotated } : {}) };\n }\n if (is.isIfStatement(s)) {\n const test = this.expression(s.expression, scope);\n const then = this.branch(s.thenStatement, scope);\n if (s.elseStatement) {\n const otherwise = this.branch(s.elseStatement, scope);\n const after = statements[i + 1];\n if (after) this.fail(\"statements after an if/else that both return\", after);\n return { kind: \"cond\", test, ifTrue: then, ifFalse: otherwise };\n }\n return {\n kind: \"cond\",\n test,\n ifTrue: then,\n ifFalse: this.statements(statements, i + 1, scope, end),\n };\n }\n if (is.isReturnStatement(s)) {\n const after = statements[i + 1];\n // `return` then a line break: JavaScript inserts a semicolon and returns undefined.\n if (!s.expression && after) {\n const gap = this.sf.text.slice(\n s.getStart(this.sf) + \"return\".length,\n after.getStart(this.sf),\n );\n if (/[\\n\\r\\u2028\\u2029]/.test(gap))\n this.fail(\n \"a line break after return (JavaScript inserts a semicolon and returns undefined)\",\n s,\n );\n }\n const value = this.returned(s, scope);\n if (after) this.fail(\"statements after a return\", after);\n return value;\n }\n if (\n is.isForStatement(s) ||\n is.isForOfStatement(s) ||\n is.isForInStatement(s) ||\n is.isWhileStatement(s) ||\n is.isDoStatement(s)\n )\n this.fail(\"a loop\", s);\n if (is.isThrowStatement(s)) this.fail(\"throw\", s);\n if (is.isSwitchStatement(s)) this.fail(\"switch\", s);\n if (is.isTryStatement(s)) this.fail(\"try\", s);\n if (is.isFunctionDeclaration(s)) this.fail(\"a nested function\", s);\n this.fail(`statement starting with ${this.text(s).split(/\\s/)[0] ?? kindName(s.kind)}`, s);\n }\n\n /** An `if` branch: `return e;` or `{ ...statements ending in return }`. */\n private branch(s: Statement, scope: Scope): Expr {\n if (is.isBlock(s)) return this.block(s.statements, scope, s);\n if (is.isReturnStatement(s)) return this.returned(s, scope);\n this.fail(\"an if branch that does not return\", s);\n }\n\n /** `return e;`. A line break after `return` makes JavaScript return undefined: no value, refused. */\n private returned(s: ReturnStatement, scope: Scope): Expr {\n if (!s.expression) this.fail(\"a return without a value\", s);\n return this.expression(s.expression, scope);\n }\n\n expression(node: Expression, scope: Scope): Expr {\n if (is.isParenthesizedExpression(node)) return this.expression(node.expression, scope);\n if (is.isIdentifier(node)) return this.identifier(node, scope);\n if (is.isNumericLiteral(node)) {\n const raw = this.text(node);\n if (!/^[0-9](_?[0-9])*$/.test(raw))\n this.fail(`the numeric literal ${raw} (integers in decimal only)`, node);\n return { kind: \"int\", value: raw.replace(/_/g, \"\") };\n }\n if (is.isBigIntLiteral(node)) this.fail(`the bigint literal ${this.text(node)}`, node);\n if (is.isStringLiteral(node)) {\n if (hasLoneSurrogate(node.text))\n this.fail(\"a string literal with a lone surrogate, which Lean's strings cannot hold\", node);\n return { kind: \"string\", value: node.text };\n }\n if (is.isNoSubstitutionTemplateLiteral(node) || is.isTemplateExpression(node))\n this.fail(\"a template literal\", node);\n if (is.isRegularExpressionLiteral(node)) this.fail(\"a regular expression\", node);\n if (node.kind === SyntaxKind.TrueKeyword) return { kind: \"bool\", value: true };\n if (node.kind === SyntaxKind.FalseKeyword) return { kind: \"bool\", value: false };\n if (node.kind === SyntaxKind.NullKeyword) return { kind: \"null\" };\n if (is.isPrefixUnaryExpression(node)) {\n if (node.operator === SyntaxKind.ExclamationToken)\n return { kind: \"not\", operand: this.expression(node.operand, scope) };\n if (node.operator === SyntaxKind.MinusToken) {\n const operand = this.expression(node.operand, scope);\n // A negated literal stays a literal with its sign flipped, so -(-1) is 1, never the text `--1`.\n return operand.kind === \"int\"\n ? {\n kind: \"int\",\n value: operand.value.startsWith(\"-\") ? operand.value.slice(1) : `-${operand.value}`,\n }\n : { kind: \"neg\", operand };\n }\n if (node.operator === SyntaxKind.PlusToken) this.fail(\"unary plus\", node);\n this.fail(`the ${this.text(node).slice(0, 2)} operator`, node);\n }\n if (is.isPostfixUnaryExpression(node))\n this.fail(`the ${this.text(node).slice(-2)} operator`, node);\n if (is.isTypeOfExpression(node)) this.fail(\"the typeof operator\", node);\n if (is.isVoidExpression(node)) this.fail(\"the void operator\", node);\n if (is.isAwaitExpression(node)) this.fail(\"the await operator\", node);\n if (is.isNewExpression(node)) this.fail(\"the new operator\", node);\n if (is.isDeleteExpression(node)) this.fail(\"the delete operator\", node);\n if (is.isBinaryExpression(node)) return this.binary(node, scope);\n if (is.isConditionalExpression(node))\n return {\n kind: \"cond\",\n test: this.expression(node.condition, scope),\n ifTrue: this.expression(node.whenTrue, scope),\n ifFalse: this.expression(node.whenFalse, scope),\n };\n if (is.isCallExpression(node)) return this.call(node, scope);\n if (is.isPropertyAccessExpression(node)) {\n if (node.questionDotToken) this.fail(\"optional chaining\", node);\n if (!is.isIdentifier(node.name)) this.fail(\"a private field\", node.name);\n return {\n kind: \"field\",\n object: this.expression(node.expression, scope),\n field: node.name.text,\n };\n }\n if (is.isElementAccessExpression(node)) {\n if (this.isHead(node))\n this.fail(\"xs[0] without ?? fallback (it is undefined on an empty list)\", node);\n this.fail(\"index access other than xs[0] ?? fallback\", node);\n }\n if (is.isObjectLiteralExpression(node)) return this.record(node, scope);\n if (is.isArrayLiteralExpression(node)) {\n const items: Expr[] = [];\n let rest: Expr | undefined;\n for (const item of node.elements) {\n if (rest) this.fail(\"a spread that is not last in an array literal\", item);\n if (is.isSpreadElement(item)) rest = this.expression(item.expression, scope);\n else if (is.isOmittedExpression(item)) this.fail(\"a hole in an array literal\", item);\n else items.push(this.expression(item, scope));\n }\n return { kind: \"list\", items, ...(rest ? { rest } : {}) };\n }\n if (is.isArrowFunction(node) || is.isFunctionExpression(node))\n this.fail(\"a function expression (the subset has callbacks of list methods only)\", node);\n if (is.isAsExpression(node)) this.fail(\"the as operator\", node);\n if (is.isSatisfiesExpression(node)) this.fail(\"the satisfies operator\", node);\n if (is.isNonNullExpression(node)) this.fail(\"the ! assertion\", node);\n if (is.isTypeAssertion(node)) this.fail(\"a type assertion\", node);\n if (node.kind === SyntaxKind.ThisKeyword) this.fail(\"this\", node);\n this.fail(`unexpected ${this.text(node) || kindName(node.kind)}`, node);\n }\n\n private identifier(node: Identifier, scope: Scope): Expr {\n const name = node.text;\n if (name === \"undefined\") this.fail(\"undefined (the subset has null)\", node);\n if (scope.has(name) || this.names.declared(name)) return { kind: \"var\", name };\n const constant = this.constant?.(node, (what) => this.fail(what, node));\n if (constant) return constant;\n // A built-in the compiler resolves to something other than its standard library: an import of the\n // name, say. (`Math.abs` reaches here too, as the global: its method is what the subset lacks.)\n if ((name === \"Math\" || name === \"Number\") && !this.names.global(node))\n this.fail(\n `${name}, which is not the standard ${name} here: a declaration of it other than the compiler's is in scope`,\n node,\n );\n this.fail(\n this.names.spec\n ? `${name}, which is neither a parameter, a const nor a function imported from the module beside the spec file`\n : `${name}, which is neither a parameter, a const nor a function of this module`,\n node,\n );\n }\n\n /** Whether an element access is `xs[0]`. */\n private isHead(node: Node): boolean {\n return (\n is.isElementAccessExpression(node) &&\n is.isNumericLiteral(node.argumentExpression) &&\n this.text(node.argumentExpression) === \"0\"\n );\n }\n\n private binary(node: BinaryExpression, scope: Scope): Expr {\n const kind = node.operatorToken.kind;\n const op = binaryOps[kind];\n if (op) {\n return {\n kind: \"binary\",\n op,\n left: this.expression(node.left, scope),\n right: this.expression(node.right, scope),\n };\n }\n if (kind === SyntaxKind.QuestionQuestionToken) {\n // `xs[0] ?? fallback` only: any other index may be past the end, which is undefined.\n if (is.isBinaryExpression(node.left) && node.left.operatorToken.kind === kind)\n this.fail(\"a chain of ??\", node);\n if (is.isElementAccessExpression(node.left) && !this.isHead(node.left))\n this.fail(\"index access other than xs[0] ?? fallback\", node.left);\n if (!is.isElementAccessExpression(node.left))\n this.fail(\n \"?? after anything but xs[0] (write xs[0] ?? fallback, parenthesized where it meets other operators)\",\n node,\n );\n if (node.left.questionDotToken) this.fail(\"optional chaining\", node.left);\n return {\n kind: \"headOr\",\n list: this.expression(node.left.expression, scope),\n fallback: this.expression(node.right, scope),\n };\n }\n if (kind >= SyntaxKind.FirstAssignment && kind <= SyntaxKind.LastAssignment)\n this.fail(\"an assignment\", node);\n if (kind === SyntaxKind.CommaToken) this.fail(\"the comma operator\", node);\n if (kind === SyntaxKind.InKeyword || kind === SyntaxKind.InstanceOfKeyword)\n this.fail(`the ${this.text(node.operatorToken)} operator`, node);\n this.fail(`the ${this.text(node.operatorToken)} operator`, node);\n }\n\n private call(node: CallExpression, scope: Scope): Expr {\n if (node.questionDotToken) this.fail(\"optional chaining\", node);\n let callee = node.expression;\n while (is.isParenthesizedExpression(callee)) callee = callee.expression;\n if (is.isPropertyAccessExpression(callee)) {\n if (callee.questionDotToken) this.fail(\"optional chaining\", callee);\n if (!is.isIdentifier(callee.name)) this.fail(\"a private method\", callee.name);\n const method = callee.name.text;\n const receiver = callee.expression;\n if (\n is.isIdentifier(receiver) &&\n receiver.text === \"Number\" &&\n method === \"isInteger\" &&\n this.global(receiver, scope)\n ) {\n const [arg, extra] = node.arguments;\n if (!arg || extra) this.fail(\"Number.isInteger takes one argument\", node);\n return { kind: \"isInteger\", operand: this.expression(arg, scope) };\n }\n if (\n is.isIdentifier(receiver) &&\n receiver.text === \"Math\" &&\n method === \"floor\" &&\n this.global(receiver, scope)\n ) {\n const [arg, extra] = node.arguments;\n if (!arg || extra) this.fail(\"Math.floor takes one argument\", node);\n return { kind: \"floor\", operand: this.expression(arg, scope) };\n }\n // The receiver first: `Math.abs` fails on `Math`, a name of nothing here, before its method.\n const list = this.expression(receiver, scope);\n if (!methods.has(method))\n this.fail(\n `the method ${method} (the subset has slice(1), map, flatMap, every, some and reduce)`,\n callee.name,\n );\n return this.method(node, list, method, scope);\n }\n if (!is.isIdentifier(callee)) this.fail(\"a call to a computed callee\", callee);\n const name = callee.text;\n // A binder or local named like a function shadows it: the call is to a number, which throws.\n if (scope.has(name))\n this.fail(`a call to ${name}, which names a value here, not the module's function`, callee);\n if (!this.names.callable(name) && this.inline) {\n const readArgs = (types: readonly (SubsetType | undefined)[]): Expr[] =>\n node.arguments.map((a, i) => {\n if (is.isSpreadElement(a)) this.fail(\"a spread argument\", a);\n const type = types[i];\n if (!type) return this.expression(a, scope);\n // The literals the argument evaluates to: itself, or a conditional's branches.\n const literals: Node[] = [];\n const collect = (e: Expression): void => {\n if (is.isParenthesizedExpression(e)) collect(e.expression);\n else if (is.isConditionalExpression(e)) {\n collect(e.whenTrue);\n collect(e.whenFalse);\n } else if (is.isObjectLiteralExpression(e)) literals.push(e);\n };\n collect(a);\n for (const l of literals) this.typedAs.set(l, type);\n try {\n return this.expression(a, scope);\n } finally {\n for (const l of literals) this.typedAs.delete(l);\n }\n });\n const inlined = this.inline(node, callee, scope, readArgs, (what) => this.fail(what, node));\n if (inlined) return inlined;\n }\n if (!this.names.declared(name)) this.identifier(callee, scope); // names nothing here: its message\n if (!this.names.callable(name))\n this.fail(`a call to ${name}, which is outside the subset`, callee);\n return {\n kind: \"call\",\n callee: this.names.target(name),\n args: node.arguments.map((a) => {\n if (is.isSpreadElement(a)) this.fail(\"a spread argument\", a);\n return this.expression(a, scope);\n }),\n };\n }\n\n /** `(a, b) => body` or `a => body`, an expression body only; the names it binds go into scope. */\n private callback(\n node: Expression,\n scope: Scope,\n arity: number,\n what: string,\n ): { names: string[]; body: Expr } {\n if (!is.isArrowFunction(node)) this.fail(`${what} takes an arrow function`, node);\n const arrow: ArrowFunction = node;\n // An async callback returns a promise, truthy whatever the body computes.\n if (isAsync(arrow)) this.fail(`an async callback in ${what}`, arrow);\n const names: string[] = [];\n for (const p of arrow.parameters) {\n if (!is.isIdentifier(p.name)) this.fail(`a destructured parameter of ${what}'s callback`, p);\n if (p.type) this.fail(`a type annotation on ${what}'s parameter`, p.type);\n if (p.initializer) this.fail(`a default value on ${what}'s parameter`, p);\n if (p.dotDotDotToken) this.fail(`a rest parameter on ${what}'s callback`, p);\n names.push(p.name.text);\n }\n if (names.length === 0 || names.length > arity)\n this.fail(\n `${what} takes a callback of 1 to ${arity} parameter(s), given ${names.length}`,\n arrow,\n );\n for (const n of names)\n if (scope.has(n) || this.names.declared(n))\n this.fail(`${what}'s parameter ${n} shadows a name already bound here`, arrow);\n if (new Set(names).size !== names.length)\n this.fail(`${what}'s parameters repeat a name`, arrow);\n if (is.isBlock(arrow.body))\n this.fail(`a block body in ${what}'s callback (write an expression)`, arrow.body);\n const inner = new Map(scope);\n for (const n of names) inner.set(n, { kind: \"null\" });\n return { names, body: this.expression(arrow.body, inner) };\n }\n\n /** A method call on a list: slice(1), map, flatMap, every, some, reduce. */\n private method(node: CallExpression, list: Expr, name: string, scope: Scope): Expr {\n const args = node.arguments;\n if (name === \"slice\") {\n const [one, extra] = args;\n if (!one || extra || !is.isNumericLiteral(one) || this.text(one) !== \"1\")\n this.fail(\"slice with an argument other than 1\", one ?? node);\n return { kind: \"tail\", list };\n }\n if (name === \"reduce\") {\n const [cb, init, extra] = args;\n if (!cb || !init || extra) this.fail(\"reduce takes a callback and an initial value\", node);\n const { names, body } = this.callback(cb, scope, 2, \"reduce\");\n if (names.length !== 2) this.fail(\"reduce takes a callback of (accumulator, item)\", cb);\n return {\n kind: \"fold\",\n list,\n acc: names[0] as string,\n item: names[1] as string,\n body,\n init: this.expression(init, scope),\n };\n }\n const [cb, extra] = args;\n if (!cb || extra) this.fail(`${name} takes one callback`, node);\n const { names, body } = this.callback(cb, scope, 2, name);\n return {\n kind: \"iterate\",\n op: name as \"map\" | \"flatMap\" | \"every\" | \"some\",\n list,\n item: names[0] as string,\n ...(names[1] === undefined ? {} : { index: names[1] }),\n body,\n };\n }\n\n private record(node: ObjectLiteralExpression, scope: Scope): Expr {\n const fields: { name: string; value: Expr }[] = [];\n for (const p of node.properties) {\n if (is.isSpreadAssignment(p)) this.fail(\"spread in a record literal\", p);\n if (is.isShorthandPropertyAssignment(p)) {\n if (!is.isIdentifier(p.name))\n this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);\n const name = p.name.text;\n if (name === \"__proto__\")\n this.fail(\"a __proto__ key, which sets the prototype, not a field\", p);\n if (!scope.has(name)) this.fail(`shorthand ${name} names nothing in scope`, p);\n fields.push({ name, value: { kind: \"var\", name } });\n continue;\n }\n if (!is.isPropertyAssignment(p)) this.fail(`a method ${this.text(p).split(\"(\")[0] ?? \"\"}`, p);\n if (is.isComputedPropertyName(p.name)) this.fail(\"a computed key\", p.name);\n if (!is.isIdentifier(p.name))\n this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);\n if (p.name.text === \"__proto__\")\n this.fail(\"a __proto__ key, which sets the prototype, not a field\", p.name);\n fields.push({ name: p.name.text, value: this.expression(p.initializer, scope) });\n }\n const type = this.typedAs.get(node) ?? this.types.contextual(node);\n const literal = (fs: typeof fields): Expr => ({\n kind: \"record\",\n fields: fs,\n ...(type ? { type } : {}),\n });\n // A member of a union picked by a conditional tag (`{ type: c ? \"a\" : \"b\", at }`) is one literal\n // per branch: the conditional moves out, the other fields go into each as written. The fields\n // are pure, so evaluating the test first computes the same value.\n const tag = type?.kind === \"union\" ? tagOf(type.name, this.ctx) : undefined;\n const chosen = tag === undefined ? undefined : fields.find((f) => f.name === tag);\n if (chosen?.value.kind === \"cond\") {\n const split = (value: Expr): Expr =>\n value.kind === \"cond\"\n ? {\n kind: \"cond\",\n test: value.test,\n ifTrue: split(value.ifTrue),\n ifFalse: split(value.ifFalse),\n }\n : literal(fields.map((f) => (f === chosen ? { name: f.name, value } : f)));\n return split(chosen.value);\n }\n return literal(fields);\n }\n}\n\n/**\n * A `const` annotation inside a spec arrow, read from its syntax against\n * the module's declared types: no compiler stands behind an arrow's\n * text, so a name must be a record or union the module reads, and the\n * forms are the primitives, `null`, literals, unions of those and arrays.\n */\nexport function syntacticType(\n sf: SourceFile,\n node: TypeNode,\n records: ReadonlySet<string>,\n unions: ReadonlySet<string>,\n refuse: Refuse,\n): SubsetType {\n const go = (n: TypeNode): SubsetType => syntacticType(sf, n, records, unions, refuse);\n if (is.isParenthesizedTypeNode(node)) return go(node.type);\n if (is.isTypeOperatorNode(node) && node.operator === SyntaxKind.ReadonlyKeyword) {\n if (!is.isArrayTypeNode(node.type))\n return refuse(\"readonly before a type that is not an array\");\n return go(node.type);\n }\n if (is.isArrayTypeNode(node)) return { kind: \"list\", element: go(node.elementType) };\n if (node.kind === SyntaxKind.NumberKeyword) return { kind: \"int\" };\n if (node.kind === SyntaxKind.BooleanKeyword) return { kind: \"bool\" };\n if (node.kind === SyntaxKind.StringKeyword) return { kind: \"string\" };\n if (node.kind === SyntaxKind.UndefinedKeyword)\n return refuse(\"undefined in a type (the subset has null)\");\n if (is.isLiteralTypeNode(node)) {\n const lit = node.literal;\n if (lit.kind === SyntaxKind.NullKeyword) return { kind: \"null\" };\n if (lit.kind === SyntaxKind.TrueKeyword || lit.kind === SyntaxKind.FalseKeyword)\n return { kind: \"bool\" };\n if (is.isStringLiteral(lit)) return { kind: \"string\" };\n return refuse(`the literal type ${textOf(sf, node)}`);\n }\n if (is.isTypeReferenceNode(node)) {\n if (node.typeArguments)\n return refuse(`type ${textOf(sf, node)} (a generic type in an arrow's const)`);\n if (!is.isIdentifier(node.typeName)) return refuse(`type ${textOf(sf, node)}`);\n const name = node.typeName.text;\n if (records.has(name)) return { kind: \"record\", name };\n if (unions.has(name)) return { kind: \"union\", name };\n return refuse(\n `type ${name} (the subset has number, boolean, string, null, and the module's own record types and unions)`,\n );\n }\n if (is.isUnionTypeNode(node)) {\n const members = node.types.map(go);\n const nulls = members.filter((m) => m.kind === \"null\");\n const rest = members.filter((m) => m.kind !== \"null\");\n const first = rest[0];\n if (!first) return refuse(\"null alone is not a type the subset takes\");\n if (!rest.every((m) => JSON.stringify(m) === JSON.stringify(first)))\n return refuse(\"a union of several types (declare it as a type alias in the module)\");\n if (nulls.length === 0) return first;\n return first.kind === \"nullable\" ? first : { kind: \"nullable\", inner: first };\n }\n return refuse(`type ${textOf(sf, node)}`);\n}\n\n/**\n * The block body of an arrow read from a parsed fragment: the statements\n * between the braces, every path returning.\n */\nexport function blockOf(sf: SourceFile): Block | undefined {\n const [first, second] = sf.statements;\n return first && !second && is.isBlock(first) ? first : undefined;\n}\n","/**\n * The compiler's types read two ways. `specTypeOf` reads a type into\n * `SpecType` as far as the spec surface describes it (primitives,\n * literals, records, unions, arrays), marking the rest `unknown` with its\n * text: binder domains for the simulator's rungs. `SubsetTypes` reads a\n * type into the subset's own types (integers, booleans, strings, records,\n * nullable types, tagged unions, lists), naming every record and union it\n * meets so the engines can declare them: a declared type by its name, an\n * instantiated generic or an inline object type as the compiler prints\n * it, a union member declared inline by its union and its tag. Both read\n * what the compiler resolved, so a type declared later in the file, in\n * another file, or through a generic alias reads as its structure.\n */\n\nimport type { SpecType } from \"@eutaxy/spec\";\nimport { SyntaxKind } from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport {\n type Checker,\n SymbolFlags,\n type Type,\n TypeFlags,\n TypeFormatFlags,\n type TypeReference,\n} from \"typescript/sync\";\nimport type { Field, RecordType, SubsetType, UnionType } from \"./subset.ts\";\n\n/** Levels of records and lists inside one another a type may hold before it is cut (a generic instantiating itself anew at each level never repeats). */\nconst maxDepth = 16;\n\n/**\n * Why an object type is not plain data, or undefined when it is: a class\n * (an instance is more than its fields: nominal, with private ones), or an\n * interface over a base the compiler could not resolve (it then shows the\n * interface's own fields alone) or over a class.\n */\nexport function notPlain(\n checker: Checker,\n type: Type,\n seen: Set<number> = new Set(),\n): string | undefined {\n const symbol = type.getSymbol();\n if (!symbol || seen.has(type.id)) return undefined;\n seen.add(type.id);\n if ((symbol.flags & SymbolFlags.Class) !== 0)\n return \"a class (an instance is more than a record of its fields)\";\n if ((symbol.flags & SymbolFlags.Interface) === 0) return undefined;\n for (const handle of symbol.declarations) {\n if (handle.kind !== SyntaxKind.InterfaceDeclaration) continue;\n const decl = handle.resolve();\n if (!decl || !is.isInterfaceDeclaration(decl)) continue;\n for (const clause of decl.heritageClauses ?? [])\n for (const base of clause.types) {\n const baseType = checker.getTypeAtLocation(base);\n if (baseType.isErrorType()) return `extends ${base.getText()}, which does not resolve`;\n // The whole ancestry: a class anywhere up makes the interface nominal.\n const why = notPlain(checker, baseType, seen);\n if (why !== undefined) return `extends ${base.getText()}: ${why}`;\n }\n }\n return undefined;\n}\n\n/** A type as the compiler prints it, in full. */\nexport function printType(checker: Checker, type: Type): string {\n return checker.typeToString(type, undefined, TypeFormatFlags.NoTruncation);\n}\n\n/**\n * The name a record or union goes by: its alias or interface name when\n * declared without type arguments, otherwise the type as the compiler\n * prints it (`Result<true, Locked>`, `{ readonly ok: boolean; }`).\n */\nexport function nameOfType(checker: Checker, type: Type): string {\n const alias = type.getAliasSymbol();\n if (alias)\n return type.getAliasTypeArguments().length === 0 ? alias.name : printType(checker, type);\n const symbol = type.getSymbol();\n if (\n symbol &&\n (symbol.flags & (SymbolFlags.Interface | SymbolFlags.Class)) !== 0 &&\n !(type.isTypeReference() && checker.getTypeArguments(type).length > 0)\n )\n return symbol.name;\n return printType(checker, type);\n}\n\n/** A union's members with `true | false` folded back into `boolean`, which the compiler keeps apart. */\nfunction foldBooleans(members: readonly Type[]): (Type | \"boolean\")[] {\n const isTrue = (t: Type) => t.isBooleanLiteralType() && t.value === true;\n const isFalse = (t: Type) => t.isBooleanLiteralType() && t.value === false;\n if (!members.some(isTrue) || !members.some(isFalse)) return [...members];\n const out: (Type | \"boolean\")[] = [];\n let folded = false;\n for (const m of members) {\n if (isTrue(m) || isFalse(m)) {\n if (!folded) out.push(\"boolean\");\n folded = true;\n } else out.push(m);\n }\n return out;\n}\n\n/** The members of a union as one type: flattened, deduplicated, one member alone. */\nexport function unionOf(members: readonly SpecType[]): SpecType {\n const flat = members.flatMap((m) => (m.kind === \"union\" ? m.members : [m]));\n const seen = new Set<string>();\n const unique = flat.filter((m) => {\n const key = JSON.stringify(m);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n return unique.length === 1 ? (unique[0] as SpecType) : { kind: \"union\", members: unique };\n}\n\n/** A type into `SpecType`; what the spec surface does not describe is `unknown` with the type's text. */\nexport function specTypeOf(\n checker: Checker,\n type: Type,\n seen: ReadonlySet<number> = new Set(),\n): SpecType {\n const unknown = (): SpecType => ({ kind: \"unknown\", text: printType(checker, type) });\n const flags = type.flags;\n if (type.isErrorType()) return unknown();\n if (flags & TypeFlags.Number) return { kind: \"number\" };\n if (flags & TypeFlags.String) return { kind: \"string\" };\n if (flags & TypeFlags.Boolean) return { kind: \"boolean\" };\n if (flags & TypeFlags.BigInt) return { kind: \"bigint\" };\n if (type.isStringLiteralType() || type.isNumberLiteralType() || type.isBooleanLiteralType())\n return { kind: \"literal\", value: type.value };\n if (flags & TypeFlags.Null) return { kind: \"null\" };\n if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return { kind: \"undefined\" };\n if (type.isUnionType())\n return unionOf(\n foldBooleans(type.getTypes()).map((m) =>\n m === \"boolean\" ? { kind: \"boolean\" } : specTypeOf(checker, m, seen),\n ),\n );\n if (!type.isObjectType()) return unknown();\n // A type reaching itself through a field or an element: the cycle is cut with the type's name;\n // one that nests without repeating is cut at a depth.\n if (seen.has(type.id) || seen.size >= maxDepth) return unknown();\n const inner = new Set(seen).add(type.id);\n if (checker.isArrayType(type)) {\n const element = checker.getTypeArguments(type as TypeReference)[0];\n return element ? { kind: \"array\", element: specTypeOf(checker, element, inner) } : unknown();\n }\n if (\n type.isTupleType() ||\n type.getCallSignatures().length > 0 ||\n type.getConstructSignatures().length > 0 ||\n type.getIndexInfos().length > 0\n )\n return unknown();\n if (notPlain(checker, type) !== undefined) return unknown();\n const properties = type.getProperties();\n // An object with a method or an accessor is no record of plain data (a Map, a class instance), and\n // neither is one keyed by a symbol (the compiler names it `__@key@…`, which no string names).\n const computed = SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor;\n if (properties.some((p) => (p.flags & computed) !== 0 || isSymbolKey(p.name))) return unknown();\n const fields = properties.map((p) => ({\n name: p.name,\n type: specTypeOf(checker, checker.getTypeOfSymbol(p), inner),\n }));\n return { kind: \"record\", name: nameOfType(checker, type), fields };\n}\n\n/** Whether a property's name is the compiler's spelling of a symbol key, which no string names. */\nconst isSymbolKey = (name: string): boolean => name.startsWith(\"__@\");\n\n/** Names a Lean structure declaration generates itself, which a field cannot take. */\nconst structureNames = new Set([\n \"mk\",\n \"rec\",\n \"recOn\",\n \"casesOn\",\n \"noConfusion\",\n \"noConfusionType\",\n \"injEq\",\n]);\n\n/** `OutsideSubset` at the type being read, by the reader that asked. */\nexport type Refuse = (what: string) => never;\n\n/**\n * The subset's types read from the compiler's, with every record and\n * union met along the way kept by name, in the order met, for the engines\n * to declare. One type is read once: a second meeting gives the same\n * record, and so does another compiler type of the same name and the\n * same fields (an inline type written twice). A type the subset does not\n * take is refused with the construct named, and a read that is refused\n * leaves nothing behind: whatever it registered on the way is taken back,\n * so no record belongs to a union that was never declared.\n */\nexport class SubsetTypes {\n readonly records = new Map<string, RecordType>();\n readonly unions: UnionType[] = [];\n private readonly checker: Checker;\n /** By the compiler's type id. */\n private readonly byId = new Map<number, SubsetType>();\n private readonly idOfName = new Map<string, number>();\n /** Types being read now, to refuse a type that holds itself. */\n private readonly reading = new Set<number>();\n\n constructor(checker: Checker) {\n this.checker = checker;\n }\n\n /** The subset type of a compiler type, or a refusal, after which nothing of the read remains. */\n of(type: Type, refuse: Refuse): SubsetType {\n const cached = this.byId.get(type.id);\n if (cached) return cached;\n if (this.reading.size > 0) return this.enter(type, refuse);\n // The outermost read of a type: all or nothing.\n const saved = {\n records: new Map(this.records),\n idOfName: new Map(this.idOfName),\n byId: new Map(this.byId),\n unions: this.unions.length,\n };\n try {\n return this.enter(type, refuse);\n } catch (err) {\n this.records.clear();\n for (const [k, v] of saved.records) this.records.set(k, v);\n this.idOfName.clear();\n for (const [k, v] of saved.idOfName) this.idOfName.set(k, v);\n this.byId.clear();\n for (const [k, v] of saved.byId) this.byId.set(k, v);\n this.unions.length = saved.unions;\n throw err;\n }\n }\n\n /** A type read under the recursion guard. */\n private enter(type: Type, refuse: Refuse): SubsetType {\n // A type reaching itself, through a field or an element, is refused rather than followed.\n if (this.reading.has(type.id))\n return refuse(`${nameOfType(this.checker, type)} holds itself (a recursive type)`);\n if (this.reading.size >= maxDepth)\n return refuse(\n `${nameOfType(this.checker, type)} is nested too deep (more than ${maxDepth} levels)`,\n );\n this.reading.add(type.id);\n try {\n const out = this.read(type, refuse);\n this.byId.set(type.id, out);\n return out;\n } finally {\n this.reading.delete(type.id);\n }\n }\n\n private read(type: Type, refuse: Refuse): SubsetType {\n const checker = this.checker;\n const text = () => printType(checker, type);\n const flags = type.flags;\n if (type.isErrorType()) return refuse(`type ${text()}, which does not resolve`);\n if (flags & TypeFlags.Number) return { kind: \"int\" };\n if (flags & (TypeFlags.String | TypeFlags.StringLiteral)) return { kind: \"string\" };\n if (flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) return { kind: \"bool\" };\n if (flags & TypeFlags.Null) return refuse(\"null alone is not a type the subset takes\");\n if (flags & (TypeFlags.Undefined | TypeFlags.Void))\n return refuse(\"undefined in a type (the subset has null)\");\n if (flags & TypeFlags.NumberLiteral)\n return refuse(`the numeric literal type ${text()} (the subset has number)`);\n if (flags & TypeFlags.BigInt) return refuse(\"bigint (the subset has number)\");\n if (flags & TypeFlags.TypeParameter) return refuse(\"type parameters\");\n if (type.isUnionType()) return this.union(type, refuse);\n if (type.isIntersectionType()) return refuse(\"an intersection type\");\n if (!type.isObjectType())\n return refuse(\n `type ${text()} (the subset has number, boolean, string, null, and record types, unions and arrays of them)`,\n );\n if (checker.isArrayType(type)) {\n const element = checker.getTypeArguments(type as TypeReference)[0];\n if (!element) return refuse(`type ${text()}`);\n return { kind: \"list\", element: this.of(element, refuse) };\n }\n if (type.isTupleType()) return refuse(\"a tuple type\");\n if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0)\n return refuse(\"a function type\");\n if (type.getIndexInfos().length > 0) return refuse(\"an index signature\");\n const why = notPlain(checker, type);\n if (why !== undefined) return refuse(`type ${text()} is outside the subset: ${why}`);\n const record = this.record(type, nameOfType(checker, type), refuse);\n return { kind: \"record\", name: record.name };\n }\n\n /** A union: `T | null` a nullable, literals their base type, several records a tagged union. */\n private union(type: Type, refuse: Refuse): SubsetType {\n const members = type.isUnionType() ? type.getTypes() : [type];\n if (members.some((m) => (m.flags & (TypeFlags.Undefined | TypeFlags.Void)) !== 0))\n return refuse(\"undefined in a type (the subset has null)\");\n const nulls = members.filter((m) => (m.flags & TypeFlags.Null) !== 0);\n const rest = members.filter((m) => (m.flags & TypeFlags.Null) === 0);\n const bare = nulls.length === 0 ? type : type.getNonNullableType();\n let base: SubsetType;\n if (rest.length === 0) return refuse(\"null alone is not a type the subset takes\");\n else if (rest.every((m) => (m.flags & (TypeFlags.String | TypeFlags.StringLiteral)) !== 0))\n base = { kind: \"string\" };\n else if (rest.every((m) => (m.flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) !== 0))\n base = { kind: \"bool\" };\n else if (rest.length === 1) base = this.of(rest[0] as Type, refuse);\n else if (rest.every((m) => m.isObjectType() && !this.checker.isArrayType(m)))\n base = this.taggedUnion(bare, rest, refuse);\n else if (rest.some((m) => m.isObjectType()))\n return refuse(\"a union mixing records with other types\");\n else if (rest.every((m) => (m.flags & TypeFlags.NumberLiteral) !== 0))\n return refuse(\n `the numeric literal type ${printType(this.checker, type)} (the subset has number)`,\n );\n else\n return refuse(\n `a union of several types (${printType(this.checker, type)}): the subset has a union of literals of one kind, a tagged union of records, and either with null`,\n );\n if (nulls.length === 0) return base;\n if (base.kind === \"nullable\") return base;\n return { kind: \"nullable\", inner: base };\n }\n\n /**\n * A union of records, told apart by a tag: a literal-typed field every\n * member has, holding a different literal in each. Members declared\n * inline are named by the union and their tag (`Outcome.true`); a\n * record declared on its own keeps its name, and may be a member of several unions.\n */\n private taggedUnion(type: Type, members: readonly Type[], refuse: Refuse): SubsetType {\n const cached = this.byId.get(type.id);\n if (cached) return cached;\n const checker = this.checker;\n const name = nameOfType(checker, type);\n // One name, one type: a second union of the name, or a record of it, is a clash.\n const taken = this.idOfName.get(name);\n if (taken !== undefined && taken !== type.id) return refuse(`two types named ${name}`);\n if (taken === undefined && (this.records.has(name) || this.unions.some((u) => u.name === name)))\n return refuse(`two types named ${name}`);\n const literalFields = (m: Type): Map<string, string | boolean> => {\n const out = new Map<string, string | boolean>();\n for (const p of m.getProperties()) {\n const t = checker.getTypeOfSymbol(p);\n if (t.isStringLiteralType() || t.isBooleanLiteralType()) out.set(p.name, t.value);\n }\n return out;\n };\n const literals = members.map(literalFields);\n const tag = [...(literals[0] as Map<string, string | boolean>).keys()].find(\n (field) =>\n literals.every((l) => l.has(field)) &&\n new Set(literals.map((l) => JSON.stringify(l.get(field)))).size === literals.length,\n );\n if (tag === undefined)\n return refuse(\n `${name}: a union of records without a tag (a literal-typed field every member has, different in each)`,\n );\n const isAnonymous = (m: Type) =>\n !m.getAliasSymbol() &&\n ((m.getSymbol()?.flags ?? 0) & (SymbolFlags.Interface | SymbolFlags.Class)) === 0;\n const read = members.map((m, i) => {\n const value = (literals[i] as Map<string, string | boolean>).get(tag) as string | boolean;\n const memberName = isAnonymous(m) ? `${name}.${String(value)}` : nameOfType(checker, m);\n const record = this.record(m, memberName, refuse, name);\n return { tag: value, record: record.name };\n });\n const union: UnionType = { name, tag, members: read };\n this.unions.push(union);\n this.idOfName.set(name, type.id);\n const out: SubsetType = { kind: \"union\", name };\n this.byId.set(type.id, out);\n return out;\n }\n\n /** A record under `name`: its fields read, the record kept; a member of `union` when given. */\n private record(type: Type, name: string, refuse: Refuse, union?: string): RecordType {\n let known = this.records.get(name);\n // A union of the name is a clash: one name, one type.\n if (!known && this.unions.some((u) => u.name === name))\n return refuse(`two types named ${name}`);\n if (known && this.idOfName.get(name) !== type.id) {\n // Another compiler type of the same name (an inline type written twice, say) is the same\n // record when it has the same fields, and a clash otherwise.\n const fields = this.fieldsOf(type, name, refuse);\n if (JSON.stringify(fields) !== JSON.stringify(known.fields))\n return refuse(`two types named ${name}`);\n this.byId.set(type.id, { kind: \"record\", name });\n }\n if (known) {\n if (union !== undefined && !known.unions?.includes(union)) {\n known = { ...known, unions: [...(known.unions ?? []), union] };\n this.records.set(name, known);\n }\n return known;\n }\n const fields = this.fieldsOf(type, name, refuse);\n const record: RecordType = {\n name,\n fields,\n ...(union === undefined ? {} : { unions: [union] }),\n };\n this.records.set(name, record);\n this.idOfName.set(name, type.id);\n this.byId.set(type.id, { kind: \"record\", name });\n return record;\n }\n\n /** The fields of a record type, each a stored value the subset takes. */\n private fieldsOf(type: Type, name: string, refuse: Refuse): Field[] {\n // A member read straight from its union is guarded here; one read through `of` already is.\n const guard = !this.reading.has(type.id);\n if (guard) this.reading.add(type.id);\n try {\n const checker = this.checker;\n const fields: Field[] = [];\n const outside: Refuse = (what) => refuse(`type ${name} is outside the subset: ${what}`);\n for (const p of type.getProperties()) {\n if (isSymbolKey(p.name)) return outside(\"a field keyed by a symbol\");\n if ((p.flags & SymbolFlags.Optional) !== 0) return outside(`optional field ${p.name}`);\n if ((p.flags & SymbolFlags.Method) !== 0) return outside(`a method ${p.name}`);\n // A getter computes; a stored field it is not.\n if ((p.flags & (SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) !== 0)\n return outside(`an accessor ${p.name}`);\n if (structureNames.has(p.name))\n return outside(`field ${p.name} takes a name Lean's structures reserve`);\n if (p.name === \"__proto__\")\n return outside(\"a field named __proto__, which JavaScript treats specially\");\n const fieldType = checker.getTypeOfSymbol(p);\n const read = this.of(fieldType, (what) => outside(`field ${p.name}: ${what}`));\n const literal = fieldType.isStringLiteralType()\n ? fieldType.value\n : fieldType.isBooleanLiteralType()\n ? fieldType.value\n : undefined;\n fields.push({ name: p.name, type: read, ...(literal === undefined ? {} : { literal }) });\n }\n return fields;\n } finally {\n if (guard) this.reading.delete(type.id);\n }\n }\n}\n","/**\n * The pure TypeScript subset the first-party engines accept, read into a\n * small tree: exported functions (declarations, and arrows a module-level\n * `const` holds) over `number`, `boolean` and `string`,\n * record types, nullable types (`T | null`) and tagged unions of records,\n * lists of any of those, returning any of those; bodies made of `const`\n * bindings, `if` with early returns, `return`, and expressions from\n * arithmetic (`+ - *`), comparisons, `=== !==` (`null` included, which\n * narrows a nullable name in the branch it guards), `&& || !`, the\n * conditional operator, record and array literals, field reads (on a\n * union, only a field every member has), list methods and calls to the\n * module's own functions. Types are whatever the compiler resolves them\n * to: declared anywhere in the file, imported from another file, or an\n * instantiated generic. Anything else is `OutsideSubset`, with the\n * construct named: the subset is specified by the contract corpus and\n * widens one characterised class at a time. What each engine takes of it\n * is the engine's business (`restrictModule`). This module holds the\n * subset's meaning: its types and tree, typing, narrowing, renaming and\n * the three passes over a module; `expressions.ts` reads the syntax and\n * `types.ts` the compiler's types.\n */\n\nimport type { Arrow } from \"@eutaxy/spec\";\nimport {\n type ArrowFunction,\n type AsExpression,\n type Expression,\n type FunctionDeclaration,\n type FunctionExpression,\n forEachLeadingCommentRange,\n forEachTrailingCommentRange,\n type Identifier,\n InternalSymbolName,\n type Node,\n type NonNullExpression,\n type ObjectLiteralExpression,\n type ParenthesizedExpression,\n type SatisfiesExpression,\n type SourceFile,\n SyntaxKind,\n type TypeAssertion,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport { type Checker, SymbolFlags, type Type } from \"typescript/sync\";\nimport {\n type CompilerError,\n type InputFile,\n isAsync,\n isConst,\n lineAt,\n openParen,\n textOf,\n withProgram,\n withSourceFile,\n} from \"./compiler.ts\";\nimport {\n blockOf,\n type Constant,\n ExprReader,\n type Inline,\n type Names,\n syntacticType,\n type TypeSource,\n} from \"./expressions.ts\";\nimport { SubsetTypes } from \"./types.ts\";\n\nexport class OutsideSubset extends Error {\n readonly line: number;\n constructor(message: string, line: number) {\n super(message);\n this.line = line;\n }\n}\n\nexport type SubsetType =\n | { readonly kind: \"int\" }\n | { readonly kind: \"bool\" }\n | { readonly kind: \"string\" }\n | { readonly kind: \"record\"; readonly name: string }\n /** `T | null`. */\n | { readonly kind: \"nullable\"; readonly inner: SubsetType }\n /** A tagged union of records declared as a type alias; its members are records of the module. */\n | { readonly kind: \"union\"; readonly name: string }\n /** The type of the literal `null` itself, which only a nullable type accepts. */\n | { readonly kind: \"null\" }\n /** `readonly T[]` or `T[]`: a list of values of one type (Lean's `List`). */\n | { readonly kind: \"list\"; readonly element: SubsetType }\n /** The element type of `[]`, which fits in a list of any type. */\n | { readonly kind: \"nothing\" };\n\nexport interface Field {\n readonly name: string;\n readonly type: SubsetType;\n /** The one value a literal-typed field holds (`ok: true`, `type: \"locked\"`): a union member's tag. */\n readonly literal?: string | boolean;\n}\n\nexport interface RecordType {\n readonly name: string;\n readonly fields: readonly Field[];\n /**\n * The tagged unions this record is a member of, in the order they were\n * read: `Err<E>` is one in `Result<A, E>` and in `Result<B, E>`. A member\n * written inline in a union is named `<union>.<tag>` after the first.\n */\n readonly unions?: readonly string[];\n}\n\n/** Whether a record is a member of a union. */\nexport function isMember(record: RecordType | undefined, union: string): boolean {\n return record?.unions?.includes(union) ?? false;\n}\n\n/** A union's members among the records known, in the order they were read. */\nfunction membersIn(union: string, ctx: TypeContext): RecordType[] {\n return [...ctx.records.values()].filter((rec) => isMember(rec, union));\n}\n\n/** A tagged union: records told apart by one field, the tag, which holds a different literal in each. */\nexport interface UnionType {\n readonly name: string;\n readonly tag: string;\n /** The member records, in declaration order, by their tag's value. */\n readonly members: readonly { readonly tag: string | boolean; readonly record: string }[];\n}\n\nexport type BinaryOp =\n | \"+\"\n | \"-\"\n | \"*\"\n | \"/\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"===\"\n | \"!==\"\n | \"&&\"\n | \"||\";\n\nexport type Expr =\n | { readonly kind: \"int\"; readonly value: string }\n | { readonly kind: \"bool\"; readonly value: boolean }\n | { readonly kind: \"string\"; readonly value: string }\n | { readonly kind: \"null\" }\n | { readonly kind: \"var\"; readonly name: string }\n /** In `body`, `name` (a nullable in scope) stands for its non-null value: inserted where a null check guards. */\n | { readonly kind: \"narrow\"; readonly name: string; readonly body: Expr }\n /** In `body`, `name` (a union in scope) is its member `member`: inserted where a test of the union's tag guards. */\n | {\n readonly kind: \"narrowTag\";\n readonly name: string;\n readonly member: string;\n readonly body: Expr;\n }\n | { readonly kind: \"neg\"; readonly operand: Expr }\n | { readonly kind: \"not\"; readonly operand: Expr }\n /** `Number.isInteger(e)`: always true of an integer in the engines' integer model, the real predicate on doubles. */\n | { readonly kind: \"isInteger\"; readonly operand: Expr }\n /** `Math.floor(e)`: rounding toward negative infinity on doubles; the identity on the integers. */\n | { readonly kind: \"floor\"; readonly operand: Expr }\n | { readonly kind: \"binary\"; readonly op: BinaryOp; readonly left: Expr; readonly right: Expr }\n | { readonly kind: \"cond\"; readonly test: Expr; readonly ifTrue: Expr; readonly ifFalse: Expr }\n | { readonly kind: \"call\"; readonly callee: string; readonly args: readonly Expr[] }\n | { readonly kind: \"field\"; readonly object: Expr; readonly field: string }\n | {\n readonly kind: \"record\";\n readonly fields: readonly { readonly name: string; readonly value: Expr }[];\n /** The type its context gives the literal (a declared return type, a const annotation, a parameter), as the compiler sees it: a record, or the union a member is picked from. */\n readonly type?: SubsetType;\n }\n | {\n readonly kind: \"let\";\n readonly name: string;\n readonly value: Expr;\n readonly body: Expr;\n /** The `const`'s annotation, when it has one: the binding's type, whatever the initializer's. */\n readonly type?: SubsetType;\n }\n /** `[a, b]`, or `[a, b, ...rest]` with the spread last. `xs.length` is a `field` read on a list. */\n | { readonly kind: \"list\"; readonly items: readonly Expr[]; readonly rest?: Expr }\n /** `xs.slice(1)`: every element but the first. */\n | { readonly kind: \"tail\"; readonly list: Expr }\n /** `xs[0] ?? fallback`: the first element, or the fallback for an empty list. */\n | { readonly kind: \"headOr\"; readonly list: Expr; readonly fallback: Expr }\n /** `xs.map`, `xs.flatMap`, `xs.every` or `xs.some` with `(item, index?) => body`. */\n | {\n readonly kind: \"iterate\";\n readonly op: \"map\" | \"flatMap\" | \"every\" | \"some\";\n readonly list: Expr;\n readonly item: string;\n readonly index?: string;\n readonly body: Expr;\n }\n /** `xs.reduce((acc, item) => body, init)`: a left fold. */\n | {\n readonly kind: \"fold\";\n readonly list: Expr;\n readonly acc: string;\n readonly item: string;\n readonly body: Expr;\n readonly init: Expr;\n };\n\nexport interface Param {\n readonly name: string;\n readonly type: SubsetType;\n}\n\nexport interface SubsetFunction {\n readonly name: string;\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n readonly body: Expr;\n /** 1-based line of the declaration. */\n readonly line: number;\n /** Offset of the `(` opening its parameters: the declaration's identity, as the spec extractor records it. */\n readonly offset: number;\n /**\n * For a recursive function, the list parameter it recurses on (its\n * index): the body tests that list's length against 0 first, and every\n * call to itself, in the other branch, passes that list's slice(1).\n */\n readonly structural?: number;\n}\n\n/** A function the subset does not take, and why. */\nexport interface OutsideFunction {\n readonly name: string;\n readonly line: number;\n readonly message: string;\n}\n\nexport interface SubsetModule {\n readonly records: readonly RecordType[];\n readonly unions: readonly UnionType[];\n /** The functions in the subset, in source order, callees before callers. */\n readonly functions: readonly SubsetFunction[];\n /** The module's other functions: outside the subset themselves, or calling one that is. */\n readonly outside: readonly OutsideFunction[];\n}\n\n/** Whether a string holds a surrogate code unit without its pair: no Lean character corresponds to it. */\nexport function hasLoneSurrogate(s: string): boolean {\n return /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/.test(s);\n}\n\n/** A type, for messages. */\nexport function describe(t: SubsetType): string {\n switch (t.kind) {\n case \"record\":\n case \"union\":\n return t.name;\n case \"nullable\":\n return `${describe(t.inner)} | null`;\n case \"list\":\n return t.element.kind === \"nullable\"\n ? `(${describe(t.element)})[]`\n : `${describe(t.element)}[]`;\n default:\n return t.kind;\n }\n}\n\nconst sameType = (a: SubsetType, b: SubsetType): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n/**\n * Whether a value of one type may stand where another is expected: the\n * same type; a member record where its union is; `null`, or the inner\n * type, where a nullable is.\n */\nexport function fits(actual: SubsetType, expected: SubsetType, ctx: TypeContext): boolean {\n if (sameType(actual, expected)) return true;\n // The element of `[]` is no value at all, so it stands for any; a list fits where its elements do.\n if (actual.kind === \"nothing\") return true;\n if (actual.kind === \"list\" && expected.kind === \"list\")\n return fits(actual.element, expected.element, ctx);\n if (expected.kind === \"union\")\n return actual.kind === \"record\" && isMember(ctx.records.get(actual.name), expected.name);\n if (expected.kind === \"nullable\")\n return (\n actual.kind === \"null\" ||\n (actual.kind === \"nullable\"\n ? fits(actual.inner, expected.inner, ctx)\n : fits(actual, expected.inner, ctx))\n );\n return false;\n}\n\n/** The type two branches share, or undefined when they share none. */\nfunction join(a: SubsetType, b: SubsetType, ctx: TypeContext): SubsetType | undefined {\n if (fits(a, b, ctx)) return b;\n if (fits(b, a, ctx)) return a;\n if (a.kind === \"list\" && b.kind === \"list\") {\n const element = join(a.element, b.element, ctx);\n return element && { kind: \"list\", element };\n }\n if (a.kind === \"record\" && b.kind === \"record\") {\n // Two members of one union join to it; members of several unions in common join to none,\n // since nothing says which (an expected type, where one is given, decides instead).\n const ub = ctx.records.get(b.name)?.unions ?? [];\n const common = (ctx.records.get(a.name)?.unions ?? []).filter((u) => ub.includes(u));\n if (common.length === 1) return { kind: \"union\", name: common[0] as string };\n }\n if (a.kind === \"nullable\" && b.kind === \"nullable\") {\n const inner = join(a.inner, b.inner, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n if (a.kind === \"null\" && b.kind !== \"null\") return { kind: \"nullable\", inner: b };\n if (b.kind === \"null\" && a.kind !== \"null\") return { kind: \"nullable\", inner: a };\n if (a.kind === \"nullable\" && b.kind !== \"null\" && b.kind !== \"nullable\") {\n const inner = join(a.inner, b, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n if (b.kind === \"nullable\" && a.kind !== \"null\" && a.kind !== \"nullable\") {\n const inner = join(a, b.inner, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n return undefined;\n}\n\n/** Whether `===` between the two types is in the subset, and on records (references in JavaScript) it is not. */\nfunction comparable(l: SubsetType, r: SubsetType): boolean {\n const base = (t: SubsetType): SubsetType => (t.kind === \"nullable\" ? t.inner : t);\n if (l.kind === \"null\" && r.kind === \"null\") return false;\n if (l.kind === \"null\") return r.kind === \"nullable\";\n if (r.kind === \"null\") return l.kind === \"nullable\";\n return sameType(base(l), base(r)) && !isReference(base(l));\n}\n\nconst isReference = (t: SubsetType): boolean =>\n t.kind === \"record\" || t.kind === \"union\" || t.kind === \"list\";\n\n/**\n * The names a test, holding or failing, shows to be non-null: `x !== null`\n * holding, `x === null` failing, through `!`, `&&` (holding) and `||`\n * (failing).\n */\nexport function narrowsOf(test: Expr, holds: boolean): string[] {\n // A narrowing already inserted around an operand (the right side of `&&`) hides nothing.\n if (test.kind === \"narrow\" || test.kind === \"narrowTag\") return narrowsOf(test.body, holds);\n const isNull = (e: Expr) => e.kind === \"null\";\n if (test.kind === \"binary\" && (test.op === \"===\" || test.op === \"!==\")) {\n const other = isNull(test.right) ? test.left : isNull(test.left) ? test.right : undefined;\n if (other?.kind !== \"var\") return [];\n return (test.op === \"!==\") === holds ? [other.name] : [];\n }\n if (test.kind === \"not\") return narrowsOf(test.operand, !holds);\n if (test.kind === \"binary\" && test.op === \"&&\" && holds)\n return [...narrowsOf(test.left, true), ...narrowsOf(test.right, true)];\n if (test.kind === \"binary\" && test.op === \"||\" && !holds)\n return [...narrowsOf(test.left, false), ...narrowsOf(test.right, false)];\n return [];\n}\n\n/** The field that tells a union's members apart: literal-typed in every member, with a different literal in each. */\nexport function tagOf(union: string, ctx: TypeContext): string | undefined {\n const members = membersIn(union, ctx);\n const first = members[0];\n if (!first) return undefined;\n return first.fields\n .filter((f) => f.literal !== undefined)\n .map((f) => f.name)\n .find((name) => {\n const values = members.map((m) => m.fields.find((f) => f.name === name)?.literal);\n return (\n values.every((v) => v !== undefined) &&\n new Set(values.map((v) => JSON.stringify(v))).size === values.length\n );\n });\n}\n\n/**\n * The names a test, holding or failing, shows to be one member of their\n * union, with that member: `x.tag === \"a\"` holding (or `!==` failing)\n * names the member tagged `\"a\"`; failing, the other member when the\n * union has two; `x.ok` alone is the test of a boolean tag; through `!`,\n * `&&` (holding) and `||` (failing) as null checks are.\n */\nexport function tagNarrowsOf(\n test: Expr,\n holds: boolean,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n): { name: string; member: string }[] {\n // The union a `x.tag` read is the tag of, with its members by tag value.\n const tagged = (e: Expr): { name: string; members: readonly RecordType[] } | undefined => {\n if (e.kind !== \"field\" || e.object.kind !== \"var\") return undefined;\n const t = scope.get(e.object.name);\n if (t?.kind !== \"union\" || tagOf(t.name, ctx) !== e.field) return undefined;\n return {\n name: e.object.name,\n members: membersIn(t.name, ctx),\n };\n };\n const byTag = (\n read: { name: string; members: readonly RecordType[] },\n tag: string,\n value: string | boolean,\n isIt: boolean,\n ): { name: string; member: string }[] => {\n const same = read.members.filter(\n (m) => m.fields.find((f) => f.name === tag)?.literal === value,\n );\n const chosen = isIt ? same : read.members.filter((m) => !same.includes(m));\n return chosen.length === 1 ? [{ name: read.name, member: (chosen[0] as RecordType).name }] : [];\n };\n if (test.kind === \"narrow\" || test.kind === \"narrowTag\")\n return tagNarrowsOf(test.body, holds, scope, ctx);\n if (test.kind === \"binary\" && (test.op === \"===\" || test.op === \"!==\")) {\n const literal = (e: Expr) => (e.kind === \"string\" || e.kind === \"bool\" ? e.value : undefined);\n const [field, value] =\n literal(test.right) !== undefined\n ? [test.left, literal(test.right)]\n : [test.right, literal(test.left)];\n if (value === undefined || field.kind !== \"field\") return [];\n const read = tagged(field);\n if (!read) return [];\n return byTag(read, field.field, value, (test.op === \"===\") === holds);\n }\n if (test.kind === \"field\") {\n const read = tagged(test);\n return read ? byTag(read, test.field, holds, true) : [];\n }\n if (test.kind === \"not\") return tagNarrowsOf(test.operand, !holds, scope, ctx);\n if (test.kind === \"binary\" && test.op === \"&&\" && holds)\n return [\n ...tagNarrowsOf(test.left, true, scope, ctx),\n ...tagNarrowsOf(test.right, true, scope, ctx),\n ];\n if (test.kind === \"binary\" && test.op === \"||\" && !holds)\n return [\n ...tagNarrowsOf(test.left, false, scope, ctx),\n ...tagNarrowsOf(test.right, false, scope, ctx),\n ];\n return [];\n}\n\n/**\n * `narrow` and `narrowTag` nodes inserted where a test guards: in a\n * conditional's branches, and in the right operand of `&&` and `||`, for\n * each nullable name the test shows to be non-null there and each union\n * name it shows to be one member there.\n */\nexport function insertNarrows(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): Expr {\n const go = (x: Expr, sc: ReadonlyMap<string, SubsetType>): Expr =>\n insertNarrows(x, sc, ctx, fail);\n // Where JavaScript tests truthiness (a condition, the operand of `!`), a nullable record or union\n // is falsy exactly when it is null, since an object is always truthy: `c` there is `c !== null`,\n // which then narrows as a null check does. A nullable number or string is no object, and stays.\n const probe = Symbol(\"untyped\");\n const condition = (x: Expr, sc: ReadonlyMap<string, SubsetType>): Expr => {\n if (x.kind === \"binary\" && (x.op === \"&&\" || x.op === \"||\"))\n return { ...x, left: condition(x.left, sc), right: condition(x.right, sc) };\n if (x.kind === \"not\") return { kind: \"not\", operand: condition(x.operand, sc) };\n let t: SubsetType;\n try {\n t = typeOf(x, sc, ctx, () => {\n throw probe;\n });\n } catch (err) {\n if (err === probe) return x;\n throw err;\n }\n if (t.kind === \"nullable\" && (t.inner.kind === \"record\" || t.inner.kind === \"union\"))\n return { kind: \"binary\", op: \"!==\", left: x, right: { kind: \"null\" } };\n return x;\n };\n const wrap = (\n body: Expr,\n test: Expr,\n holds: boolean,\n sc: ReadonlyMap<string, SubsetType>,\n ): Expr => {\n const inner = new Map(sc);\n let out = body;\n const nullable = [...new Set(narrowsOf(test, holds))].filter(\n (n) => sc.get(n)?.kind === \"nullable\",\n );\n for (const n of nullable) inner.set(n, (sc.get(n) as { inner: SubsetType }).inner);\n // Tag tests are read in the scope null checks leave: `x !== null && x.ok` narrows x twice.\n const tags: { name: string; member: string }[] = [];\n for (const t of tagNarrowsOf(test, holds, inner, ctx))\n if (!tags.some((x) => x.name === t.name)) {\n tags.push(t);\n inner.set(t.name, { kind: \"record\", name: t.member });\n }\n out = go(out, inner);\n for (const t of tags.reverse())\n out = { kind: \"narrowTag\", name: t.name, member: t.member, body: out };\n for (const n of nullable.reverse()) out = { kind: \"narrow\", name: n, body: out };\n return out;\n };\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return e;\n case \"not\":\n return { kind: \"not\", operand: go(condition(e.operand, scope), scope) };\n case \"neg\":\n case \"isInteger\":\n case \"floor\":\n return { kind: e.kind, operand: go(e.operand, scope) };\n case \"narrow\":\n case \"narrowTag\":\n return e;\n case \"binary\": {\n const left = go(e.left, scope);\n if (e.op === \"&&\")\n return { kind: \"binary\", op: e.op, left, right: wrap(e.right, left, true, scope) };\n if (e.op === \"||\")\n return { kind: \"binary\", op: e.op, left, right: wrap(e.right, left, false, scope) };\n return { kind: \"binary\", op: e.op, left, right: go(e.right, scope) };\n }\n case \"cond\": {\n const test = go(condition(e.test, scope), scope);\n return {\n kind: \"cond\",\n test,\n ifTrue: wrap(e.ifTrue, test, true, scope),\n ifFalse: wrap(e.ifFalse, test, false, scope),\n };\n }\n case \"call\":\n return { kind: \"call\", callee: e.callee, args: e.args.map((a) => go(a, scope)) };\n case \"field\":\n return { kind: \"field\", object: go(e.object, scope), field: e.field };\n case \"record\":\n return { ...e, fields: e.fields.map((f) => ({ name: f.name, value: go(f.value, scope) })) };\n case \"let\": {\n const value = go(e.value, scope);\n const inner = new Map(scope);\n inner.set(e.name, e.type ?? typeOf(value, scope, ctx, fail));\n return { ...e, value, body: go(e.body, inner) };\n }\n case \"list\":\n return {\n kind: \"list\",\n items: e.items.map((x) => go(x, scope)),\n ...(e.rest ? { rest: go(e.rest, scope) } : {}),\n };\n case \"tail\":\n return { kind: \"tail\", list: go(e.list, scope) };\n case \"headOr\":\n return { kind: \"headOr\", list: go(e.list, scope), fallback: go(e.fallback, scope) };\n case \"iterate\": {\n const list = go(e.list, scope);\n return { ...e, list, body: go(e.body, iterateScope(e, list, scope, ctx, fail)) };\n }\n case \"fold\": {\n const list = go(e.list, scope);\n const init = go(e.init, scope);\n // The callback's names before its body is typed: its null checks narrow first, as in map.\n const inner = new Map(scope);\n inner.set(e.acc, typeOf(init, scope, ctx, fail));\n inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), \"reduce\", fail));\n return { ...e, list, init, body: go(e.body, inner) };\n }\n }\n}\n\n/**\n * The element type of a list expression's type. An operation on an empty\n * array no type is given for (`[].length`, `[].slice(1)`) is refused: an\n * engine could only guess the element type, and such code has a plain\n * value to write instead; `const xs: T[] = []` gives one.\n */\nfunction elementOf(t: SubsetType, what: string, fail: (message: string) => never): SubsetType {\n if (t.kind !== \"list\") fail(`${what} on a ${describe(t)}, not a list`);\n if (holdsNothing(t))\n fail(`${what} on an empty array of no declared type (annotate it: const xs: T[] = [])`);\n return t.element;\n}\n\n/** Whether a type holds the element type of an empty array literal anywhere in it (`[[]]` does). */\nfunction holdsNothing(t: SubsetType): boolean {\n if (t.kind === \"nothing\") return true;\n if (t.kind === \"list\") return holdsNothing(t.element);\n if (t.kind === \"nullable\") return holdsNothing(t.inner);\n return false;\n}\n\n/** The scope inside an iteration's callback: the item an element, the index an integer. */\nfunction iterateScope(\n e: Extract<Expr, { kind: \"iterate\" }>,\n list: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): Map<string, SubsetType> {\n const inner = new Map(scope);\n inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), e.op, fail));\n if (e.index !== undefined) inner.set(e.index, { kind: \"int\" });\n return inner;\n}\n\n/**\n * The scope inside a fold's callback and the accumulator's type: the\n * initial value's, widened once to the body's when the body's holds it.\n * A callback that takes the accumulator apart as a list needs the initial\n * value typed (`xs.reduce((acc, x) => [x, ...acc], [])` does not\n * type-check in TypeScript either).\n */\nfunction foldScope(\n e: Extract<Expr, { kind: \"fold\" }>,\n list: Expr,\n init: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): { scope: Map<string, SubsetType>; acc: SubsetType } {\n const item = elementOf(typeOf(list, scope, ctx, fail), \"reduce\", fail);\n const at = (acc: SubsetType) => new Map([...scope, [e.acc, acc], [e.item, item]]);\n const start = typeOf(init, scope, ctx, fail);\n const body = typeOf(e.body, at(start), ctx, fail);\n if (fits(body, start, ctx)) return { scope: at(start), acc: start };\n if (fits(start, body, ctx) && fits(typeOf(e.body, at(body), ctx, fail), body, ctx))\n return { scope: at(body), acc: body };\n fail(`reduce's callback makes a ${describe(body)} from an accumulator of ${describe(start)}`);\n}\n\n/** A function's parameters and return type, for typing calls. */\nexport interface CalleeSignature {\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n}\n\n/** What typing an expression needs to know about its module. */\nexport interface TypeContext {\n readonly records: ReadonlyMap<string, RecordType>;\n readonly signatures: ReadonlyMap<string, CalleeSignature>;\n}\n\n/** The type of an expression in a scope; records are matched by their fields' names. */\nexport function typeOf(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n /**\n * The type the context declares for `e` (a return type, a const's\n * annotation, a parameter): it decides a conditional whose branches are\n * members of several unions in common, where they alone join to none.\n */\n expected?: SubsetType,\n): SubsetType {\n switch (e.kind) {\n case \"int\":\n return { kind: \"int\" };\n case \"bool\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"null\":\n return { kind: \"null\" };\n case \"var\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n return t;\n }\n case \"narrow\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n if (t.kind !== \"nullable\")\n fail(`${e.name} is narrowed but is a ${describe(t)}, not a nullable`);\n return typeOf(e.body, new Map([...scope, [e.name, t.inner]]), ctx, fail, expected);\n }\n case \"narrowTag\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n if (t.kind !== \"union\")\n fail(`${e.name} is narrowed by a tag but is a ${describe(t)}, not a union`);\n if (!isMember(ctx.records.get(e.member), t.name))\n fail(`${e.member} is not a member of ${t.name}`);\n return typeOf(\n e.body,\n new Map([...scope, [e.name, { kind: \"record\", name: e.member }]]),\n ctx,\n fail,\n expected,\n );\n }\n case \"binary\": {\n const l = typeOf(e.left, scope, ctx, fail);\n const r = typeOf(e.right, scope, ctx, fail);\n // `+` joins two strings; every other arithmetic or ordering operator is on integers only\n // (ordering strings compares UTF-16 code units in JavaScript and characters in Lean: not the same).\n if (e.op === \"+\" && l.kind === \"string\" && r.kind === \"string\") return { kind: \"string\" };\n const arithmetic = [\"+\", \"-\", \"*\", \"/\", \"<\", \"<=\", \">\", \">=\"].includes(e.op);\n if (arithmetic && (l.kind !== \"int\" || r.kind !== \"int\"))\n fail(\n `${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on integers${e.op === \"+\" ? \", and + on two strings\" : \"\"})`,\n );\n if ((e.op === \"&&\" || e.op === \"||\") && (l.kind !== \"bool\" || r.kind !== \"bool\"))\n fail(`${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on booleans)`);\n if (e.op === \"===\" || e.op === \"!==\") {\n // Against null, any nullable; otherwise records and unions are references in JavaScript.\n const againstNull = l.kind === \"null\" || r.kind === \"null\";\n const base = (t: SubsetType): SubsetType => (t.kind === \"nullable\" ? t.inner : t);\n if (!againstNull && (isReference(base(l)) || isReference(base(r))))\n fail(\n `${e.op} on records compares references in JavaScript; compare their fields instead`,\n );\n if (!comparable(l, r)) fail(`${e.op} between a ${describe(l)} and a ${describe(r)}`);\n }\n return [\"+\", \"-\", \"*\", \"/\"].includes(e.op) ? { kind: \"int\" } : { kind: \"bool\" };\n }\n case \"neg\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`unary minus on a ${t.kind}`);\n return { kind: \"int\" };\n }\n case \"not\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"bool\") fail(`! on a ${t.kind}`);\n return { kind: \"bool\" };\n }\n case \"isInteger\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`Number.isInteger on a ${t.kind}`);\n return { kind: \"bool\" };\n }\n case \"floor\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`Math.floor on a ${t.kind}`);\n return { kind: \"int\" };\n }\n case \"cond\": {\n const test = typeOf(e.test, scope, ctx, fail);\n if (test.kind !== \"bool\")\n fail(\n `a condition that is a ${describe(test)} (truthiness is not in the subset; compare it)`,\n );\n const a = typeOf(e.ifTrue, scope, ctx, fail, expected);\n const b = typeOf(e.ifFalse, scope, ctx, fail, expected);\n const joined = join(a, b, ctx);\n if (joined) return joined;\n if (expected && fits(a, expected, ctx) && fits(b, expected, ctx)) return expected;\n return fail(\n `the branches of a conditional have different types (${describe(a)} and ${describe(b)})`,\n );\n }\n case \"let\": {\n const inferred = typeOf(e.value, scope, ctx, fail, e.type);\n if (e.type && !fits(inferred, e.type, ctx))\n fail(`const ${e.name} is annotated ${describe(e.type)} but holds a ${describe(inferred)}`);\n if (!e.type && holdsNothing(inferred))\n fail(\n `const ${e.name} holds an empty array of no declared type (annotate it: const ${e.name}: T[] = [])`,\n );\n return typeOf(e.body, new Map([...scope, [e.name, e.type ?? inferred]]), ctx, fail, expected);\n }\n case \"call\": {\n const sig = ctx.signatures.get(e.callee);\n if (!sig) fail(`the signature of ${e.callee} is not known`);\n if (sig.params.length !== e.args.length)\n fail(`${e.callee} takes ${sig.params.length} argument(s), called with ${e.args.length}`);\n e.args.forEach((a, i) => {\n const want = sig.params[i]?.type as SubsetType;\n const got = typeOf(a, scope, ctx, fail, want);\n if (!fits(got, want, ctx))\n fail(\n `argument ${i + 1} of ${e.callee} is a ${describe(got)}, not the ${describe(want)} it takes`,\n );\n });\n return sig.returns;\n }\n case \"field\": {\n const o = typeOf(e.object, scope, ctx, fail);\n if (o.kind === \"list\") {\n if (e.field !== \"length\") fail(`${e.field} read from a list (the subset has length)`);\n elementOf(o, \"length\", fail);\n return { kind: \"int\" };\n }\n if (o.kind === \"nullable\")\n fail(\n `field ${e.field} read from a ${describe(o)}: compare it with null first, which narrows it`,\n );\n if (o.kind === \"union\") {\n // Only a field every member has, with one type: the tag, typically. Narrowing by the tag is not in the subset yet.\n const members = membersIn(o.name, ctx);\n const types = members.map((rec) => rec.fields.find((x) => x.name === e.field)?.type);\n if (types.some((t) => t === undefined))\n fail(\n `field ${e.field} is not on every member of ${o.name} (test the tag first, which narrows it)`,\n );\n const first = types[0] as SubsetType;\n if (!types.every((t) => sameType(t as SubsetType, first)))\n fail(`field ${e.field} has different types across the members of ${o.name}`);\n return first;\n }\n if (o.kind !== \"record\") fail(`field ${e.field} read from a ${describe(o)}`);\n const f = ctx.records.get(o.name)?.fields.find((x) => x.name === e.field);\n if (!f) fail(`${o.name} has no field ${e.field}`);\n return f.type;\n }\n case \"record\": {\n // The record types whose fields are exactly these names, then those whose field types the values fit.\n const names = e.fields\n .map((f) => f.name)\n .sort()\n .join(\",\");\n // The context's type, when the compiler gave one, narrows the candidates: the record itself, or a union's members.\n const context = e.type;\n const candidates =\n context?.kind === \"record\"\n ? [...ctx.records.values()].filter((rec) => rec.name === context.name)\n : context?.kind === \"union\"\n ? membersIn(context.name, ctx)\n : [...ctx.records.values()];\n const byNames = candidates.filter(\n (rec) =>\n rec.fields\n .map((f) => f.name)\n .sort()\n .join(\",\") === names,\n );\n if (byNames.length === 0)\n fail(`a record literal with fields ${names} matches no declared record type`);\n const types = new Map(e.fields.map((f) => [f.name, typeOf(f.value, scope, ctx, fail)]));\n const fitting = byNames.filter((rec) =>\n rec.fields.every((f) => fits(types.get(f.name) as SubsetType, f.type, ctx)),\n );\n if (fitting.length === 0) {\n const rec = byNames[0] as RecordType;\n const off = rec.fields.find(\n (f) => !fits(types.get(f.name) as SubsetType, f.type, ctx),\n ) as Field;\n fail(\n `field ${off.name} of a ${rec.name} literal holds a ${describe(types.get(off.name) as SubsetType)}, not a ${describe(off.type)}`,\n );\n }\n // Among a union's members, the literal's tag tells them apart.\n const literalOf = (name: string): string | boolean | undefined => {\n const v = e.fields.find((f) => f.name === name)?.value;\n return v?.kind === \"string\" || v?.kind === \"bool\" ? v.value : undefined;\n };\n const tagged = fitting.filter((rec) =>\n rec.fields.every((f) => f.literal === undefined || literalOf(f.name) === f.literal),\n );\n const chosen = tagged.length > 0 ? tagged : fitting;\n if (chosen.length > 1)\n fail(\n `a record literal with fields ${names} matches ${chosen.map((r) => r.name).join(\" and \")} alike`,\n );\n return { kind: \"record\", name: (chosen[0] as RecordType).name };\n }\n case \"list\": {\n let element: SubsetType = { kind: \"nothing\" };\n const add = (t: SubsetType) => {\n const joined = join(element, t, ctx);\n if (!joined) fail(`an array literal of a ${describe(element)} and a ${describe(t)}`);\n element = joined;\n };\n for (const item of e.items) add(typeOf(item, scope, ctx, fail));\n if (e.rest) add(elementOf(typeOf(e.rest, scope, ctx, fail), \"a spread\", fail));\n return { kind: \"list\", element };\n }\n case \"tail\": {\n const t = typeOf(e.list, scope, ctx, fail);\n elementOf(t, \"slice\", fail);\n return t;\n }\n case \"headOr\": {\n const element = elementOf(typeOf(e.list, scope, ctx, fail), \"[0]\", fail);\n // `??` replaces null as well as the missing head: on a list of a nullable type it is not headD.\n if (element.kind === \"nullable\" || element.kind === \"null\")\n fail(\"xs[0] ?? on a list of a nullable type (?? replaces a null element too)\");\n const fallback = typeOf(e.fallback, scope, ctx, fail);\n const joined = join(element, fallback, ctx);\n if (!joined) fail(`?? between a ${describe(element)} and a ${describe(fallback)}`);\n return joined;\n }\n case \"iterate\": {\n const body = typeOf(e.body, iterateScope(e, e.list, scope, ctx, fail), ctx, fail);\n if (e.op === \"map\") return { kind: \"list\", element: body };\n if (e.op === \"flatMap\")\n return { kind: \"list\", element: elementOf(body, \"flatMap's callback result\", fail) };\n if (body.kind !== \"bool\")\n fail(`${e.op}'s callback returns a ${describe(body)}, not a boolean`);\n return { kind: \"bool\" };\n }\n case \"fold\":\n return foldScope(e, e.list, e.init, scope, ctx, fail).acc;\n }\n}\n\n/** Every name an expression binds or refers to: its variables and its lets. */\nfunction boundNames(e: Expr, out = new Set<string>()): Set<string> {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return out;\n case \"var\":\n out.add(e.name);\n return out;\n case \"narrow\":\n case \"narrowTag\":\n out.add(e.name);\n return boundNames(e.body, out);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return boundNames(e.operand, out);\n case \"binary\":\n boundNames(e.left, out);\n return boundNames(e.right, out);\n case \"cond\":\n boundNames(e.test, out);\n boundNames(e.ifTrue, out);\n return boundNames(e.ifFalse, out);\n case \"call\":\n for (const a of e.args) boundNames(a, out);\n return out;\n case \"field\":\n return boundNames(e.object, out);\n case \"record\":\n for (const f of e.fields) boundNames(f.value, out);\n return out;\n case \"let\":\n out.add(e.name);\n boundNames(e.value, out);\n return boundNames(e.body, out);\n case \"list\":\n for (const x of e.items) boundNames(x, out);\n return e.rest ? boundNames(e.rest, out) : out;\n case \"tail\":\n return boundNames(e.list, out);\n case \"headOr\":\n boundNames(e.list, out);\n return boundNames(e.fallback, out);\n case \"iterate\":\n out.add(e.item);\n if (e.index !== undefined) out.add(e.index);\n boundNames(e.list, out);\n return boundNames(e.body, out);\n case \"fold\":\n out.add(e.acc);\n out.add(e.item);\n boundNames(e.list, out);\n boundNames(e.init, out);\n return boundNames(e.body, out);\n }\n}\n\n/** A name not among `taken`: the name with underscores appended. */\nfunction fresh(name: string, taken: ReadonlySet<string>): string {\n let out = `${name}_`;\n while (taken.has(out)) out += \"_\";\n return out;\n}\n\n/**\n * The expression with its variables renamed (an arrow's own parameter\n * names to the binders'). A `let` whose name is a rename's target would\n * capture the renamed references in its body, so such a let is renamed to\n * a fresh name first; a let whose name is a rename's source shadows it.\n */\nexport function renameVars(\n e: Expr,\n names: ReadonlyMap<string, string>,\n taken: ReadonlySet<string> = new Set([...names.keys(), ...names.values(), ...boundNames(e)]),\n /** Names no binder in `e` may keep (the scope `e` is inlined into): such a binder moves to a fresh name. */\n avoid: ReadonlySet<string> = new Set(),\n): Expr {\n const go = (x: Expr): Expr => renameVars(x, names, taken, avoid);\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return e;\n case \"var\":\n return { kind: \"var\", name: names.get(e.name) ?? e.name };\n case \"narrow\":\n return { kind: \"narrow\", name: names.get(e.name) ?? e.name, body: go(e.body) };\n case \"narrowTag\":\n return { ...e, name: names.get(e.name) ?? e.name, body: go(e.body) };\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return { kind: e.kind, operand: go(e.operand) };\n case \"binary\":\n return { kind: \"binary\", op: e.op, left: go(e.left), right: go(e.right) };\n case \"cond\":\n return { kind: \"cond\", test: go(e.test), ifTrue: go(e.ifTrue), ifFalse: go(e.ifFalse) };\n case \"call\":\n return { kind: \"call\", callee: e.callee, args: e.args.map(go) };\n case \"field\":\n return { kind: \"field\", object: go(e.object), field: e.field };\n case \"record\":\n return { ...e, fields: e.fields.map((f) => ({ name: f.name, value: go(f.value) })) };\n case \"let\": {\n // A let binds its own name; a binder of that name is shadowed inside, as in the source.\n const inner = new Map(names);\n inner.delete(e.name);\n let bound = e.name;\n const targets = new Set([...names.values(), ...avoid]);\n if (targets.has(e.name)) {\n // The let would capture a renamed reference: the let itself moves out of the way, to a name\n // nothing in the expression uses (another let may already be spelled with the underscore).\n bound = fresh(e.name, taken);\n inner.set(e.name, bound);\n }\n return {\n ...e,\n name: bound,\n value: go(e.value),\n body: renameVars(e.body, inner, new Set([...taken, bound]), avoid),\n };\n }\n case \"list\":\n return { kind: \"list\", items: e.items.map(go), ...(e.rest ? { rest: go(e.rest) } : {}) };\n case \"tail\":\n return { kind: \"tail\", list: go(e.list) };\n case \"headOr\":\n return { kind: \"headOr\", list: go(e.list), fallback: go(e.fallback) };\n case \"iterate\": {\n const own = [e.item, ...(e.index === undefined ? [] : [e.index])];\n const { inner, bound, scoped } = bindAll(own, names, taken, avoid);\n return {\n ...e,\n list: go(e.list),\n item: bound[0] as string,\n ...(e.index === undefined ? {} : { index: bound[1] as string }),\n body: renameVars(e.body, inner, scoped, avoid),\n };\n }\n case \"fold\": {\n const { inner, bound, scoped } = bindAll([e.acc, e.item], names, taken, avoid);\n return {\n ...e,\n list: go(e.list),\n init: go(e.init),\n acc: bound[0] as string,\n item: bound[1] as string,\n body: renameVars(e.body, inner, scoped, avoid),\n };\n }\n }\n}\n\n/**\n * The renames inside a callback that binds `own` names, as for a let:\n * each shadows a rename of its own name, and one that is a rename's target\n * moves to a fresh name so it captures nothing.\n */\nfunction bindAll(\n own: readonly string[],\n names: ReadonlyMap<string, string>,\n taken: ReadonlySet<string>,\n avoid: ReadonlySet<string>,\n): { inner: Map<string, string>; bound: string[]; scoped: Set<string> } {\n const inner = new Map(names);\n const targets = new Set([...names.values(), ...avoid]);\n const scoped = new Set(taken);\n const bound = own.map((n) => {\n inner.delete(n);\n if (!targets.has(n)) return n;\n const moved = fresh(n, scoped);\n scoped.add(moved);\n inner.set(n, moved);\n return moved;\n });\n return { inner, bound, scoped };\n}\n\n/** The functions an expression calls. */\nfunction callees(e: Expr, out = new Set<string>()): Set<string> {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return out;\n case \"narrow\":\n case \"narrowTag\":\n return callees(e.body, out);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return callees(e.operand, out);\n case \"binary\":\n callees(e.left, out);\n return callees(e.right, out);\n case \"cond\":\n callees(e.test, out);\n callees(e.ifTrue, out);\n return callees(e.ifFalse, out);\n case \"call\":\n out.add(e.callee);\n for (const a of e.args) callees(a, out);\n return out;\n case \"field\":\n return callees(e.object, out);\n case \"record\":\n for (const f of e.fields) callees(f.value, out);\n return out;\n case \"let\":\n callees(e.value, out);\n return callees(e.body, out);\n case \"list\":\n for (const x of e.items) callees(x, out);\n return e.rest ? callees(e.rest, out) : out;\n case \"tail\":\n return callees(e.list, out);\n case \"headOr\":\n callees(e.list, out);\n return callees(e.fallback, out);\n case \"iterate\":\n callees(e.list, out);\n return callees(e.body, out);\n case \"fold\":\n callees(e.list, out);\n callees(e.init, out);\n return callees(e.body, out);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Reading: a module through the compiler, an arrow from its text.\n\n/** The path a module read from text alone is compiled under: an import of another file does not resolve from it. */\nconst virtualModulePath = \"/eutaxy/reader/module.ts\";\n\nexport interface ReadSubsetOptions {\n /** The module's path on disk, under which its imports resolve. Without it the module stands alone. */\n readonly path?: string;\n /** Other files the read sees in place of (or beside) the files on disk, by path. */\n readonly files?: readonly InputFile[];\n}\n\n/** What typing a module's expressions needs, shared by every function read. */\nfunction moduleContext(records: Map<string, RecordType>): {\n ctx: TypeContext;\n signatures: Map<string, CalleeSignature>;\n} {\n const signatures = new Map<string, CalleeSignature>();\n return { ctx: { records, signatures }, signatures };\n}\n\n/** The contextual type the compiler gives a record literal, as the subset reads it; undefined where it has none the subset takes. */\nfunction contextualType(\n checker: Checker,\n types: SubsetTypes,\n node: ObjectLiteralExpression,\n): SubsetType | undefined {\n const type = checker.getContextualType(node);\n if (!type) return undefined;\n // A context inferred from the literal itself (a callback's result, say) declares nothing: the\n // literal is matched against the declared records instead.\n const fromLiteral = (t: Type): boolean =>\n t.isObjectType() && t.getSymbol()?.name === InternalSymbolName.Object;\n if (fromLiteral(type) || (type.isUnionType() && type.getTypes().some(fromLiteral)))\n return undefined;\n const skip = Symbol(\"outside\");\n try {\n const read = types.of(type, () => {\n throw skip;\n });\n return read.kind === \"nullable\" ? read.inner : read;\n } catch (err) {\n if (err === skip) return undefined;\n throw err;\n }\n}\n\n/** The line of the first direct `eval` in the file: a mention that is not a property of something else. */\nfunction directEval(sf: SourceFile): number | undefined {\n let line: number | undefined;\n const visit = (node: Node): void => {\n if (line !== undefined) return;\n if (is.isIdentifier(node) && node.text === \"eval\") {\n const parent = node.parent;\n const property =\n (is.isPropertyAccessExpression(parent) && parent.name === node) ||\n (is.isPropertyAssignment(parent) && parent.name === node);\n if (!property) {\n line = lineAt(sf, node);\n return;\n }\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return line;\n}\n\n/** An expression TypeScript lets wrap another without changing what it names: parentheses and assertions. */\ntype Wrapper =\n | ParenthesizedExpression\n | NonNullExpression\n | AsExpression\n | SatisfiesExpression\n | TypeAssertion;\n\nfunction isWrapper(n: Node): n is Wrapper {\n return (\n is.isParenthesizedExpression(n) ||\n is.isNonNullExpression(n) ||\n is.isAsExpression(n) ||\n is.isSatisfiesExpression(n) ||\n is.isTypeAssertion(n)\n );\n}\n\n/** Whether a node is written to: assigned, updated, or bound by a destructuring or a `for` head. */\nfunction isWritten(node: Node): boolean {\n let n: Node = node;\n for (;;) {\n const p: Node = n.parent;\n if (!p) return false;\n if (isWrapper(p) && p.expression === n) {\n n = p;\n continue;\n }\n if (is.isBinaryExpression(p)) {\n const k = p.operatorToken.kind;\n if (p.left === n && k >= SyntaxKind.FirstAssignment && k <= SyntaxKind.LastAssignment)\n return true;\n return false;\n }\n if (is.isPrefixUnaryExpression(p) || is.isPostfixUnaryExpression(p))\n return p.operator === SyntaxKind.PlusPlusToken || p.operator === SyntaxKind.MinusMinusToken;\n if (is.isForInStatement(p) || is.isForOfStatement(p)) return p.initializer === n;\n // Inside a destructuring target, the whole pattern is what gets assigned.\n if (is.isArrayLiteralExpression(p) || is.isSpreadElement(p) || is.isSpreadAssignment(p)) {\n n = p;\n continue;\n }\n if (is.isPropertyAssignment(p) && p.initializer === n) {\n n = p.parent;\n continue;\n }\n if (is.isShorthandPropertyAssignment(p) && p.name === n) {\n n = p.parent;\n continue;\n }\n if (is.isObjectLiteralExpression(p)) {\n n = p;\n continue;\n }\n return false;\n }\n}\n\n/** What every PROVEN rests on besides the engine's model: the reader's assumption about the built-ins. */\nexport const builtinsAssumption =\n \"the built-ins the subset reads (Math, Number and the array methods) are the standard ones: a direct assignment to a global of the standard library or to a property of one, or through globalThis, self or window, in a read file is refused, but one made another way (Object.defineProperty, through an alias) or elsewhere (a polyfill, another module) is not seen\";\n\n/** Names a file reaches the globals through that the library the reads compile against does not declare. */\nconst globalObjects = new Set([\"globalThis\", \"self\", \"window\", \"global\"]);\n\n/**\n * The first direct assignment (or `delete`) in a file whose target is a\n * global of the compiler's standard library or a property of one, at any\n * depth (`Math.floor = …`, `Number[\"isInteger\"] = …`, `Array.prototype.map\n * = …`, `Math = …`), or anything under `globalThis`, `self`, `window` or\n * `global`, with its line; inside a function or not. The chain's root is\n * resolved by the compiler, so a local's `prototype` field is the local's.\n * What reaches a built-in another way (`Object.defineProperty`, an alias)\n * is not seen: `builtinsAssumption` says so.\n */\nexport function rebound(\n sf: SourceFile,\n checker: Checker,\n standardGlobal: (id: Identifier) => boolean,\n): { line: number; target: string } | undefined {\n let found: { line: number; target: string } | undefined;\n // `window` and its kin, by name, unless the name is a parameter or a local of some function here.\n const globalObject = (r: Identifier): boolean => {\n if (!globalObjects.has(r.text)) return false;\n const decl = checker.getSymbolAtLocation(r)?.valueDeclaration?.resolve();\n if (!decl) return true;\n if (decl.kind === SyntaxKind.Parameter) return false;\n return !(is.isVariableDeclaration(decl) && decl.parent.parent.parent !== decl.getSourceFile());\n };\n // The node a `delete` would take: the target with the wrappers around it.\n const outermost = (node: Node): Node => {\n let out: Node = node;\n for (let p: Node = out.parent; p && isWrapper(p) && p.expression === out; p = p.parent) out = p;\n return out;\n };\n const root = (node: Node): Node => {\n let n: Node = node;\n while (is.isPropertyAccessExpression(n) || is.isElementAccessExpression(n) || isWrapper(n))\n n = n.expression;\n return n;\n };\n const builtin = (node: Node): boolean => {\n const r = root(node);\n return is.isIdentifier(r) && (globalObject(r) || standardGlobal(r));\n };\n const visit = (node: Node): void => {\n if (found) return;\n if (\n (is.isPropertyAccessExpression(node) ||\n is.isElementAccessExpression(node) ||\n is.isIdentifier(node)) &&\n (isWritten(node) || is.isDeleteExpression(outermost(node).parent)) &&\n builtin(node)\n ) {\n found = { line: lineAt(sf, node), target: textOf(sf, node) };\n return;\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return found;\n}\n\n/**\n * The first `@ts-ignore` or `@ts-expect-error` directive in a range of a\n * file, with its position: a comment shaped as the compiler reads one (the\n * directive opens a `//` comment, or the last line of a block comment),\n * found as the compiler finds comments, leading or trailing a node's\n * text, so the words in prose or in a string are not one. A comment\n * before a closing token alone (`/* … *\\/ }`) is not seen; what it could\n * hide is on that token's line.\n */\nfunction directiveIn(\n sf: SourceFile,\n start: number,\n end: number,\n): { text: string; pos: number } | undefined {\n const text = sf.text;\n const singleLine = /^\\/\\/\\/?\\s*@ts-(ignore|expect-error)/;\n const lastLine = /^(?:\\/|\\*)*\\s*@ts-(ignore|expect-error)/;\n let found: { text: string; pos: number } | undefined;\n const check = (pos: number, commentEnd: number): void => {\n if (found || pos < start || commentEnd > end) return;\n const comment = text.slice(pos, commentEnd);\n const m = comment.startsWith(\"//\")\n ? singleLine.exec(comment)\n : lastLine.exec(comment.slice(comment.lastIndexOf(\"\\n\") + 1));\n if (m) found = { text: `@ts-${m[1]}`, pos };\n };\n const visit = (node: Node): void => {\n if (found || node.end < start || node.pos > end) return;\n forEachLeadingCommentRange(text, node.pos, check);\n forEachTrailingCommentRange(text, node.end, check);\n node.forEachChild(visit);\n };\n visit(sf);\n return found;\n}\n\n/**\n * The line of a `@ts-nocheck` directive at the top of a file, which turns\n * the compiler's checks off for all of it: as the compiler reads it, a\n * `//` comment opening with it, the last of it and `@ts-check` deciding.\n */\nfunction noCheckDirective(sf: SourceFile): number | undefined {\n const text = sf.text;\n const from = text.startsWith(\"#!\") ? Math.max(0, text.indexOf(\"\\n\")) : 0;\n let line: number | undefined;\n forEachLeadingCommentRange(text, from, (pos, end) => {\n const m = /^\\/\\/\\/?\\s*@ts-(check|nocheck)\\b/.exec(text.slice(pos, end));\n if (m) line = m[1] === \"nocheck\" ? sf.getLineAndCharacterOfPosition(pos).line + 1 : undefined;\n });\n return line;\n}\n\n/** A declaration's text, and the statement's leading comments, where a directive reaches its first line. */\ninterface DeclaredRange {\n readonly start: number;\n readonly end: number;\n readonly lead?: { readonly start: number; readonly end: number };\n}\n\n/**\n * Why a range of a file is not read: the first error the compiler reports\n * inside it, or a `@ts-ignore` or `@ts-expect-error` directive in it or\n * in the leading comments (where a directive reaches the first line),\n * which hides one from the reader. Undefined when the range is clean.\n */\nfunction notCompiled(\n sf: SourceFile,\n typeErrors: (path: string) => readonly CompilerError[],\n { start, end, lead }: DeclaredRange,\n): { message: string; line: number } | undefined {\n const error = typeErrors(sf.fileName).find((e) => e.pos < end && e.end > start);\n if (error)\n return { message: `the compiler reports an error: ${error.message}`, line: error.line };\n const silenced =\n (lead ? directiveIn(sf, lead.start, lead.end) : undefined) ?? directiveIn(sf, start, end);\n if (silenced)\n return {\n message: `a ${silenced.text} comment, which hides a compiler error from the reader`,\n line: sf.getLineAndCharacterOfPosition(silenced.pos).line + 1,\n };\n return undefined;\n}\n\n/**\n * Where a declared function's errors are looked for: its own declaration\n * (in a `const` list, a sibling's error, or a directive in a sibling's\n * body, is the sibling's), and for directives the statement's leading\n * comments too, since a directive above the statement reaches its first\n * line, siblings included.\n */\nfunction rangeOf(d: Declared): DeclaredRange {\n let declaration: Node = d.node;\n while (!is.isFunctionDeclaration(declaration) && !is.isVariableDeclaration(declaration))\n declaration = declaration.parent;\n const sf = d.statement.getSourceFile();\n return {\n start: declaration.pos,\n end: declaration.end,\n lead: { start: d.statement.pos, end: d.statement.getStart(sf) },\n };\n}\n\n/**\n * The declared functions the module assigns to anywhere, with the line\n * of the first assignment: what runs under such a name may not be its\n * declaration. A name is confirmed through the compiler, so a local of\n * the same name assigned in some block is not the function.\n */\nfunction assigned(\n sf: SourceFile,\n checker: Checker,\n declarations: ReadonlyMap<string, Declared>,\n): Map<string, number> {\n const out = new Map<string, number>();\n const symbolIds = new Map<string, number | undefined>();\n const idOf = (name: string): number | undefined => {\n if (!symbolIds.has(name)) {\n const decl = declarations.get(name);\n symbolIds.set(name, decl ? checker.getSymbolAtLocation(decl.name)?.id : undefined);\n }\n return symbolIds.get(name);\n };\n const visit = (node: Node): void => {\n if (\n is.isIdentifier(node) &&\n declarations.has(node.text) &&\n !out.has(node.text) &&\n isWritten(node)\n ) {\n const id = idOf(node.text);\n // In `({ f } = …)` the name is the property's; the value it assigns is the binding's symbol.\n const parent = node.parent;\n const symbol =\n is.isShorthandPropertyAssignment(parent) && parent.name === node\n ? checker.getShorthandAssignmentValueSymbol(parent)\n : checker.getSymbolAtLocation(node);\n if (id !== undefined && symbol?.id === id) out.set(node.text, lineAt(sf, node));\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return out;\n}\n\n/** A function as written: a declaration, or the arrow (or function expression) a module-level binding holds. */\ntype FunctionNode = FunctionDeclaration | ArrowFunction | FunctionExpression;\n\n/** A module-level function: its name, its node, and the statement declaring it (for its line). */\ninterface Declared {\n readonly name: Identifier;\n readonly node: FunctionNode;\n readonly statement: Node;\n}\n\n/** A function's header read: its typed parameters and return type, with the body still to read. */\ninterface Head {\n readonly name: string;\n readonly decl: FunctionNode;\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n readonly line: number;\n readonly offset: number;\n}\n\n/** The parameter names of a function the subset can take at all: synchronous, no generator, plain parameters. */\nfunction shape(reader: ExprReader, decl: FunctionNode): string[] {\n if (isAsync(decl)) reader.fail(\"an async function (core functions are synchronous)\", decl);\n if (!is.isArrowFunction(decl) && decl.asteriskToken) reader.fail(\"a generator function\", decl);\n return decl.parameters.map((p) => {\n if (!is.isIdentifier(p.name)) reader.fail(\"a destructured parameter\", p);\n const pname = p.name.text;\n if (p.dotDotDotToken) reader.fail(\"a rest parameter\", p);\n // `this: T` annotates the receiver and is erased; it is no argument the function is called with.\n if (pname === \"this\") reader.fail(\"a this parameter (the receiver is not modelled)\", p);\n if (p.questionToken) reader.fail(`optional parameter ${pname}`, p);\n if (p.initializer) reader.fail(`a default value for ${pname}`, p);\n return pname;\n });\n}\n\n/** `export function name(params): Type {` or `export const name = (params): Type => …` read, the types through the compiler. */\nfunction head(reader: ExprReader, types: SubsetTypes, checker: Checker, d: Declared): Head {\n const sf = reader.sf;\n const decl = d.node;\n const name = d.name.text;\n const pnames = shape(reader, decl);\n if (decl.typeParameters) reader.fail(\"type parameters\", decl.typeParameters[0] ?? decl);\n const params: Param[] = decl.parameters.map((p, i) => {\n const pname = pnames[i] as string;\n if (!p.type) reader.fail(`parameter ${pname} without a type`, p);\n return {\n name: pname,\n type: types.of(checker.getTypeAtLocation(p.type), reader.refuseAt(p.type)),\n };\n });\n if (!decl.type)\n reader.fail(\n `${name} without a return type (the subset needs it to name the record returned)`,\n decl,\n );\n const returns = types.of(checker.getTypeAtLocation(decl.type), reader.refuseAt(decl.type));\n if (!decl.body) reader.fail(\"a function without a body\", decl);\n const offset = openParen(sf, decl);\n if (offset === undefined) reader.fail(\"a function without a parameter list\", decl);\n return { name, decl, params, returns, line: lineAt(sf, d.statement), offset };\n}\n\n/** The function, its body read and typed against its header. */\nfunction declaration(reader: ExprReader, h: Head): SubsetFunction {\n const body = h.decl.body as NonNullable<FunctionNode[\"body\"]>;\n const scope = new Map(h.params.map((p) => [p.name, p.type]));\n // An arrow's expression body is its one return. Null checks narrow the names they guard in the\n // branches they guard, before anything is typed.\n const statements = is.isBlock(body)\n ? reader.block(body.statements, scope, body)\n : reader.expression(body, scope);\n const read = reader.narrowed(statements, scope, body);\n // Typing the whole body here: a record literal of no declared type, a field read on an integer or\n // a body of another type than declared are all outside the subset, found now rather than by an engine.\n const actual = reader.typeOfExpr(read, scope, body, h.returns);\n if (!fits(actual, h.returns, reader.ctx))\n reader.fail(\n `${h.name} returns a ${describe(actual)} but declares ${describe(h.returns)}`,\n body,\n );\n return {\n name: h.name,\n params: h.params,\n returns: h.returns,\n body: read,\n line: h.line,\n offset: h.offset,\n };\n}\n\n/** A file's top-level functions, and the ones whose name may run something else, with why. */\ninterface FileFunctions {\n readonly declarations: ReadonlyMap<string, Declared>;\n readonly overloaded: ReadonlySet<string>;\n readonly untrusted: ReadonlyMap<string, OutsideFunction>;\n /** What puts the whole file outside, functions and constants alike: eval, a built-in assigned to, or the compiler's checks turned off. */\n readonly tainted?: { readonly line: number; readonly message: string };\n}\n\n/**\n * A file's top-level functions: declarations, and the arrows module-level\n * consts hold. A binding that may be reassigned (let, var) or holds a\n * function expression is listed, for its callers' typing, and untrusted;\n * so is every function of a file mentioning eval directly or assigning to\n * a built-in, and a function the file assigns to.\n */\nfunction fileFunctions(\n sf: SourceFile,\n checker: Checker,\n standardGlobal: (id: Identifier) => boolean,\n): FileFunctions {\n const declarations = new Map<string, Declared>();\n const overloaded = new Set<string>();\n const untrusted = new Map<string, OutsideFunction>();\n const declare = (name: Identifier, node: FunctionNode, statement: Node): void => {\n if (declarations.has(name.text)) overloaded.add(name.text);\n else declarations.set(name.text, { name, node, statement });\n };\n for (const st of sf.statements) {\n if (is.isFunctionDeclaration(st)) {\n if (st.name) declare(st.name, st, st);\n continue;\n }\n if (!is.isVariableStatement(st)) continue;\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n let init: Expression = d.initializer;\n while (is.isParenthesizedExpression(init)) init = init.expression;\n if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;\n const name = d.name.text;\n declare(d.name, init, st);\n if (!isConst(st.declarationList))\n untrusted.set(name, {\n name,\n line: lineAt(sf, st),\n message: `${name} is declared with let or var, so what runs under its name may be another function`,\n });\n else if (is.isFunctionExpression(init))\n untrusted.set(name, {\n name,\n line: lineAt(sf, st),\n message: `${name} holds a function expression (write a function declaration or an arrow)`,\n });\n }\n }\n // A direct eval can rebind any declaration of the file without naming it, so any mention of `eval`\n // that is not a property of something else (`globalThis.eval` is indirect, and cannot) puts every\n // function outside: `eval(…)`, `(eval)(…)`, inside a template substitution alike. So does a\n // `@ts-nocheck` comment, which turns off the compiler's checks the reader relies on, and a direct\n // assignment to a built-in the subset reads as standard (`Math.floor = …`, `Array.prototype.map =\n // …`), wherever it is in the file: once it has run, the file's functions compute something else.\n // The engines state the assumption that nothing the reader does not see does this.\n const evalLine = directEval(sf);\n const noCheck = noCheckDirective(sf);\n const patched = rebound(sf, checker, standardGlobal);\n const tainted =\n evalLine !== undefined\n ? {\n line: evalLine,\n message: \"the module mentions eval directly, which can rebind any of its declarations\",\n }\n : noCheck !== undefined\n ? {\n line: noCheck,\n message:\n \"its file has a @ts-nocheck comment, which turns off the compiler's checks the reader relies on\",\n }\n : patched !== undefined\n ? {\n line: patched.line,\n message: `its file assigns to ${patched.target} (line ${patched.line}), so the built-ins its functions use may not be the standard ones`,\n }\n : undefined;\n if (tainted) for (const name of declarations.keys()) untrusted.set(name, { name, ...tainted });\n for (const [name, line] of assigned(sf, checker, declarations))\n if (!untrusted.has(name))\n untrusted.set(name, {\n name,\n line,\n message: `${name} is assigned in the module, so what runs under its name may not be its declaration`,\n });\n return { declarations, overloaded, untrusted, ...(tainted ? { tainted } : {}) };\n}\n\n/** What inlining a module's calls needs from the read it belongs to. */\ninterface InlinerContext {\n readonly checker: Checker;\n readonly types: SubsetTypes;\n readonly typeSource: TypeSource;\n readonly ctx: TypeContext;\n /** The module being read, and its functions. */\n readonly module: SourceFile;\n readonly own: FileFunctions;\n readonly parseError: (path: string) => { line: number; message: string } | undefined;\n readonly typeErrors: (path: string) => readonly CompilerError[];\n /** Whether an identifier names the global of its name (`Math`): the compiler resolves it to its standard library. */\n readonly standardGlobal: (id: Identifier) => boolean;\n}\n\n/**\n * Bind the type parameters in `declared` so that it is `expected`, or a\n * member of `expected` when that is a union: a parameter binds to what it\n * meets, and two instantiations of one alias match argument by argument.\n * Returns the type matched (the union member, say), or undefined, with\n * `bound` unchanged by a member that did not match.\n */\nfunction match(declared: Type, expected: Type, bound: Map<number, Type>): Type | undefined {\n if (declared.isTypeParameter()) {\n const had = bound.get(declared.id);\n if (had && had.id !== expected.id) return undefined;\n bound.set(declared.id, expected);\n return expected;\n }\n const alias = declared.getAliasSymbol();\n const other = expected.getAliasSymbol();\n if (alias && other && alias.id === other.id) {\n const xs = declared.getAliasTypeArguments();\n const ys = expected.getAliasTypeArguments();\n if (xs.length !== ys.length) return undefined;\n const trial = new Map(bound);\n for (let i = 0; i < xs.length; i++)\n if (!match(xs[i] as Type, ys[i] as Type, trial)) return undefined;\n for (const [k, v] of trial) bound.set(k, v);\n return expected;\n }\n if (expected.isUnionType())\n for (const member of expected.getTypes()) {\n const trial = new Map(bound);\n if (match(declared, member, trial)) {\n for (const [k, v] of trial) bound.set(k, v);\n return member;\n }\n }\n return undefined;\n}\n\n/**\n * Calls to functions the module cannot name as its own, read inlined: a\n * generic function (of the module or not) at the call's instantiation,\n * and a function of another file, as the compiler resolves the import.\n * The callee's body is read in its own file under the parameter types the\n * call's resolved signature gives, its literals typed by the resolved\n * return type, its names moved away from the caller's, and bound by `let`\n * to the arguments in order: a pure function called by value computes\n * exactly that. The callee's own calls inline the same way, so the\n * helpers of its file come with it. A callee with no body here (a\n * declaration file), one its file may rebind, or one reached again while\n * it is being inlined (recursion) is outside the subset, with why.\n */\nfunction inliner(c: InlinerContext): { inline: Inline; constant: Constant } {\n const files = new Map<SourceFile, FileFunctions>([[c.module, c.own]]);\n const functionsOf = (file: SourceFile): FileFunctions => {\n let found = files.get(file);\n if (!found) {\n found = fileFunctions(file, c.checker, c.standardGlobal);\n files.set(file, found);\n }\n return found;\n };\n // Whether a declaration's text compiles, once per declaration however often it is read.\n const vetted = new Map<Node, { message: string; line: number } | undefined>();\n const vet = (\n file: SourceFile,\n key: Node,\n range: DeclaredRange,\n ): { message: string; line: number } | undefined => {\n if (!vetted.has(key)) vetted.set(key, notCompiled(file, c.typeErrors, range));\n return vetted.get(key);\n };\n const inlining: string[] = [];\n // The type parameters of the functions being read, bound to the types their calls give them,\n // innermost last: a generic function read inside another sees the outer one's as concrete types.\n const substitutions: Map<number, Type>[] = [];\n const concrete = (t: Type): Type => {\n const top = substitutions[substitutions.length - 1];\n return top && t.isTypeParameter() ? (top.get(t.id) ?? t) : t;\n };\n // `fail` is annotated so that the compiler narrows after a call to it.\n const inline: Inline = (call, callee, scope, readArgs, fail: (what: string) => never) => {\n // A call the compiler rejects (a name imported with `import type`, which does not exist when the\n // code runs; arguments that do not fit) is no call the reader may stand in for.\n const caller = call.getSourceFile();\n const start = call.getStart(caller);\n if (c.typeErrors(caller.fileName).some((e) => e.pos < call.end && e.end > start))\n fail(`the compiler reports an error on this call to ${callee.text}`);\n let symbol = c.checker.getSymbolAtLocation(callee);\n if (!symbol) return undefined;\n if (symbol.flags & SymbolFlags.Alias) symbol = c.checker.getAliasedSymbol(symbol);\n const decl = symbol.valueDeclaration?.resolve();\n if (!decl || !(is.isFunctionDeclaration(decl) || is.isVariableDeclaration(decl)))\n return undefined;\n const file = decl.getSourceFile();\n // The declaration's own name: a default export's symbol is named `default`.\n const name = decl.name && is.isIdentifier(decl.name) ? decl.name.text : symbol.name;\n const where = file === c.module ? name : `${name} (from ${file.fileName})`;\n if (file.isDeclarationFile)\n fail(`${where} has no body to read: it is declared in a declaration file`);\n const fns = functionsOf(file);\n const d = fns.declarations.get(name);\n // Only a top-level function of its file is read; anything else is refused by the usual message.\n if (!d || !decl.name || d.name.pos !== decl.name.pos) return undefined;\n if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);\n const untrusted = fns.untrusted.get(name);\n if (untrusted) fail(`${where} is outside the subset: ${untrusted.message}`);\n if (fns.overloaded.has(name)) fail(`${where} is declared more than once (overloads)`);\n const body = d.node.body;\n if (!body) fail(`${where} has no body to read`);\n // A callee the compiler reports an error in computes something its text does not say.\n const bad = vet(file, d.node, rangeOf(d));\n if (bad)\n fail(\n `${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? \"\" : \" of its file\"})`,\n );\n const signature = c.checker.getResolvedSignature(call);\n if (c.checker.isUnknownSignature(signature)) fail(`the call to ${where} does not resolve`);\n const fileNames: Names = {\n callable: () => false,\n target: (n) => n,\n declared: (n) => fns.declarations.has(n),\n spec: false,\n global: c.standardGlobal,\n };\n const typeSource: TypeSource = {\n annotation: (node, refuse) => c.types.of(concrete(c.checker.getTypeAtLocation(node)), refuse),\n contextual: c.typeSource.contextual,\n };\n const reader = new ExprReader(file, fileNames, typeSource, c.ctx, undefined, inline, constant);\n const params = shape(reader, d.node);\n const symbols = signature.getParameters();\n if (symbols.length !== params.length || call.arguments.length !== params.length)\n fail(`${where} takes ${params.length} argument(s), called with ${call.arguments.length}`);\n // A generic callee is instantiated by where its value goes first: the compiler infers `E` in\n // `err({ type: \"locked\" })` from the argument alone, a record of its own, where the caller's\n // declared result names the error union the literal belongs to. What the context leaves open\n // is the compiler's instantiation.\n const bound = new Map<number, Type>();\n const declared = c.checker.getSignatureFromDeclaration(d.node);\n const generalReturn = c.checker.getReturnTypeOfSignature(declared);\n const context = d.node.typeParameters ? c.checker.getContextualType(call) : undefined;\n const matched = context ? match(generalReturn, concrete(context), bound) : undefined;\n const declaredParams = declared.getParameters();\n const generalParams = symbols.map((_, i) => {\n const own = declaredParams[i];\n return own ? c.checker.getTypeOfSymbol(own) : undefined;\n });\n const resolvedParams = symbols.map((p) => concrete(c.checker.getTypeOfSymbol(p)));\n const resolvedReturn = concrete(c.checker.getReturnTypeOfSignature(signature));\n // The callee's own type parameters, for its body: the context's first, the compiler's after.\n generalParams.forEach((g, i) => {\n if (g) match(g, resolvedParams[i] as Type, bound);\n });\n match(generalReturn, resolvedReturn, bound);\n const types = symbols.map((_, i) => {\n const g = generalParams[i];\n const type =\n g?.isTypeParameter() && bound.has(g.id)\n ? concrete(bound.get(g.id) as Type)\n : (resolvedParams[i] as Type);\n return c.types.of(type, (what) =>\n fail(`${where}, parameter ${params[i]} at this call: ${what}`),\n );\n });\n const returns = c.types.of(matched ?? resolvedReturn, (what) =>\n fail(`${where} returns, at this call, ${what}`),\n );\n const own = new Map([...bound].map(([k, v]) => [k, concrete(v)]));\n // The arguments in the caller's scope, before this callee is marked as being read: a nested call\n // to the same function is no recursion.\n const args = readArgs(types);\n const key = `${file.fileName}#${name}`;\n if (inlining.includes(key))\n fail(\n `${where} is recursive, which a function read at its calls cannot be (recursion is in the subset only as a module's own structural recursion)`,\n );\n inlining.push(key);\n substitutions.push(own);\n try {\n const inner = new Map(params.map((p, i) => [p, types[i] as SubsetType]));\n const readBody = (): Expr => {\n const read = returning(\n is.isBlock(body)\n ? reader.block(body.statements, inner, body)\n : reader.expression(body, inner),\n returns,\n );\n const actual = reader.typeOfExpr(reader.narrowed(read, inner, body), inner, body, returns);\n if (!fits(actual, returns, c.ctx))\n reader.fail(\n `returns a ${describe(actual)}, not the ${describe(returns)} called for`,\n body,\n );\n return read;\n };\n let read: Expr;\n try {\n read = readBody();\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n fail(\n `${where}, read at this call, is outside the subset: ${err.message} (line ${err.line} of its file)`,\n );\n }\n // Its parameters and its own names move away from every name the caller has here.\n const callerNames = new Set([...scope.keys(), ...args.flatMap((a) => [...boundNames(a)])]);\n // Every parameter name is reserved, used or not, so no fresh name repeats one.\n const taken = new Set([...callerNames, ...boundNames(read), ...params]);\n const renames = new Map<string, string>();\n for (const p of params) {\n const to = callerNames.has(p) ? fresh(p, taken) : p;\n taken.add(to);\n renames.set(p, to);\n }\n const renamed = renameVars(read, renames, taken, callerNames);\n return params.reduceRight<Expr>(\n (rest, p, i) => ({\n kind: \"let\",\n name: renames.get(p) as string,\n value: args[i] as Expr,\n body: rest,\n type: types[i] as SubsetType,\n }),\n renamed,\n );\n } finally {\n substitutions.pop();\n inlining.pop();\n }\n };\n // The constants being read, innermost last: one that reaches itself is refused.\n const reading: string[] = [];\n const constant: Constant = (name, fail: (what: string) => never) => {\n let symbol = c.checker.getSymbolAtLocation(name);\n if (!symbol) return undefined;\n const imported = (symbol.flags & SymbolFlags.Alias) !== 0;\n if (imported) symbol = c.checker.getAliasedSymbol(symbol);\n const decl = symbol.valueDeclaration?.resolve();\n if (!decl || !is.isVariableDeclaration(decl) || !is.isIdentifier(decl.name)) return undefined;\n const list = decl.parent;\n const statement = list.parent;\n const file = decl.getSourceFile();\n // A module-level `const` only: a `let` or `var` may be rebound, a local is not this name.\n if (!is.isVariableDeclarationList(list) || !is.isVariableStatement(statement)) return undefined;\n // A local the compiler resolves the name to, which the reader has not bound, is declared later in\n // its block: a const there throws when used before its line, a var reads undefined.\n if (statement.parent !== file)\n fail(`${name.text}, which is declared after this use in its block`);\n const where = file === c.module ? decl.name.text : `${decl.name.text} (from ${file.fileName})`;\n // A global (Math, say) is declared in the compiler's own declaration files: no constant here.\n if (file.isDeclarationFile && !imported) return undefined;\n if (file.isDeclarationFile)\n fail(`${where} has no value to read: it is declared in a declaration file`);\n if (!isConst(list)) fail(`${where} is a module-level let or var, which may be rebound`);\n // A name the compiler rejects here (used before its declaration, say) is not read.\n const at = name.getSourceFile();\n const start = name.getStart(at);\n if (c.typeErrors(at.fileName).some((e) => e.pos < name.end && e.end > start))\n fail(`the compiler reports an error on ${name.text} here`);\n if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);\n const init = decl.initializer;\n if (!init) fail(`${where} has no initializer`);\n if (is.isArrowFunction(init) || is.isFunctionExpression(init)) return undefined;\n // The declaration as a whole: a declared type the value does not fit is reported on the name.\n const bad = vet(file, decl, {\n start: decl.pos,\n end: decl.end,\n lead: { start: statement.pos, end: statement.getStart(file) },\n });\n if (bad)\n fail(\n `${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? \"\" : \" of its file\"})`,\n );\n const key = `${file.fileName}#${decl.name.text}`;\n if (reading.includes(key)) fail(`${where} is defined in terms of itself`);\n const fns = functionsOf(file);\n // A constant of a file that may rebind a built-in, or whose checks are off, is no value to trust.\n if (fns.tainted) fail(`${where} is outside the subset: ${fns.tainted.message}`);\n const fileNames: Names = {\n callable: () => false,\n target: (n) => n,\n declared: (n) => fns.declarations.has(n),\n spec: false,\n global: c.standardGlobal,\n };\n const reader = new ExprReader(\n file,\n fileNames,\n c.typeSource,\n c.ctx,\n undefined,\n undefined,\n constant,\n );\n reading.push(key);\n try {\n const value = reader.expression(init, new Map());\n if (!isValue(value))\n reader.fail(\n `${decl.name.text} holds something other than a number, boolean or string built from literals, operators and other such constants`,\n init,\n );\n return value;\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n fail(\n `${where}, read where it is used, is outside the subset: ${err.message} (line ${err.line} of its file)`,\n );\n } finally {\n reading.pop();\n }\n };\n return { inline, constant };\n}\n\n/**\n * Whether an expression is a value a constant may hold: literals of the\n * primitive types and the operators on them, with no name, call or record.\n */\nfunction isValue(e: Expr): boolean {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n return true;\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return isValue(e.operand);\n case \"binary\":\n return isValue(e.left) && isValue(e.right);\n case \"cond\":\n return isValue(e.test) && isValue(e.ifTrue) && isValue(e.ifFalse);\n default:\n return false;\n }\n}\n\n/**\n * The expression with the record literals it returns typed `t`, where\n * they have no type of their own: a function inlined at a call returns\n * its instantiated type, which a literal in a generic body cannot name.\n */\nfunction returning(e: Expr, t: SubsetType): Expr {\n const target = t.kind === \"nullable\" ? t.inner : t;\n if (target.kind !== \"record\" && target.kind !== \"union\") return e;\n switch (e.kind) {\n case \"record\":\n return e.type ? e : { ...e, type: target };\n case \"let\":\n case \"narrow\":\n case \"narrowTag\":\n return { ...e, body: returning(e.body, t) };\n case \"cond\":\n return { ...e, ifTrue: returning(e.ifTrue, t), ifFalse: returning(e.ifFalse, t) };\n default:\n return e;\n }\n}\n\n/**\n * Read a module: every function the subset takes (in source order, so\n * callees come before callers), the record types and unions they use,\n * and, for the other functions, why not. A function calling one outside\n * the subset is outside it too. The names given are what the caller\n * cares about; one the module does not declare at its top level is\n * reported among the others, not thrown.\n */\nexport function readSubset(\n source: string,\n functions?: readonly string[],\n options: ReadSubsetOptions = {},\n): SubsetModule {\n const path = options.path ?? virtualModulePath;\n return withProgram(\n [{ path, text: source }, ...(options.files ?? [])],\n ({ checker, file, parseError, typeErrors, standardGlobal }) => {\n const sf = file(path);\n // Pass 1: the module's top-level functions, and what makes them untrustworthy. A generic one is\n // no function of the subset (no claim is stated over a type parameter); its callers read it inlined.\n const own = fileFunctions(sf, checker, standardGlobal);\n const { declarations, overloaded } = own;\n const declared = new Set(declarations.keys());\n const generic = new Set(\n [...declarations].filter(([, d]) => d.node.typeParameters).map(([name]) => name),\n );\n const outside = new Map<string, OutsideFunction>();\n const error = parseError(path);\n // Source the compiler cannot parse is source the reader cannot trust: every function is outside.\n if (error) {\n for (const name of new Set([...declared, ...(functions ?? [])]))\n outside.set(name, {\n name,\n line: 0,\n message: `the module could not be parsed: ${error.message} (line ${error.line})`,\n });\n return { records: [], unions: [], functions: [], outside: [...outside.values()] };\n }\n // A name asked for that is no module-level declaration (inside a namespace, say) is reported, not thrown.\n for (const name of functions ?? [])\n if (!declared.has(name))\n outside.set(name, {\n name,\n line: 0,\n message: `the module declares no function ${name} at its top level`,\n });\n for (const [name, why] of own.untrusted) if (!outside.has(name)) outside.set(name, why);\n // The module's own declared types first, in their order, so a record literal of no declared type\n // is matched against every record the module declares, and a record belongs to the union declared\n // first. A declared type the subset does not take is left out here; a function using it says why.\n const types = new SubsetTypes(checker);\n const skip = Symbol(\"outside\");\n for (const st of sf.statements) {\n if (!is.isInterfaceDeclaration(st) && !is.isTypeAliasDeclaration(st)) continue;\n if (st.typeParameters) continue; // a generic alias is read where it is instantiated\n const symbol = checker.getSymbolAtLocation(st.name);\n if (!symbol) continue;\n try {\n types.of(checker.getDeclaredTypeOfSymbol(symbol), () => {\n throw skip;\n });\n } catch (err) {\n if (err !== skip) throw err;\n }\n }\n // Pass 2: signatures, so every function's return type is known before any body is read.\n const { ctx, signatures } = moduleContext(types.records);\n const names: Names = {\n callable: (n) => declared.has(n) && !generic.has(n),\n target: (n) => n,\n declared: (n) => declared.has(n),\n spec: false,\n global: standardGlobal,\n };\n const typeSource: TypeSource = {\n annotation: (node, refuse) => types.of(checker.getTypeAtLocation(node), refuse),\n contextual: (node) => contextualType(checker, types, node),\n };\n const { inline, constant } = inliner({\n checker,\n types,\n typeSource,\n ctx,\n module: sf,\n own,\n parseError,\n typeErrors,\n standardGlobal,\n });\n const reader = new ExprReader(sf, names, typeSource, ctx, undefined, inline, constant);\n const heads: Head[] = [];\n for (const [name, decl] of declarations) {\n try {\n if (overloaded.has(name))\n reader.fail(`${name} is declared more than once (overloads)`, decl.statement);\n const h = head(reader, types, checker, decl);\n // Callers of an assigned function still type-check against its declaration; they are then outside with it.\n signatures.set(name, { params: h.params, returns: h.returns });\n if (!outside.has(name)) heads.push(h);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n if (!outside.has(name)) outside.set(name, { name, line: err.line, message: err.message });\n }\n }\n // Pass 3: bodies. Text the compiler rejects (a const used before its declaration, which\n // throws where the reader sees a value) may compute something other than what it says: a\n // function read fine is still outside, with the compiler's message, when it has such an error.\n const read = new Map<string, SubsetFunction>();\n for (const h of heads) {\n try {\n const fn = declaration(reader, h);\n const bad = notCompiled(sf, typeErrors, rangeOf(declarations.get(h.name) as Declared));\n if (bad) throw new OutsideSubset(bad.message, bad.line);\n read.set(h.name, fn);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n outside.set(h.name, { name: h.name, line: err.line, message: err.message });\n }\n }\n closeOverCallees(read, outside);\n // Recursion is in the subset as structural recursion on a list (`structuralOn`), a function calling\n // itself directly; any other recursion is outside, and so are its callers.\n const reaches = (from: string, target: string, seen = new Set<string>()): boolean => {\n const fn = read.get(from);\n if (!fn) return false;\n for (const c of callees(fn.body)) {\n if (c === target) return true;\n if (!seen.has(c)) {\n seen.add(c);\n if (reaches(c, target, seen)) return true;\n }\n }\n return false;\n };\n for (const [name, fn] of [...read])\n if (reaches(name, name)) {\n const direct = [...callees(fn.body)].every((c) => c === name || !reaches(c, name));\n const on = direct ? structuralOn(fn) : undefined;\n if (on !== undefined) {\n read.set(name, { ...fn, structural: on });\n continue;\n }\n read.delete(name);\n outside.set(name, {\n name,\n line: fn.line,\n message: `${name} is recursive in a way the subset does not take: it takes a function calling itself on a list parameter's slice(1), after a first test of that list's length against 0 (if (xs.length === 0) return …)`,\n });\n }\n closeOverCallees(read, outside);\n // Callees before callers, whatever the source order: Lean needs a definition before its use.\n const ordered: SubsetFunction[] = [];\n const placed = new Set<string>();\n while (ordered.length < read.size)\n // A structurally recursive function calls itself: that callee needs no placing first.\n for (const [name, fn] of read)\n if (\n !placed.has(name) &&\n [...callees(fn.body)].every((c) => c === name || placed.has(c))\n ) {\n ordered.push(fn);\n placed.add(name);\n }\n return {\n records: [...types.records.values()],\n unions: types.unions,\n functions: ordered,\n outside: [...outside.values()],\n };\n },\n );\n}\n\n/** A caller of a function outside the subset is outside it too, however many steps away. */\nfunction closeOverCallees(\n read: Map<string, SubsetFunction>,\n outside: Map<string, OutsideFunction>,\n): void {\n for (let changed = true; changed; ) {\n changed = false;\n for (const [name, fn] of read) {\n const bad = [...callees(fn.body)].find((c) => outside.has(c));\n if (bad === undefined) continue;\n read.delete(name);\n outside.set(name, {\n name,\n line: fn.line,\n message: `calls ${bad}, which is outside the subset: ${outside.get(bad)?.message}`,\n });\n changed = true;\n }\n }\n}\n\n/**\n * A reader over text that is not the module: with `aliases`, the text is\n * a spec file's, whose names for the module's functions are its own\n * imports and nothing else; without, the text sees the module's names.\n * No compiler stands behind the text, so a `const` annotation is read\n * from its syntax against the module's declared types, and a record\n * literal has no contextual type. Lines are not reported: the text's\n * position is the caller's to know.\n */\nfunction arrowReader(\n sf: SourceFile,\n module: SubsetModule,\n aliases?: ReadonlyMap<string, string>,\n): ExprReader {\n const records = new Map(module.records.map((rec) => [rec.name, rec]));\n const unionNames = new Set(module.unions.map((u) => u.name));\n const inSubset = new Set(module.functions.map((f) => f.name));\n let names: Names;\n if (aliases) {\n const declared = new Set(aliases.keys());\n const callable = new Set(\n [...aliases].filter(([, fn]) => inSubset.has(fn)).map(([local]) => local),\n );\n names = {\n callable: (n) => callable.has(n),\n target: (n) => aliases.get(n) ?? n,\n declared: (n) => declared.has(n),\n spec: true,\n global: () => true,\n };\n } else {\n const declared = new Set([...inSubset, ...module.outside.map((o) => o.name)]);\n names = {\n callable: (n) => inSubset.has(n),\n target: (n) => n,\n declared: (n) => declared.has(n),\n spec: false,\n global: () => true,\n };\n }\n const recordNames = new Set(records.keys());\n const typeSource: TypeSource = {\n annotation: (node, refuse) => syntacticType(sf, node, recordNames, unionNames, refuse),\n contextual: () => undefined,\n };\n const signatures = new Map<string, CalleeSignature>(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n );\n return new ExprReader(sf, names, typeSource, { records, signatures }, () => 0);\n}\n\n/** The one expression a fragment `(text)` parsed to, or why the text is not one expression. */\nfunction fragmentExpression(sf: SourceFile): Expression {\n const [first, second] = sf.statements;\n if (second) throw new OutsideSubset(`unexpected ${textOf(sf, second)} after the expression`, 0);\n if (!first || !is.isExpressionStatement(first) || !is.isParenthesizedExpression(first.expression))\n throw new OutsideSubset(\"could not be parsed as an expression\", 0);\n let broken: string | undefined;\n const visit = (node: Node): void => {\n if (broken !== undefined) return;\n if (is.isIdentifier(node) && node.text === \"\")\n broken = \"could not be parsed (something is missing)\";\n node.forEachChild(visit);\n };\n visit(first);\n if (broken !== undefined) throw new OutsideSubset(broken, 0);\n return first.expression.expression;\n}\n\n/**\n * One TypeScript expression (a claim's body, say) in a scope of typed\n * names, over a module already read. The whole text must be the\n * expression.\n */\nexport function readExpression(\n text: string,\n scope: ReadonlyMap<string, SubsetType>,\n module: SubsetModule,\n aliases?: ReadonlyMap<string, string>,\n): Expr {\n return withSourceFile(`(${text}\\n)`, (sf) => {\n const expr = fragmentExpression(sf);\n return arrowReader(sf, module, aliases).expression(expr, scope);\n });\n}\n\n/**\n * The body of a spec file's arrow (`when` or `ensures`) as a boolean\n * expression: an expression body as it is, a block body through the same\n * statement reader as a function body (`const`, `if`, early returns).\n * The scope maps the arrow's own parameter names to the binders' types;\n * `aliases` maps the spec file's local names to the module's functions,\n * and a free name that is neither is outside the subset: the spec file's\n * scope is its imports, never the module's. `Math` and `Number` are the\n * globals wherever the arrow's own scope does not bind them: `readSpecs`\n * has checked that every built-in a claim names resolves to the standard\n * library in the spec file.\n */\nexport function readArrowBody(\n arrow: Arrow,\n scope: ReadonlyMap<string, SubsetType>,\n module: SubsetModule,\n aliases: ReadonlyMap<string, string> = new Map(),\n): Expr {\n if (!arrow.block)\n return withSourceFile(`(${arrow.body}\\n)`, (sf) => {\n const expr = fragmentExpression(sf);\n const reader = arrowReader(sf, module, aliases);\n return reader.narrowed(reader.expression(expr, scope), scope, sf);\n });\n return withSourceFile(`{${arrow.body}\\n}`, (sf) => {\n const block = blockOf(sf);\n if (!block) throw new OutsideSubset(\"could not be parsed as a block\", 0);\n const reader = arrowReader(sf, module, aliases);\n return reader.narrowed(reader.block(block.statements, new Map(scope), block), scope, sf);\n });\n}\n\n/**\n * The list parameter a function recurses on structurally, or undefined:\n * its body is `if (p.length === 0) … else …` for a list parameter p, the\n * test and the first branch do not call it, and every call to it in the\n * other branch passes `p.slice(1)` for p. Lean takes such a definition as\n * a match on `[]` and `head :: tail`, recursing on the tail.\n */\nfunction structuralOn(fn: SubsetFunction): number | undefined {\n const body = fn.body;\n if (body.kind !== \"cond\") return undefined;\n const t = body.test;\n if (t.kind !== \"binary\" || t.op !== \"===\") return undefined;\n const sides = [t.left, t.right];\n const zero = sides.find((x) => x.kind === \"int\" && x.value === \"0\");\n const len = sides.find((x) => x !== zero);\n if (!zero || len?.kind !== \"field\" || len.field !== \"length\" || len.object.kind !== \"var\")\n return undefined;\n const list = len.object.name;\n const at = fn.params.findIndex((p) => p.name === list && p.type.kind === \"list\");\n if (at < 0) return undefined;\n if (callees(t).has(fn.name) || callees(body.ifTrue).has(fn.name)) return undefined;\n const calls = selfCalls(body.ifFalse, fn.name);\n const onTail = (a: Expr | undefined) =>\n a?.kind === \"tail\" && a.list.kind === \"var\" && a.list.name === list;\n return calls.length > 0 && calls.every((c) => onTail(c.args[at])) ? at : undefined;\n}\n\n/** Every call to `name` in an expression. */\nfunction selfCalls(e: Expr, name: string): Extract<Expr, { kind: \"call\" }>[] {\n const out: Extract<Expr, { kind: \"call\" }>[] = [];\n const walk = (x: Expr): void => {\n if (x.kind === \"call\" && x.callee === name) out.push(x);\n for (const child of children(x)) walk(child);\n };\n walk(e);\n return out;\n}\n\n/** An expression's direct subexpressions. */\nexport function children(e: Expr): Expr[] {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return [];\n case \"narrow\":\n case \"narrowTag\":\n return [e.body];\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return [e.operand];\n case \"binary\":\n return [e.left, e.right];\n case \"cond\":\n return [e.test, e.ifTrue, e.ifFalse];\n case \"call\":\n return [...e.args];\n case \"field\":\n return [e.object];\n case \"record\":\n return e.fields.map((f) => f.value);\n case \"let\":\n return [e.value, e.body];\n case \"list\":\n return [...e.items, ...(e.rest ? [e.rest] : [])];\n case \"tail\":\n return [e.list];\n case \"headOr\":\n return [e.list, e.fallback];\n case \"iterate\":\n return [e.list, e.body];\n case \"fold\":\n return [e.list, e.init, e.body];\n }\n}\n\n/** Whether an expression holds a node of the kinds named. */\nfunction hasNode(e: Expr, kinds: ReadonlySet<Expr[\"kind\"]>): boolean {\n if (kinds.has(e.kind)) return true;\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return false;\n case \"narrow\":\n case \"narrowTag\":\n return hasNode(e.body, kinds);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return hasNode(e.operand, kinds);\n case \"binary\":\n return hasNode(e.left, kinds) || hasNode(e.right, kinds);\n case \"cond\":\n return hasNode(e.test, kinds) || hasNode(e.ifTrue, kinds) || hasNode(e.ifFalse, kinds);\n case \"call\":\n return e.args.some((a) => hasNode(a, kinds));\n case \"field\":\n return hasNode(e.object, kinds);\n case \"record\":\n return e.fields.some((f) => hasNode(f.value, kinds));\n case \"let\":\n return hasNode(e.value, kinds) || hasNode(e.body, kinds);\n case \"list\":\n return e.items.some((x) => hasNode(x, kinds)) || (e.rest ? hasNode(e.rest, kinds) : false);\n case \"tail\":\n return hasNode(e.list, kinds);\n case \"headOr\":\n return hasNode(e.list, kinds) || hasNode(e.fallback, kinds);\n case \"iterate\":\n return hasNode(e.list, kinds) || hasNode(e.body, kinds);\n case \"fold\":\n return hasNode(e.list, kinds) || hasNode(e.init, kinds) || hasNode(e.body, kinds);\n }\n}\n\n/**\n * The module as an engine that takes only some of the subset's types sees\n * it: records with a field of a type it does not take are dropped, and so\n * are functions whose signature holds one, whose body uses what the\n * types bring (`null`, narrowing), or which call such a function; each is\n * reported outside with `reason`.\n */\nexport function restrictModule(\n module: SubsetModule,\n takes: (t: SubsetType) => boolean,\n reason: string,\n /** Expression kinds a function's body may not hold here: by default what nullable types and unions bring. */\n bodies: ReadonlySet<Expr[\"kind\"]> = new Set([\"null\", \"narrow\", \"narrowTag\"]),\n /** A body the engine refuses for what it computes, not its kinds or types (a division, say). */\n refused?: (body: Expr) => boolean,\n): SubsetModule {\n // A record with a field the engine does not take is out, and so is a union with such a member, and\n // so, in turn, is a record with a field of that union: to a fixed point.\n const badRecords = new Set<string>();\n for (const u of module.unions)\n if (!takes({ kind: \"union\", name: u.name })) badRecords.add(`union:${u.name}`);\n for (let changed = true; changed; ) {\n changed = false;\n for (const rec of module.records)\n if (\n !badRecords.has(rec.name) &&\n rec.fields.some((f) => !typeTaken(f.type, takes, badRecords))\n ) {\n badRecords.add(rec.name);\n changed = true;\n }\n for (const u of module.unions) {\n if (!badRecords.has(`union:${u.name}`) && u.members.some((m) => badRecords.has(m.record))) {\n badRecords.add(`union:${u.name}`);\n changed = true;\n }\n // A member of a dropped union stays a record of its own: every record has its own sort, so a\n // member of several unions does not go with one of them.\n }\n }\n const outside = new Map(module.outside.map((o) => [o.name, o]));\n const kept = new Map(module.functions.map((f) => [f.name, f]));\n const uses = (f: SubsetFunction) =>\n !f.params.every((p) => typeTaken(p.type, takes, badRecords)) ||\n !typeTaken(f.returns, takes, badRecords) ||\n annotations(f.body).some((t) => !typeTaken(t, takes, badRecords)) ||\n hasNode(f.body, bodies) ||\n refused?.(f.body) === true;\n for (const f of module.functions)\n if (uses(f)) {\n kept.delete(f.name);\n outside.set(f.name, { name: f.name, line: f.line, message: reason });\n }\n for (let changed = true; changed; ) {\n changed = false;\n for (const [name, f] of kept) {\n const bad = [...callees(f.body)].find((c) => outside.has(c));\n if (bad === undefined) continue;\n kept.delete(name);\n outside.set(name, {\n name,\n line: f.line,\n message: `calls ${bad}, which is outside the engine's subset: ${outside.get(bad)?.message}`,\n });\n changed = true;\n }\n }\n return {\n // A kept record names only the unions kept with it.\n records: module.records\n .filter((r) => !badRecords.has(r.name))\n .map((r) => {\n const unions = r.unions?.filter((u) => !badRecords.has(`union:${u}`));\n if (unions === r.unions) return r;\n const { unions: _, ...rest } = r;\n return unions && unions.length > 0 ? { ...rest, unions } : rest;\n }),\n unions: module.unions.filter((u) => !badRecords.has(`union:${u.name}`)),\n functions: module.functions.filter((f) => kept.has(f.name)),\n outside: [...outside.values()],\n };\n}\n\nfunction typeTaken(\n t: SubsetType,\n takes: (t: SubsetType) => boolean,\n badRecords: ReadonlySet<string>,\n): boolean {\n if (!takes(t)) return false;\n if (t.kind === \"record\") return !badRecords.has(t.name);\n if (t.kind === \"union\") return !badRecords.has(`union:${t.name}`);\n if (t.kind === \"nullable\") return typeTaken(t.inner, takes, badRecords);\n if (t.kind === \"list\") return typeTaken(t.element, takes, badRecords);\n return true;\n}\n\n/** The types a body's `const` annotations and its record literals' contexts name. */\nfunction annotations(e: Expr, out: SubsetType[] = []): SubsetType[] {\n if ((e.kind === \"let\" || e.kind === \"record\") && e.type) out.push(e.type);\n for (const c of children(e)) annotations(c, out);\n return out;\n}\n\n/** An expression only lists bring. */\nexport type ListExpr = Extract<Expr, { kind: \"list\" | \"tail\" | \"headOr\" | \"iterate\" | \"fold\" }>;\n\n/** The expression kinds only lists bring, for an engine that does not take them. */\nexport const listKinds: ReadonlySet<Expr[\"kind\"]> = new Set<ListExpr[\"kind\"]>([\n \"list\",\n \"tail\",\n \"headOr\",\n \"iterate\",\n \"fold\",\n]);\n\n/** Whether an expression is one only lists bring (a type guard over `listKinds`). */\nexport const isListExpr = (e: Expr): e is ListExpr => listKinds.has(e.kind);\n","/**\n * A module and its spec file read into `ModuleSpecs` through the\n * compiler. From the module: the exported functions and their parameter\n * types (`function` declarations and `const` arrows alike), the types as\n * the compiler resolves them. From the spec file: every\n * `export const name = forall(f, { sample, when, ensures })` and\n * `total(f)`, with the combinators imported from `eutaxy/spec` and `f`\n * imported from the module beside the spec file (the import resolved by\n * the compiler); the arrows are kept as text, their parameter names\n * naming the binders, and the precondition's conjuncts about one\n * parameter become that binder's hint. Anything else is an error with a\n * line, never a guess.\n */\n\nimport type {\n Arrow,\n Binder,\n Endpoint,\n FunctionSpec,\n Hint,\n ModuleSpecs,\n Param,\n Property,\n SpecError,\n SpecType,\n} from \"@eutaxy/spec\";\nimport {\n type ArrowFunction,\n type Expression,\n type FunctionLikeBase,\n type ImportDeclaration,\n type Node,\n type SourceFile,\n SyntaxKind,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport type { Checker, Program } from \"typescript/sync\";\nimport { endpointBigInt, endpointNumber } from \"../generate.ts\";\nimport {\n isAsync,\n isConst,\n isExported,\n lineAt,\n type Opened,\n openParen,\n textOf,\n withProgram,\n withSourceFile,\n} from \"./compiler.ts\";\nimport { rebound } from \"./subset.ts\";\nimport { specTypeOf, unionOf } from \"./types.ts\";\n\nexport interface ReadSpecsInput {\n /** The module's source. */\n readonly module: string;\n /** The spec file's source. */\n readonly spec: string;\n /**\n * The module's path, under which its imports resolve; the spec file\n * is beside it unless `specPath` says otherwise. For a module given\n * by text alone, any absolute path the spec file's import of the\n * module resolves to (`/x/domain.ts` for `import … from \"./domain.ts\"`).\n */\n readonly modulePath: string;\n /** The spec file's path; `<module>.props.ts` by default. */\n readonly specPath?: string;\n /** Specifiers the combinators come from; `eutaxy/spec` and the workspace name by default. */\n readonly specSpecifiers?: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// The module: exported functions and their parameter types.\n\ninterface Declaration {\n readonly name: string;\n readonly params: readonly Param[];\n readonly line: number;\n readonly offset: number;\n}\n\ninterface ModuleSide {\n readonly declarations: ReadonlyMap<string, Declaration>;\n /** Exported name to local declaration name. */\n readonly exports: ReadonlyMap<string, string>;\n readonly errors: readonly SpecError[];\n}\n\n/** The parameters of a function-like declaration: `name?: T = default`, `...rest`, destructured. */\nfunction readParams(checker: Checker, fn: FunctionLikeBase): Param[] {\n const params: Param[] = [];\n for (const p of fn.parameters) {\n const name = is.isIdentifier(p.name) ? p.name.text : null;\n if (name === \"this\") continue; // a receiver annotation, no argument\n if (p.dotDotDotToken) {\n params.push({ name: null, type: { kind: \"unknown\", text: `...${name ?? \"\"}` } });\n continue;\n }\n let type: SpecType;\n if (p.type) type = specTypeOf(checker, checker.getTypeAtLocation(p.type));\n else if (p.initializer) type = specTypeOf(checker, checker.getTypeAtLocation(p));\n else type = { kind: \"unknown\", text: \"(no type annotation)\" };\n // An optional parameter, or one with a default, may be passed undefined.\n if (p.questionToken || p.initializer) type = unionOf([type, { kind: \"undefined\" }]);\n params.push({ name, type });\n }\n return params;\n}\n\nfunction readModuleSide(sf: SourceFile, checker: Checker): ModuleSide {\n const errors: SpecError[] = [];\n const declarations = new Map<string, Declaration>();\n const exports = new Map<string, string>();\n const declare = (name: string, fn: FunctionLikeBase, at: Node): void => {\n const offset = openParen(sf, fn);\n if (offset === undefined) return; // an arrow without parentheses: no parameter list to point at\n if (declarations.has(name)) {\n errors.push({\n line: lineAt(sf, at),\n message: `${name} is declared more than once (overloads): a spec is checked against one signature`,\n inModule: true,\n });\n return;\n }\n declarations.set(name, { name, params: readParams(checker, fn), line: lineAt(sf, at), offset });\n };\n for (const st of sf.statements) {\n if (is.isFunctionDeclaration(st)) {\n if (!st.name) continue;\n declare(st.name.text, st, st);\n if (isExported(st)) exports.set(st.name.text, st.name.text);\n continue;\n }\n if (is.isVariableStatement(st)) {\n // `export const f = (a: T): R => …` or `= function (a: T) …`: a function by another declaration.\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n let init: Expression = d.initializer;\n while (is.isParenthesizedExpression(init)) init = init.expression;\n if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;\n declare(d.name.text, init, st);\n if (isExported(st)) exports.set(d.name.text, d.name.text);\n }\n continue;\n }\n // `export { a, b as c }`; with `from`, a re-export of another module's names (not this module's).\n if (is.isExportDeclaration(st) && !st.moduleSpecifier && !st.isTypeOnly && st.exportClause) {\n if (!is.isNamedExports(st.exportClause)) continue;\n for (const e of st.exportClause.elements) {\n if (e.isTypeOnly) continue;\n const local = e.propertyName ?? e.name;\n if (is.isIdentifier(local) && is.isIdentifier(e.name)) exports.set(e.name.text, local.text);\n }\n }\n }\n return { declarations, exports, errors };\n}\n\n// ---------------------------------------------------------------------------\n// The spec file.\n\ninterface Imported {\n readonly from: string;\n /** The exported name imported; `*` for a namespace import. */\n readonly name: string;\n readonly declaration: ImportDeclaration;\n}\n\n/** `import { a, b as c } from \"x\"`, `import * as ns from \"x\"`, `import d from \"x\"`; type-only imports skipped. */\nfunction imports(sf: SourceFile): Map<string, Imported> {\n const out = new Map<string, Imported>();\n for (const st of sf.statements) {\n if (!is.isImportDeclaration(st) || !st.importClause) continue;\n const clause = st.importClause;\n if (clause.phaseModifier === SyntaxKind.TypeKeyword) continue;\n if (!is.isStringLiteral(st.moduleSpecifier)) continue;\n const from = st.moduleSpecifier.text;\n if (clause.name) out.set(clause.name.text, { from, name: \"default\", declaration: st });\n const bindings = clause.namedBindings;\n if (!bindings) continue;\n if (is.isNamespaceImport(bindings))\n out.set(bindings.name.text, { from, name: \"*\", declaration: st });\n else\n for (const e of bindings.elements) {\n if (e.isTypeOnly) continue;\n const imported = e.propertyName ?? e.name;\n const name = is.isIdentifier(imported) ? imported.text : imported.text;\n out.set(e.name.text, { from, name, declaration: st });\n }\n }\n return out;\n}\n\n/** `1`, `-1`, `1_000`, `1.5`, `10n` as an endpoint value; undefined otherwise. */\nfunction numberText(sf: SourceFile, node: Expression): string | undefined {\n if (is.isNumericLiteral(node) || is.isBigIntLiteral(node))\n return textOf(sf, node).replace(/_/g, \"\");\n if (\n is.isPrefixUnaryExpression(node) &&\n node.operator === SyntaxKind.MinusToken &&\n (is.isNumericLiteral(node.operand) || is.isBigIntLiteral(node.operand))\n )\n return `-${textOf(sf, node.operand).replace(/_/g, \"\")}`;\n return undefined;\n}\n\n/** The top-level conjuncts of an expression, parentheses stripped. */\nfunction conjuncts(node: Expression, out: Expression[] = []): Expression[] {\n let e = node;\n while (is.isParenthesizedExpression(e)) e = e.expression;\n if (is.isBinaryExpression(e) && e.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {\n conjuncts(e.left, out);\n conjuncts(e.right, out);\n } else out.push(e);\n return out;\n}\n\nconst comparisons: Partial<Record<SyntaxKind, string>> = {\n [SyntaxKind.LessThanToken]: \"<\",\n [SyntaxKind.LessThanEqualsToken]: \"<=\",\n [SyntaxKind.GreaterThanToken]: \">\",\n [SyntaxKind.GreaterThanEqualsToken]: \">=\",\n};\n\n/**\n * What an expression says about each of the named parameters on its own:\n * its top-level conjuncts of the forms `Number.isInteger(x)`, `x < n`,\n * `n <= x` (and the other comparisons) and `/re/.test(x)`, by parameter\n * index.\n */\nfunction hintsIn(\n sf: SourceFile,\n body: Expression,\n params: readonly (string | null)[],\n): Map<number, Hint> {\n const out = new Map<number, Hint>();\n const position = new Map<string, number>();\n params.forEach((p, i) => {\n if (p !== null) position.set(p, i);\n });\n const merge = (i: number, h: Hint) => {\n const old = out.get(i) ?? {};\n out.set(i, { ...old, ...h });\n };\n for (const conjunct of conjuncts(body)) {\n if (is.isCallExpression(conjunct)) {\n const callee = conjunct.expression;\n const [arg, extra] = conjunct.arguments;\n if (!is.isPropertyAccessExpression(callee) || !is.isIdentifier(callee.name) || !arg || extra)\n continue;\n if (!is.isIdentifier(arg)) continue;\n const at = position.get(arg.text);\n if (at === undefined) continue;\n // Number.isInteger(x)\n if (\n is.isIdentifier(callee.expression) &&\n callee.expression.text === \"Number\" &&\n callee.name.text === \"isInteger\"\n )\n merge(at, { integer: true });\n // /re/.test(x)\n else if (is.isRegularExpressionLiteral(callee.expression) && callee.name.text === \"test\") {\n const m = /^\\/([\\s\\S]*)\\/([a-z]*)$/.exec(textOf(sf, callee.expression));\n if (m) merge(at, { regex: { pattern: m[1] as string, flags: m[2] as string } });\n }\n continue;\n }\n // x op n, n op x\n if (!is.isBinaryExpression(conjunct)) continue;\n const op = comparisons[conjunct.operatorToken.kind];\n if (op === undefined) continue;\n const bound = (variable: Expression, literal: Expression, variableOnLeft: boolean) => {\n if (!is.isIdentifier(variable)) return;\n const value = numberText(sf, literal);\n if (value === undefined) return;\n const at = position.get(variable.text);\n if (at === undefined) return;\n // `x < n` bounds x above; `n < x` bounds it below.\n const above = variableOnLeft ? op.startsWith(\"<\") : op.startsWith(\">\");\n const endpoint: Endpoint = { value, inclusive: op.endsWith(\"=\") };\n merge(at, above ? { upper: endpoint } : { lower: endpoint });\n };\n if (is.isIdentifier(conjunct.left)) bound(conjunct.left, conjunct.right, true);\n else if (is.isIdentifier(conjunct.right)) bound(conjunct.right, conjunct.left, false);\n }\n return out;\n}\n\n/**\n * What the precondition says about each of its parameters on its own,\n * read from the arrow's text: see `hintsIn`. A block body gives none.\n */\nexport function hintsOf(arrow: Arrow): Map<number, Hint> {\n if (arrow.block) return new Map();\n return withSourceFile(`(${arrow.body}\\n)`, (sf) => {\n const [first, second] = sf.statements;\n if (second || !first || !is.isExpressionStatement(first)) return new Map();\n let e = first.expression;\n while (is.isParenthesizedExpression(e)) e = e.expression;\n return hintsIn(sf, e, arrow.params);\n });\n}\n\ninterface SpecExport {\n readonly name: string;\n readonly kind: \"forall\" | \"total\";\n readonly fn: string;\n readonly sample?: Arrow;\n readonly when?: Arrow;\n readonly ensures?: Arrow;\n readonly text: string;\n readonly line: number;\n /** The hints the sample and the precondition give, combined per binder index. */\n readonly hints: ReadonlyMap<number, Hint>;\n}\n\nclass SpecFail extends Error {\n readonly line: number;\n constructor(message: string, line: number) {\n super(message);\n this.line = line;\n }\n}\n\n/** The module's exports the spec file imports by name, as `local` to exported `name`. */\ninterface ModuleImport {\n readonly local: string;\n readonly name: string;\n}\n\n/** Read the spec file's exports. */\nfunction readSpecSide(\n sf: SourceFile,\n { program, checker, standardGlobal }: Opened,\n modulePath: string,\n moduleKey: string,\n specSpecifiers: ReadonlySet<string>,\n): { specs: SpecExport[]; errors: SpecError[]; imports: ModuleImport[] } {\n const errors: SpecError[] = [];\n const bound = imports(sf);\n const specs: SpecExport[] = [];\n function fail(message: string, at: Node): never {\n throw new SpecFail(message, lineAt(sf, at));\n }\n // Whether an import's specifier resolves to the module beside the spec file.\n const resolvesToModule = new Map<string, boolean>();\n const fromModule = (imp: Imported): boolean => {\n const known = resolvesToModule.get(imp.from);\n if (known !== undefined) return known;\n const resolved = program.getResolvedModuleFromModuleSpecifier(\n imp.declaration.moduleSpecifier as Parameters<\n Program[\"getResolvedModuleFromModuleSpecifier\"]\n >[0],\n sf.fileName,\n );\n const target = resolved ? program.getSourceFile(resolved.resolvedFileName) : undefined;\n const is = target !== undefined && target.path === moduleKey;\n resolvesToModule.set(imp.from, is);\n return is;\n };\n /** The combinator a callee names (`forall`, `ns.forall`), or undefined. */\n const combinator = (callee: Expression): \"forall\" | \"total\" | undefined => {\n if (is.isPropertyAccessExpression(callee)) {\n if (!is.isIdentifier(callee.expression) || !is.isIdentifier(callee.name)) return undefined;\n const ns = bound.get(callee.expression.text);\n const member = callee.name.text;\n if (\n ns?.name === \"*\" &&\n specSpecifiers.has(ns.from) &&\n (member === \"forall\" || member === \"total\")\n )\n return member;\n return undefined;\n }\n if (!is.isIdentifier(callee)) return undefined;\n const imp = bound.get(callee.text);\n if (imp && specSpecifiers.has(imp.from) && (imp.name === \"forall\" || imp.name === \"total\"))\n return imp.name;\n return undefined;\n };\n /** The module function a first argument names, or why not. */\n const functionArg = (arg: Expression | undefined, call: Node): string => {\n if (!arg)\n return fail(\"the first argument must name a function of the module, found the end\", call);\n if (\n is.isPropertyAccessExpression(arg) &&\n is.isIdentifier(arg.expression) &&\n is.isIdentifier(arg.name)\n ) {\n const ns = bound.get(arg.expression.text);\n if (ns?.name === \"*\" && fromModule(ns)) return arg.name.text;\n return fail(`${textOf(sf, arg)} is not a function imported from the module`, arg);\n }\n if (!is.isIdentifier(arg))\n return fail(\n `the first argument must name a function of the module, found ${textOf(sf, arg)}`,\n arg,\n );\n const imp = bound.get(arg.text);\n if (!imp)\n return fail(\n `${arg.text} is not imported from the module (import it from ./${modulePath.split(\"/\").pop()})`,\n arg,\n );\n if (!fromModule(imp))\n return fail(\n `${arg.text} is imported from ${JSON.stringify(imp.from)}, not from the module beside this spec file`,\n arg,\n );\n if (imp.name === \"*\" || imp.name === \"default\")\n return fail(`${arg.text} must be a named import of the module's function`, arg);\n return imp.name;\n };\n /**\n * A claim is read from its arrow's text alone, where `Math` and `Number`\n * are the globals unless the arrow binds them itself: an arrow naming\n * one that resolves to anything else here (a binding of the spec file,\n * an import, a const of the arrow's own block declared after the use)\n * is refused, so a claim is never read as something it does not\n * compute. A parameter or const of the arrow bound before the use is\n * the arrow reader's own name for it (a parameter named `Math` reads as\n * that parameter), and a binding the claims do not name, or a type-only\n * import, is fine.\n */\n const builtins = (arrow: ArrowFunction, node: Node, what: string): void => {\n if (\n is.isPropertyAccessExpression(node) &&\n is.isIdentifier(node.expression) &&\n (node.expression.text === \"Math\" || node.expression.text === \"Number\") &&\n !standardGlobal(node.expression)\n ) {\n const id = node.expression;\n const bound = checker.getSymbolAtLocation(id)?.declarations[0]?.resolve();\n const own =\n bound !== undefined &&\n bound.getSourceFile() === sf &&\n bound.pos >= arrow.pos &&\n bound.end <= arrow.end &&\n bound.getStart(sf) < id.getStart(sf);\n if (!own) {\n const file = bound?.getSourceFile();\n const where =\n bound && file\n ? ` (bound at line ${lineAt(file, bound)}${file === sf ? \"\" : ` of ${file.fileName}`})`\n : \"\";\n fail(\n `${what} names ${id.text}, which is not the global ${id.text} here${where}; rename the binding`,\n id,\n );\n }\n }\n node.forEachChild((child) => builtins(arrow, child, what));\n };\n /** An arrow function: its params, body text and whether the body is a block. */\n const arrow = (node: Expression, what: string): { arrow: Arrow; node: ArrowFunction } => {\n if (!is.isArrowFunction(node))\n return fail(\n `${what} must be an arrow function, found ${textOf(sf, node).split(/\\s/)[0] ?? \"\"}`,\n node,\n );\n if (isAsync(node)) fail(`${what} is an async arrow; it must be synchronous`, node);\n builtins(node, node.body, what);\n // A rest or destructured parameter has no name of its own: the binder keeps the function's.\n const params = node.parameters.map((p) =>\n !p.dotDotDotToken && is.isIdentifier(p.name) ? p.name.text : null,\n );\n const body = node.body;\n const line = lineAt(sf, node);\n if (is.isBlock(body))\n return {\n arrow: {\n params,\n body: sf.text.slice(body.getStart(sf) + 1, body.end - 1),\n block: true,\n line,\n },\n node,\n };\n return { arrow: { params, body: textOf(sf, body), block: false, line }, node };\n };\n for (const st of sf.statements) {\n if (!is.isVariableStatement(st)) continue;\n const exported = isExported(st);\n const constant = isConst(st.declarationList);\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n const name = d.name.text;\n // `satisfies`, `as`, `!` and parentheses change nothing at runtime: the call is inside them.\n let init: Expression = d.initializer;\n while (\n is.isParenthesizedExpression(init) ||\n is.isSatisfiesExpression(init) ||\n is.isAsExpression(init) ||\n is.isNonNullExpression(init)\n )\n init = init.expression;\n if (!is.isCallExpression(init)) continue;\n const kind = combinator(init.expression);\n if (!kind) continue;\n const line = lineAt(sf, st);\n try {\n if (!exported) fail(`${name} is a spec but not exported, so nothing would check it`, st);\n if (!constant)\n fail(\n `a spec must be a const export, not ${textOf(sf, st).split(/\\s/)[exported ? 1 : 0] ?? \"let\"}`,\n st,\n );\n const [first, second, third] = init.arguments;\n const fn = functionArg(first, init);\n if (kind === \"total\") {\n if (second) fail(\"total takes the function alone\", second);\n specs.push({ name, kind: \"total\", fn, text: `total(${fn})`, line, hints: new Map() });\n continue;\n }\n if (!second) return fail(\"forall takes the function, then { when, ensures }\", init);\n if (third) return fail(`unexpected ${textOf(sf, third)} after forall's arguments`, third);\n if (!is.isObjectLiteralExpression(second))\n return fail(\n \"forall's second argument must be an object literal { when, ensures }\",\n second,\n );\n let sample: { arrow: Arrow; node: ArrowFunction } | undefined;\n let when: { arrow: Arrow; node: ArrowFunction } | undefined;\n let ensures: { arrow: Arrow; node: ArrowFunction } | undefined;\n for (const prop of second.properties) {\n const key =\n is.isPropertyAssignment(prop) ||\n is.isShorthandPropertyAssignment(prop) ||\n is.isMethodDeclaration(prop)\n ? prop.name\n : undefined;\n const keyName =\n key && is.isIdentifier(key) ? key.text : key ? textOf(sf, key) : textOf(sf, prop);\n if (keyName !== \"sample\" && keyName !== \"when\" && keyName !== \"ensures\")\n fail(`forall's properties are sample, when and ensures, found ${keyName}`, prop);\n if (!is.isPropertyAssignment(prop))\n fail(`${keyName} must be written as ${keyName}: (…) => …`, prop);\n const read = arrow(prop.initializer, keyName);\n if (keyName === \"sample\") {\n if (sample) fail(\"sample is given twice\", prop);\n sample = read;\n } else if (keyName === \"when\") {\n if (when) fail(\"when is given twice\", prop);\n when = read;\n } else {\n if (ensures) fail(\"ensures is given twice\", prop);\n ensures = read;\n }\n }\n if (!ensures) return fail(\"forall needs an ensures\", second);\n // The precondition and the sample both steer the draws, combined per binder.\n const hintsOfArrow = (\n a: { arrow: Arrow; node: ArrowFunction } | undefined,\n ): Map<number, Hint> =>\n a && !is.isBlock(a.node.body) ? hintsIn(sf, a.node.body, a.arrow.params) : new Map();\n const fromSample = hintsOfArrow(sample);\n const fromWhen = hintsOfArrow(when);\n const hints = new Map<number, Hint>();\n for (const i of new Set([...fromSample.keys(), ...fromWhen.keys()])) {\n const h = combineHints(fromWhen.get(i), fromSample.get(i));\n if (h) hints.set(i, h);\n }\n specs.push({\n name,\n kind: \"forall\",\n fn,\n ...(sample ? { sample: sample.arrow } : {}),\n ...(when ? { when: when.arrow } : {}),\n ensures: ensures.arrow,\n text: ensures.arrow.body.replace(/\\s+/g, \" \").trim(),\n line,\n hints,\n });\n } catch (err) {\n if (!(err instanceof SpecFail)) throw err;\n errors.push({ line: err.line, message: `${name}: ${err.message}` });\n }\n }\n }\n const moduleImports: ModuleImport[] = [...bound]\n .filter(([, imp]) => imp.name !== \"*\" && imp.name !== \"default\" && fromModule(imp))\n .map(([local, imp]) => ({ local, name: imp.name }));\n return { specs, errors, imports: moduleImports };\n}\n\n/** The tighter of two endpoints on one side; the first when they cannot be compared. */\nfunction tighter(\n first: Endpoint | undefined,\n second: Endpoint | undefined,\n side: \"lower\" | \"upper\",\n): Endpoint | undefined {\n if (!first) return second;\n if (!second) return first;\n // Integral literals compare exactly (bigints reach past every double); others as doubles.\n const integral = (e: Endpoint) => !/[.eE]/.test(e.value);\n let order: number;\n try {\n if (integral(first) && integral(second)) {\n const a = endpointBigInt(first.value);\n const b = endpointBigInt(second.value);\n order = a === b ? 0 : a > b ? 1 : -1;\n } else {\n const a = endpointNumber(first.value);\n const b = endpointNumber(second.value);\n if (Number.isNaN(a) || Number.isNaN(b)) return first;\n order = a === b ? 0 : a > b ? 1 : -1;\n }\n } catch {\n return first;\n }\n if (order !== 0) return (side === \"lower\" ? order > 0 : order < 0) ? first : second;\n return first.inclusive ? second : first;\n}\n\n/**\n * Two hints on one binder as one: integer when either says so, the\n * tighter bound on each side, the first's regex (two cannot be combined,\n * and the draws are checked against both arrows anyway).\n */\nfunction combineHints(first: Hint | undefined, second: Hint | undefined): Hint | undefined {\n if (!first) return second;\n if (!second) return first;\n const lower = tighter(first.lower, second.lower, \"lower\");\n const upper = tighter(first.upper, second.upper, \"upper\");\n const regex = first.regex ?? second.regex;\n return {\n ...(first.integer || second.integer ? { integer: true as const } : {}),\n ...(lower ? { lower } : {}),\n ...(upper ? { upper } : {}),\n ...(regex ? { regex } : {}),\n };\n}\n\n/** Read a module and its spec file. */\nexport function readSpecs(input: ReadSpecsInput): ModuleSpecs {\n const modulePath = input.modulePath;\n const specPath = input.specPath ?? modulePath.replace(/\\.ts$/, \".props.ts\");\n return withProgram(\n [\n { path: modulePath, text: input.module },\n { path: specPath, text: input.spec },\n ],\n (opened) => {\n const { checker, file, parseError } = opened;\n const moduleError = parseError(modulePath);\n const specError = parseError(specPath);\n const errors: SpecError[] = [];\n if (moduleError)\n errors.push({\n line: moduleError.line,\n message: `the module could not be parsed: ${moduleError.message}`,\n inModule: true,\n });\n if (specError)\n errors.push({\n line: specError.line,\n message: `the spec file could not be parsed: ${specError.message}`,\n });\n if (moduleError || specError) return { functions: [], errors };\n const moduleFile = file(modulePath);\n const moduleSide = readModuleSide(moduleFile, checker);\n const specSide = readSpecSide(\n file(specPath),\n opened,\n modulePath,\n moduleFile.path,\n new Set(input.specSpecifiers ?? [\"eutaxy/spec\", \"@eutaxy/spec\"]),\n );\n errors.push(...moduleSide.errors, ...specSide.errors);\n // The spec file runs whenever it is imported (the TESTED rung imports it): an assignment to a\n // built-in there makes the claims compute something other than what they are read as.\n const patched = rebound(file(specPath), checker, opened.standardGlobal);\n if (patched)\n errors.push({\n line: patched.line,\n message: `the spec file assigns to ${patched.target}, so the built-ins its claims are read with may not be the standard ones`,\n });\n // The claims' free names: the spec file's local names for the module's declarations.\n const imports = specSide.imports.flatMap((i) => {\n const fn = moduleSide.exports.get(i.name);\n return fn === undefined ? [] : [{ local: i.local, fn }];\n });\n const byFunction = new Map<string, { decl: Declaration; properties: Property[] }>();\n for (const s of specSide.specs) {\n const local = moduleSide.exports.get(s.fn);\n const decl = local === undefined ? undefined : moduleSide.declarations.get(local);\n if (!decl) {\n errors.push({\n line: s.line,\n message: `${s.name}: the module exports no function ${s.fn} whose parameters the reader can read (a function declaration or a const arrow)`,\n });\n continue;\n }\n const entry = byFunction.get(s.fn) ?? { decl, properties: [] };\n if (entry.properties.some((p) => p.name === s.name)) {\n errors.push({ line: s.line, message: `${s.name} is exported twice` });\n continue;\n }\n const binders: Binder[] = decl.params.map((p, i) => {\n const fromEnsures = s.ensures?.params[i];\n const name = fromEnsures ?? p.name ?? `arg${i}`;\n const hint = s.hints.get(i);\n return { name, type: p.type, ...(hint ? { hint } : {}) };\n });\n entry.properties.push({\n name: s.name,\n kind: s.kind,\n binders,\n ...(s.sample ? { sample: s.sample } : {}),\n ...(s.when ? { when: s.when } : {}),\n ...(s.ensures ? { ensures: s.ensures } : {}),\n imports,\n text: s.text,\n line: s.line,\n });\n byFunction.set(s.fn, entry);\n }\n const functions: FunctionSpec[] = [...byFunction.entries()].map(\n ([name, { decl, properties }]) => ({\n name,\n params: decl.params,\n properties,\n line: decl.line,\n offset: decl.offset,\n }),\n );\n return { functions, errors };\n },\n );\n}\n","/**\n * Lean 4 for a module in the subset and the properties on it. The\n * module's record types become structures, its functions definitions over\n * `Int`, `Bool` and `String`, each property a theorem whose statement is\n * the claim over its binders, with the precondition as a hypothesis.\n * Booleans stay `Bool` in terms, as in TypeScript, and become propositions\n * with `= true` where a statement needs one; comparisons are `decide`d.\n * Every theorem is closed by one tactic script, except where a proof is\n * supplied beside the spec file (`supplied.ts`): then the statement is\n * fixed as a definition first, and the supplied tactics must prove it.\n */\n\nimport {\n children,\n type Expr,\n hasLoneSurrogate,\n OutsideSubset,\n type RecordType,\n readArrowBody,\n renameVars,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n type TypeContext,\n typeOf,\n} from \"@eutaxy/prover/reader\";\nimport { type Arrow, describeType, type Property, type SpecType } from \"@eutaxy/spec\";\n\n/**\n * TypeScript names as Lean identifiers that can clash with nothing Lean\n * defines and not with each other: functions get `f_`, record types `R_`,\n * variables `v_`, theorems `t_`. The schemes differ in their first letter,\n * so no two names from different kinds coincide whatever the author\n * wrote (`ts_f` and `f_` would, under suffixing), and Lean's prelude has\n * no names of these shapes, so a function called `decide` or a parameter\n * called `max` stays what the author meant.\n */\nexport const ident = {\n fn: (name: string) => quote(`f_${name}`),\n record: (name: string) => quote(`R_${name}`),\n variable: (name: string) => quote(`v_${name}`),\n // Fields keep their names, which may be Lean keywords: those are quoted.\n field: (name: string) => (leanKeywords.has(name) ? `«${name}»` : quote(name)),\n};\n\n/** Lean's keywords, which a field name may coincide with. */\nconst leanKeywords = new Set(\n \"at by calc def deriving do else end example export extends from fun have if import in inductive instance lemma let macro match mutual namespace open private protected return section set_option show structure syntax termination_by then theorem universe variable where with abbrev axiom class opaque partial noncomputable unsafe nomatch nofun omit include local scoped attribute initialize builtin_initialize elab notation infix infixl infixr prefix postfix declare_syntax_cat macro_rules elab_rules syntax_rules suffices obtain exists forall Type Prop Sort true false fun\".split(\n \" \",\n ),\n);\n\nfunction quote(name: string): string {\n // Guillemets hold anything but guillemets: those are escaped as `%ab` and `%bb`, with `%` itself\n // as `%25` first, in every name, so two names never meet in one identifier.\n const escaped = name.replace(/%/g, \"%25\").replace(/«/g, \"%ab\").replace(/»/g, \"%bb\");\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(escaped) ? escaped : `«${escaped}»`;\n}\n\nfunction leanType(t: SubsetType): string {\n switch (t.kind) {\n case \"int\":\n return \"Int\";\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return \"String\";\n case \"record\":\n return ident.record(t.name);\n case \"list\":\n return `(List ${leanType(t.element)})`;\n case \"nothing\":\n return fail(\"the element type of an empty array, which nothing gives\");\n case \"nullable\":\n case \"union\":\n case \"null\":\n return fail(`a ${t.kind} type, which the Lean engine does not take yet`);\n }\n}\n\nexport function emitRecord(r: RecordType): string {\n return [\n `structure ${ident.record(r.name)} where`,\n ...r.fields.map((f) => ` ${ident.field(f.name)} : ${leanType(f.type)}`),\n \" deriving Repr, DecidableEq\",\n ].join(\"\\n\");\n}\n\ninterface Env {\n readonly module: SubsetModule;\n readonly ctx: TypeContext;\n /**\n * In the non-empty branch of a structurally recursive function: the list\n * parameter is `head :: tail` there, so `xs[0] ?? d` is the head,\n * `xs.slice(1)` the tail (what the recursive call must be given for Lean\n * to see the recursion is structural), and `xs` itself `head :: tail`.\n */\n readonly cons?: { readonly list: string; readonly head: string; readonly tail: string };\n}\n\nfunction env(module: SubsetModule): Env {\n return {\n module,\n ctx: {\n records: new Map(module.records.map((r) => [r.name, r])),\n signatures: new Map(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n ),\n },\n };\n}\n\nexport const divisionOutside =\n \"division other than Math.floor(x / c) with c a positive integer constant: this engine models numbers as integers, which / leaves (the SMT engine takes it)\";\n\n/** Whether an expression divides other than as Math.floor(x / c), c a positive integer constant. */\nexport function dividesOutside(e: Expr): boolean {\n if (e.kind === \"floor\" && e.operand.kind === \"binary\" && e.operand.op === \"/\") {\n const c = integerValue(e.operand.right);\n if (c !== undefined && c > 0n) return dividesOutside(e.operand.left);\n }\n if (e.kind === \"binary\" && e.op === \"/\") return true;\n return children(e).some(dividesOutside);\n}\n\n/** The value of an integer expression built from literals by + - * and negation, if it is one. */\nfunction integerValue(e: Expr): bigint | undefined {\n if (e.kind === \"int\") return BigInt(e.value);\n if (e.kind === \"neg\") {\n const v = integerValue(e.operand);\n return v === undefined ? undefined : -v;\n }\n if (e.kind !== \"binary\") return undefined;\n const l = integerValue(e.left);\n const r = integerValue(e.right);\n if (l === undefined || r === undefined) return undefined;\n if (e.op === \"+\") return l + r;\n if (e.op === \"-\") return l - r;\n if (e.op === \"*\") return l * r;\n return undefined;\n}\n\nconst fail: (message: string) => never = (message) => {\n throw new OutsideSubset(message, 0);\n};\n\n/** A term of the expression's TypeScript type: `Int`, `Bool`, `String` or a structure. */\nexport function term(e: Expr, scope: ReadonlyMap<string, SubsetType>, env: Env): string {\n const t = (x: Expr) => term(x, scope, env);\n switch (e.kind) {\n case \"int\":\n return `(${e.value} : Int)`;\n case \"bool\":\n return e.value ? \"true\" : \"false\";\n case \"string\":\n return leanString(e.value);\n case \"var\":\n if (env.cons?.list === e.name) return `(${env.cons.head} :: ${env.cons.tail})`;\n return ident.variable(e.name);\n case \"null\":\n case \"narrow\":\n return fail(\"null, which the Lean engine does not take yet\");\n case \"narrowTag\":\n return fail(\"a union, which the Lean engine does not take yet\");\n case \"neg\":\n return `(-${t(e.operand)})`;\n case \"not\":\n return `(!${t(e.operand)})`;\n case \"isInteger\":\n // Every number is an integer in this engine's model. The operand is still emitted, so what\n // this engine refuses in it (a division) is refused here too, not dropped with it.\n typeOf(e.operand, scope, env.ctx, fail);\n t(e.operand);\n return \"true\";\n case \"floor\": {\n // Of an integer, Math.floor is the integer; of x / c, with c a positive integer constant, it is\n // Lean's Int division, which rounds toward negative infinity as Math.floor does.\n const o = e.operand;\n if (o.kind !== \"binary\" || o.op !== \"/\") return t(o);\n const c = integerValue(o.right);\n if (c === undefined || c <= 0n) fail(divisionOutside);\n return `(${t(o.left)} / (${c} : Int))`;\n }\n case \"binary\":\n switch (e.op) {\n case \"+\": {\n const lt = typeOf(e.left, scope, env.ctx, fail);\n return `(${t(e.left)} ${lt.kind === \"string\" ? \"++\" : \"+\"} ${t(e.right)})`;\n }\n case \"-\":\n case \"*\":\n return `(${t(e.left)} ${e.op} ${t(e.right)})`;\n case \"/\":\n return fail(divisionOutside);\n case \"<\":\n case \">\":\n return `(decide (${t(e.left)} ${e.op} ${t(e.right)}))`;\n case \"<=\":\n return `(decide (${t(e.left)} ≤ ${t(e.right)}))`;\n case \">=\":\n return `(decide (${t(e.left)} ≥ ${t(e.right)}))`;\n case \"===\":\n case \"!==\": {\n // === on objects compares references in JavaScript; Lean's = would compare the fields.\n const lt = typeOf(e.left, scope, env.ctx, fail);\n if (lt.kind === \"record\")\n fail(\n `${e.op} on records compares references in JavaScript; compare their fields instead`,\n );\n return `(decide (${t(e.left)} ${e.op === \"===\" ? \"=\" : \"≠\"} ${t(e.right)}))`;\n }\n case \"&&\":\n return `(${t(e.left)} && ${t(e.right)})`;\n case \"||\":\n return `(${t(e.left)} || ${t(e.right)})`;\n }\n break;\n case \"cond\":\n return `(if ${t(e.test)} = true then ${t(e.ifTrue)} else ${t(e.ifFalse)})`;\n case \"call\":\n return `(${ident.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join(\"\")})`;\n case \"field\":\n // A list's length is a natural number in Lean; the subset counts in Int.\n if (typeOf(e.object, scope, env.ctx, fail).kind === \"list\")\n return `(Int.ofNat (List.length ${t(e.object)}))`;\n return `${t(e.object)}.${ident.field(e.field)}`;\n case \"record\": {\n const type = typeOf(e, scope, env.ctx, fail);\n const name =\n type.kind === \"record\"\n ? ident.record(type.name)\n : fail(\"a record literal of no record type\");\n return `({ ${e.fields.map((f) => `${ident.field(f.name)} := ${t(f.value)}`).join(\", \")} } : ${name})`;\n }\n case \"let\": {\n const inner = new Map(scope);\n const bound = e.type ?? typeOf(e.value, scope, env.ctx, fail);\n inner.set(e.name, bound);\n // The annotation, when there is one, types the binding in Lean too (`const xs: number[] = []`).\n const annotated = e.type ? ` : ${leanType(e.type)}` : \"\";\n return `(let ${ident.variable(e.name)}${annotated} := ${t(e.value)}; ${term(e.body, inner, env)})`;\n }\n case \"list\": {\n if (e.items.length === 0 && !e.rest) return \"[]\";\n if (!e.rest) return `[${e.items.map(t).join(\", \")}]`;\n return `(${[...e.items.map(t), t(e.rest)].join(\" :: \")})`;\n }\n case \"tail\":\n if (e.list.kind === \"var\" && env.cons?.list === e.list.name) return env.cons.tail;\n return `(List.tail ${t(e.list)})`;\n case \"headOr\":\n if (e.list.kind === \"var\" && env.cons?.list === e.list.name) return env.cons.head;\n return `(List.headD ${t(e.list)} ${t(e.fallback)})`;\n case \"iterate\": {\n const listType = typeOf(e.list, scope, env.ctx, fail);\n if (listType.kind !== \"list\") fail(`${e.op} on a ${listType.kind}`);\n const inner = new Map(scope);\n inner.set(e.item, listType.element);\n if (e.index !== undefined) inner.set(e.index, { kind: \"int\" });\n const body = term(e.body, inner, env);\n // The index counts from 0 as a natural number; the subset's is an Int.\n const nat = e.index === undefined ? \"\" : quote(`nv_${e.index}`);\n const fn =\n e.index === undefined\n ? `(fun ${ident.variable(e.item)} => ${body})`\n : `(fun (${ident.variable(e.item)}, ${nat}) => let ${ident.variable(e.index)} := Int.ofNat ${nat}; ${body})`;\n const list = e.index === undefined ? t(e.list) : `(List.zipIdx ${t(e.list)})`;\n // map and flatMap take the function first; all and any take the list first.\n if (e.op === \"map\") return `(List.map ${fn} ${list})`;\n if (e.op === \"flatMap\") return `(List.flatMap ${fn} ${list})`;\n return `(${e.op === \"every\" ? \"List.all\" : \"List.any\"} ${list} ${fn})`;\n }\n case \"fold\": {\n const listType = typeOf(e.list, scope, env.ctx, fail);\n if (listType.kind !== \"list\") fail(`reduce on a ${listType.kind}`);\n const inner = new Map(scope);\n inner.set(e.acc, typeOf(e, scope, env.ctx, fail));\n inner.set(e.item, listType.element);\n return `(List.foldl (fun ${ident.variable(e.acc)} ${ident.variable(e.item)} => ${term(e.body, inner, env)}) ${t(e.init)} ${t(e.list)})`;\n }\n }\n}\n\nexport function emitFunction(f: SubsetFunction, module: SubsetModule): string {\n const e = env(module);\n const scope = new Map(f.params.map((p) => [p.name, p.type]));\n const params = f.params.map((p) => `(${ident.variable(p.name)} : ${leanType(p.type)})`).join(\" \");\n const head = `def ${ident.fn(f.name)} ${params} : ${leanType(f.returns)} :=`;\n if (f.structural === undefined || f.body.kind !== \"cond\")\n return `${head}\\n ${term(f.body, scope, e)}`;\n // Structural recursion: a match on the list the body tests against 0, recursing on its tail.\n // `vh_`/`vt_` names cannot meet a variable, whose names all start `v_`.\n const list = (f.params[f.structural] as { name: string }).name;\n const cons = { list, head: quote(`vh_${list}`), tail: quote(`vt_${list}`) };\n return [\n head,\n ` match ${ident.variable(list)} with`,\n ` | [] => ${term(f.body.ifTrue, scope, e)}`,\n ` | ${cons.head} :: ${cons.tail} => ${term(f.body.ifFalse, scope, { ...e, cons })}`,\n ].join(\"\\n\");\n}\n\n/**\n * The subset type a binder ranges over, or `OutsideSubset`: `number` is\n * `Int` (the engine's integer model, an assumption every PROVEN carries),\n * a union of string literals is `String` (the proof covers every string,\n * more than the type admits), a record is the module's structure of that\n * name. Nullable types, tagged unions, bigint and whatever the reader\n * could not read are outside.\n */\nexport function binderType(name: string, t: SpecType, module: SubsetModule): SubsetType {\n switch (t.kind) {\n case \"number\":\n return { kind: \"int\" };\n case \"boolean\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"literal\":\n if (typeof t.value === \"string\") return { kind: \"string\" };\n if (typeof t.value === \"boolean\") return { kind: \"bool\" };\n return { kind: \"int\" };\n case \"bigint\":\n // A BigInt passed to a function over number throws on the first mixed operation in JavaScript.\n fail(`binder ${name} over bigint: the subset has no bigint`);\n break;\n case \"union\":\n if (t.members.every((m) => m.kind === \"literal\" && typeof m.value === \"string\"))\n return { kind: \"string\" };\n if (t.members.some((m) => m.kind === \"null\" || m.kind === \"undefined\"))\n fail(\n `binder ${name} over ${describeType(t)}: nullable types are not in the engine's subset yet`,\n );\n fail(`binder ${name} over ${describeType(t)}: unions are not in the engine's subset yet`);\n break;\n case \"record\":\n if (t.name !== undefined && module.records.some((r) => r.name === t.name))\n return { kind: \"record\", name: t.name };\n fail(\n `binder ${name} over ${describeType(t)}: ${t.name === undefined ? \"an inline record type\" : `record type ${t.name} is outside the subset`}`,\n );\n break;\n case \"null\":\n case \"undefined\":\n fail(`binder ${name} over ${t.kind}`);\n break;\n case \"array\":\n return { kind: \"list\", element: binderType(name, t.element, module) };\n case \"unknown\":\n fail(`binder ${name} over ${t.text}, which the reader could not read`);\n }\n}\n\n/** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */\nfunction arrowTerm(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n try {\n return arrowTermAt(arrow, what, property, types, e);\n } catch (err) {\n // What the subset refused, located in the spec file.\n if (!(err instanceof OutsideSubset)) throw err;\n throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);\n }\n}\n\nfunction arrowTermAt(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n const binders = property.binders;\n const scope = new Map<string, SubsetType>();\n const names = new Map<string, string>();\n arrow.params.forEach((p, i) => {\n const binder = binders[i];\n const type = types[i];\n if (p === null) fail(`a destructured parameter in ${what}`);\n if (!binder || !type) fail(`${what} takes more parameters than the function has`);\n scope.set(p, type);\n names.set(p, binder.name);\n });\n const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));\n const read = readArrowBody(arrow, scope, e.module, aliases);\n const t = typeOf(read, scope, e.ctx, fail);\n if (t.kind !== \"bool\")\n fail(`${what} is not boolean (a ${t.kind === \"record\" ? t.name : t.kind})`);\n const renamed = renameVars(read, names);\n const binderScope = new Map(binders.map((b, i) => [b.name, types[i] as SubsetType]));\n return term(renamed, binderScope, e);\n}\n\n/** The proposition a property claims: binders universally quantified, the precondition in front. */\nexport function statement(property: Property, module: SubsetModule): string {\n return stated(property, module).text;\n}\n\n/** The statement and how many hypotheses stand before the claim (the tactic script introduces them by name). */\nexport function stated(\n property: Property,\n module: SubsetModule,\n): { readonly text: string; readonly hypotheses: number } {\n if (property.kind !== \"forall\" || !property.ensures) fail(\"not a forall property\");\n const e = env(module);\n const types = property.binders.map((b) => binderType(b.name, b.type, module));\n const binders = property.binders\n .map((b, i) => `(${ident.variable(b.name)} : ${leanType(types[i] as SubsetType)})`)\n .join(\" \");\n const hyps = property.when\n ? [`(${arrowTerm(property.when, \"when\", property, types, e)} = true)`]\n : [];\n const claim = `(${arrowTerm(property.ensures, \"ensures\", property, types, e)} = true)`;\n const body = [...hyps, claim].join(\" →\\n \");\n return {\n // A function of no parameters has nothing to quantify over: the proposition stands alone.\n text: binders === \"\" ? body : `∀ ${binders},\\n ${body}`,\n hypotheses: hyps.length,\n };\n}\n\n/**\n * The tactic script every theorem is closed by. Booleans become\n * propositions first, while the `Decidable` instances in the statement\n * still match their propositions (unfolding under `decide` first leaves\n * them stale and stops `simp`); Bool binders are cased, so boolean claims\n * are decided by enumeration; then the module's definitions unfold, each\n * conditional splits, and linear integer arithmetic (`omega`) closes what\n * remains. Nothing here is specific to a property; what Lean checks is\n * the statement.\n */\nexport function tactics(module: SubsetModule, property: Property, hypotheses: number): string {\n const defs = module.functions.map((f) => ident.fn(f.name)).join(\", \");\n const names = property.binders.map((b) => ident.variable(b.name));\n const hyps = Array.from({ length: hypotheses }, (_, i) => `h${i}_`);\n const bools = property.binders\n .filter(\n (b) =>\n b.type.kind === \"boolean\" ||\n (b.type.kind === \"literal\" && typeof b.type.value === \"boolean\"),\n )\n .map((b) => ident.variable(b.name));\n const introduced = [...names, ...hyps];\n return [\n ...(introduced.length > 0 ? [` intro ${introduced.join(\" \")}`] : []),\n ...(bools.length > 0 ? [` ${bools.map((b) => `cases ${b}`).join(\" <;> \")}`] : []),\n \" all_goals (try simp_all)\",\n ` all_goals (try simp only [${defs}] at *)`,\n \" all_goals (repeat' (split <;> simp_all))\",\n \" all_goals (try simp_all)\",\n \" all_goals (first | decide | trivial | omega)\",\n ].join(\"\\n\");\n}\n\n/** A Lean-safe theorem name: unique by position, readable by the function's and property's names. */\nexport function theoremName(index: number, fn: string, property: string): string {\n return `t${index}_${fn}_${property}`.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n\nexport interface EmittedTheorem {\n readonly function: string;\n readonly property: string;\n readonly name: string;\n /** 1-based lines of the theorem in the emitted file, inclusive. */\n readonly from: number;\n readonly to: number;\n /** Closed by a supplied proof, not the tactic script. */\n readonly supplied?: true;\n /** For a supplied proof: the 1-based line of the `#print axioms` that audits it. */\n readonly axiomsLine?: number;\n /** For a supplied proof: the 1-based line of the `#check` that shows its type, which must be the statement alone. */\n readonly typeLine?: number;\n}\n\nexport interface Emitted {\n readonly source: string;\n readonly theorems: readonly EmittedTheorem[];\n /** Properties the emitter could not state, with why. */\n readonly skipped: readonly {\n readonly function: string;\n readonly property: string;\n readonly reason: string;\n }[];\n /** 1-based lines of the supplied lemmas in the emitted file, inclusive, when there are any. */\n readonly lemmas?: { readonly from: number; readonly to: number };\n}\n\n/** The supplied proofs to use: lemmas, and each property's tactic proof by name. */\nexport interface SuppliedText {\n readonly lemmas: string;\n readonly proofs: ReadonlyMap<string, string>;\n}\n\n/** A tactic block at the indentation a `by` takes: its common indentation stripped, two spaces put back. */\nfunction indented(block: string): string {\n const lines = block.split(\"\\n\");\n const widths = lines.filter((l) => l.trim() !== \"\").map((l) => /^ */.exec(l)?.[0].length ?? 0);\n const common = widths.length > 0 ? Math.min(...widths) : 0;\n return lines.map((l) => (l.trim() === \"\" ? \"\" : ` ${l.slice(common)}`)).join(\"\\n\");\n}\n\n/**\n * The whole file: structures, definitions, one theorem per property, any\n * extra lines (translation checks), then the properties with supplied\n * proofs: each statement fixed as a definition before any supplied text,\n * the supplied lemmas, each theorem proving its definition with the\n * supplied tactics, and `#print axioms` for each.\n */\nexport function emitModule(\n module: SubsetModule,\n properties: readonly { readonly function: string; readonly property: Property }[],\n extra: readonly string[] = [],\n supplied?: SuppliedText,\n): Emitted {\n const parts: string[] = [\n \"-- Generated by Eutaxy's first-party engine from the module and its spec file; the theorems are its properties.\",\n \"set_option linter.unusedSimpArgs false\",\n \"set_option linter.unusedVariables false\",\n ...module.records.map(emitRecord),\n ...module.functions.map((f) => emitFunction(f, module)),\n ];\n const theorems: EmittedTheorem[] = [];\n const skipped: Emitted[\"skipped\"][number][] = [];\n const later: { fn: string; property: string; name: string; statement: string; proof: string }[] =\n [];\n for (const { function: fn, property } of properties) {\n let body: { text: string; hypotheses: number };\n try {\n body = stated(property, module);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n skipped.push({ function: fn, property: property.name, reason: err.message });\n continue;\n }\n const name = theoremName(theorems.length + skipped.length + later.length, fn, property.name);\n const proof = supplied?.proofs.get(property.name);\n if (proof !== undefined) {\n later.push({ fn, property: property.name, name, statement: body.text, proof });\n continue;\n }\n const text = `theorem ${name} :\\n ${body.text} := by\\n${tactics(module, property, body.hypotheses)}`;\n const from = parts.join(\"\\n\\n\").split(\"\\n\").length + 2;\n parts.push(text);\n theorems.push({\n function: fn,\n property: property.name,\n name,\n from,\n to: from + text.split(\"\\n\").length - 1,\n });\n }\n parts.push(...extra);\n const lineAfter = () => parts.join(\"\\n\\n\").split(\"\\n\").length + 2;\n let lemmas: Emitted[\"lemmas\"];\n if (later.length > 0) {\n for (const l of later) parts.push(`def s_${l.name} : Prop :=\\n ${l.statement}`);\n if (supplied && supplied.lemmas !== \"\") {\n const from = lineAfter();\n parts.push(supplied.lemmas);\n lemmas = { from, to: from + supplied.lemmas.split(\"\\n\").length - 1 };\n }\n const ownProofs: EmittedTheorem[] = [];\n for (const l of later) {\n const text = `theorem ${l.name} : s_${l.name} := by\\n unfold s_${l.name}\\n${indented(l.proof)}`;\n const from = lineAfter();\n parts.push(text);\n ownProofs.push({\n function: l.fn,\n property: l.property,\n name: l.name,\n from,\n to: from + text.split(\"\\n\").length - 1,\n supplied: true,\n });\n }\n // Each audit's line is recorded: only Lean's message at that line counts as the audit.\n for (const t of ownProofs) {\n // Its type, as Lean has it: a hypothesis the supplied text slipped in (a section variable) shows here.\n const typeLine = lineAfter();\n parts.push(`#check @${t.name}`);\n const axiomsLine = lineAfter();\n parts.push(`#print axioms ${t.name}`);\n theorems.push({ ...t, axiomsLine, typeLine });\n }\n }\n return { source: `${parts.join(\"\\n\\n\")}\\n`, theorems, skipped, ...(lemmas ? { lemmas } : {}) };\n}\n\n/**\n * A JavaScript string as a Lean string literal: `\"` and `\\` escaped, control\n * characters as `\\xHH`, everything else written as it is (Lean source is\n * UTF-8). A lone surrogate has no Lean character and is refused.\n */\nexport function leanString(value: string): string {\n if (hasLoneSurrogate(value))\n fail(\"a string with a lone surrogate, which Lean's strings cannot hold\");\n let out = '\"';\n for (const c of value) {\n const code = c.codePointAt(0) as number;\n if (c === '\"') out += '\\\\\"';\n else if (c === \"\\\\\") out += \"\\\\\\\\\";\n else if (code < 0x20 || code === 0x7f) out += `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n else out += c;\n }\n return `${out}\"`;\n}\n\n/** A TypeScript value of a subset type as a Lean term, for translation checks. */\nexport function value(v: unknown, t: SubsetType, module: SubsetModule): string {\n switch (t.kind) {\n case \"int\":\n if (typeof v !== \"number\" || !Number.isInteger(v)) fail(`${String(v)} is not an integer`);\n return `(${v} : Int)`;\n case \"bool\":\n if (typeof v !== \"boolean\") fail(`${String(v)} is not a boolean`);\n return v ? \"true\" : \"false\";\n case \"string\":\n if (typeof v !== \"string\") fail(`${String(v)} is not a string`);\n return leanString(v);\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a record`);\n const o = v as Record<string, unknown>;\n const extra = Object.keys(o).filter((k) => !rec.fields.some((f) => f.name === k));\n if (extra.length > 0) fail(`${t.name} value has unexpected fields ${extra.join(\", \")}`);\n return `({ ${rec.fields.map((f) => `${ident.field(f.name)} := ${value(o[f.name], f.type, module)}`).join(\", \")} } : ${ident.record(t.name)})`;\n }\n case \"list\":\n if (!Array.isArray(v)) fail(`${String(v)} is not an array`);\n return `([${v.map((x) => value(x, t.element, module)).join(\", \")}] : ${leanType(t)})`;\n case \"nothing\":\n return fail(\"a value of no type\");\n case \"nullable\":\n case \"union\":\n case \"null\":\n return fail(`a ${t.kind} type, which the Lean engine does not take yet`);\n }\n}\n","/**\n * Where a pinned prover toolchain lives on this machine once `eutaxy prover\n * install` has put it there, and what that command downloads: one upstream\n * release file per platform, with the checksum the download must match.\n * Node-side only (`@eutaxy/prover/toolchain`, a subpath so workerd never\n * loads it): it reads the file system, so this file alone references Node's\n * types, as the reader alone uses the compiler's. Nothing here downloads or\n * runs anything; the engines ask `installed` and the command does the rest.\n */\n/// <reference types=\"node\" />\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\n/** The platforms Eutaxy runs a prover on: Node's `process.platform-process.arch`. */\nexport type Platform = \"linux-x64\" | \"linux-arm64\" | \"darwin-x64\" | \"darwin-arm64\" | \"win32-x64\";\nexport const platforms: readonly Platform[] = [\n \"linux-x64\",\n \"linux-arm64\",\n \"darwin-x64\",\n \"darwin-arm64\",\n \"win32-x64\",\n];\n\n/** One file of an upstream release: where it is, what it must hash to, how big it is. */\nexport interface ReleaseFile {\n /** The file's name in the release, which a mirror or offline copy keeps. */\n readonly file: string;\n readonly url: string;\n /** Lower-case hex SHA-256 of the file. */\n readonly sha256: string;\n readonly bytes: number;\n}\n\n/** A prover toolchain as `eutaxy prover install` knows it. */\nexport interface Toolchain {\n /** The name the command takes: the engine's. */\n readonly name: string;\n readonly version: string;\n /** The executable inside the unpacked release, relative to its root; `.exe` is added on Windows. */\n readonly executable: string;\n readonly files: Readonly<Partial<Record<Platform, ReleaseFile>>>;\n}\n\n/** What of the machine the lookup depends on, so tests can hand in another. */\nexport interface Host {\n readonly platform: string;\n readonly arch: string;\n readonly env: Readonly<Record<string, string | undefined>>;\n readonly home: string;\n}\n\nexport function host(): Host {\n return { platform: process.platform, arch: process.arch, env: process.env, home: homedir() };\n}\n\nexport function platformOf(h: Host): Platform | undefined {\n const key = `${h.platform}-${h.arch}`;\n return (platforms as readonly string[]).includes(key) ? (key as Platform) : undefined;\n}\n\n/**\n * Eutaxy's cache directory: `EUTAXY_CACHE_DIR`, else the platform's user\n * cache (`$XDG_CACHE_HOME/eutaxy` or `~/.cache/eutaxy` on Linux,\n * `~/Library/Caches/eutaxy` on macOS, `%LOCALAPPDATA%\\eutaxy\\Cache` on\n * Windows). Always absolute: the engines spawn the executable from a\n * scratch directory, where a relative path would not resolve.\n */\nexport function cacheDir(h: Host = host()): string {\n const set = h.env[\"EUTAXY_CACHE_DIR\"];\n if (set) return resolve(set);\n if (h.platform === \"darwin\") return join(h.home, \"Library\", \"Caches\", \"eutaxy\");\n if (h.platform === \"win32\")\n return join(h.env[\"LOCALAPPDATA\"] || join(h.home, \"AppData\", \"Local\"), \"eutaxy\", \"Cache\");\n return resolve(h.env[\"XDG_CACHE_HOME\"] || join(h.home, \".cache\"), \"eutaxy\");\n}\n\n/** Where one toolchain's unpacked release lives: `<cache>/toolchains/<name>/<version>`. */\nexport function toolchainDir(\n cache: string,\n toolchain: Pick<Toolchain, \"name\" | \"version\">,\n): string {\n return join(cache, \"toolchains\", toolchain.name, toolchain.version);\n}\n\n/** The file the command writes last, so its presence means the install completed. */\nexport const markerFile = \"eutaxy-toolchain.json\";\n\nexport interface InstallMarker {\n readonly name: string;\n readonly version: string;\n readonly platform: Platform;\n readonly file: string;\n readonly sha256: string;\n /** Where the file came from: the upstream URL, or the mirror or directory given. */\n readonly source: string;\n}\n\nexport function executableName(toolchain: Pick<Toolchain, \"executable\">, h: Host): string {\n return h.platform === \"win32\" ? `${toolchain.executable}.exe` : toolchain.executable;\n}\n\nexport interface Installed {\n readonly dir: string;\n readonly executable: string;\n readonly marker: InstallMarker;\n}\n\n/**\n * The toolchain the command put in the cache, if its marker and its\n * executable are both there and the marker names this toolchain for this\n * platform (a cache carried to another machine holds the wrong binary).\n */\nexport function installed(toolchain: Toolchain, h: Host = host()): Installed | undefined {\n const dir = toolchainDir(cacheDir(h), toolchain);\n const executable = join(dir, executableName(toolchain, h));\n const markerPath = join(dir, markerFile);\n if (!existsSync(markerPath) || !existsSync(executable)) return undefined;\n try {\n const marker = JSON.parse(readFileSync(markerPath, \"utf8\")) as Partial<InstallMarker>;\n if (\n marker.name !== toolchain.name ||\n marker.version !== toolchain.version ||\n marker.platform !== platformOf(h) ||\n typeof marker.file !== \"string\" ||\n typeof marker.sha256 !== \"string\" ||\n typeof marker.source !== \"string\"\n )\n return undefined;\n return { dir, executable, marker: marker as InstallMarker };\n } catch {\n return undefined;\n }\n}\n","/**\n * Running Lean over a process boundary. The engine is pinned to one Lean\n * release, looked for in Eutaxy's cache first (where `eutaxy prover install\n * lean` puts the upstream release named in `leanDownloads`), then through\n * `elan` (Lean's toolchain manager), asked for it by name, then as a bare\n * `lean` that must report that version. Nothing is ever downloaded during\n * a check; a missing toolchain is `unavailable`, with the command that\n * installs it. Diagnostics come back as `file:line:col: severity: message`\n * lines, which the engine maps to theorems.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { type Host, host, installed, type Toolchain } from \"@eutaxy/prover/toolchain\";\n\n/**\n * The Lean release the engine's contract corpus is checked against. On a\n * bump: run the corpus and the supplied-proof tests on the new release,\n * and read its release notes for a new command that runs code while a\n * file is checked (a `#` command is already refused; a new word goes into\n * `supplied.ts`'s refused list in the same change). CI caches the\n * toolchain by this file's hash.\n */\nexport const leanToolchain = \"leanprover/lean4:v4.35.0\";\nexport const leanVersion = \"4.35.0\";\n/** How to put the pinned toolchain on this machine. */\nexport const installHint = `run: eutaxy prover install lean (or install elan, https://elan.lean-lang.org, and run: elan toolchain install ${leanToolchain})`;\n\nconst leanRelease = `https://github.com/leanprover/lean4/releases/download/v${leanVersion}`;\nconst leanFile = (name: string, sha256: string, bytes: number) => ({\n file: name,\n url: `${leanRelease}/${name}`,\n sha256,\n bytes,\n});\n/**\n * The upstream release files `eutaxy prover install lean` downloads, one per\n * platform, as published on Lean's GitHub release with the checksums it\n * reports; the file names carry the version, and a test holds them to\n * `leanVersion`. The compiler ships its C toolchain, so each is 570 to\n * 620 MB, the same download elan makes.\n */\nexport const leanDownloads: Toolchain = {\n name: \"lean\",\n version: leanVersion,\n executable: \"bin/lean\",\n files: {\n \"linux-x64\": leanFile(\n \"lean-4.35.0-linux.tar.zst\",\n \"7289597a44543246c9227b8cae501767e095ce17f6d448b95fc4a8dc97268f6d\",\n 594481375,\n ),\n \"linux-arm64\": leanFile(\n \"lean-4.35.0-linux_aarch64.tar.zst\",\n \"c8f0f8a3920e839718b1343e6781fd80a3e9b1024fbcd7078eb30f54e806b028\",\n 594868592,\n ),\n \"darwin-x64\": leanFile(\n \"lean-4.35.0-darwin.tar.zst\",\n \"0b43be5c7ecfb36016566a41005ab62bdb04743e6bfd5837e45f796ef4750b4e\",\n 576516478,\n ),\n \"darwin-arm64\": leanFile(\n \"lean-4.35.0-darwin_aarch64.tar.zst\",\n \"c0c6f34f35ba1dcc5c4a5fd106fefab9eb5e8469712624dd2c868d51b63177c2\",\n 570422530,\n ),\n \"win32-x64\": leanFile(\n \"lean-4.35.0-windows.tar.zst\",\n \"893fde3f52b48c647e3edcf33844cbb61f8ef70fcd88e0536bfc83f29844081e\",\n 622724192,\n ),\n },\n};\n\nexport interface LeanRun {\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n readonly timedOut: boolean;\n}\n\nexport interface LeanDiagnostic {\n readonly line: number;\n readonly column: number;\n readonly severity: \"error\" | \"warning\" | \"info\";\n readonly message: string;\n}\n\nexport interface LeanToolchain {\n /** The `lean` executable to run, with the arguments that select the pinned toolchain. */\n readonly command: string;\n readonly args: readonly string[];\n readonly version: string;\n}\n\nfunction run(\n command: string,\n args: readonly string[],\n options: { readonly cwd?: string; readonly timeoutMs: number },\n): Promise<LeanRun> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawn>;\n try {\n // Its own process group, so a timeout kills `lean` under `elan run`, not just elan.\n child = spawn(command, args, {\n cwd: options.cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n } catch (err) {\n resolve({ code: null, stdout: \"\", stderr: String(err), timedOut: false });\n return;\n }\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n try {\n if (process.platform !== \"win32\" && child.pid !== undefined)\n process.kill(-child.pid, \"SIGKILL\");\n else child.kill(\"SIGKILL\");\n } catch {\n child.kill(\"SIGKILL\");\n }\n }, options.timeoutMs);\n child.stdout?.on(\"data\", (d: Buffer) => {\n stdout += d.toString();\n });\n child.stderr?.on(\"data\", (d: Buffer) => {\n stderr += d.toString();\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ code: null, stdout, stderr: `${stderr}${String(err)}`, timedOut });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n });\n}\n\n/** Candidates for the `elan` and `lean` executables: the PATH, then elan's default home. */\nfunction candidates(name: string): string[] {\n const home = process.env[\"ELAN_HOME\"] ?? join(homedir(), \".elan\");\n return [name, join(home, \"bin\", name)];\n}\n\n/**\n * The pinned toolchain if it is installed: the one `eutaxy prover install\n * lean` put in the cache, when it answers with the pinned version; else\n * through `elan run <toolchain>` when elan is present (and only when it\n * already has the toolchain, so nothing is downloaded); else a bare `lean`\n * of exactly that version.\n */\nexport async function findLean(\n h: Host = host(),\n): Promise<LeanToolchain | { readonly unavailable: string }> {\n let cached: string | undefined;\n const fromCache = installed(leanDownloads, h);\n if (fromCache) {\n const v = await run(fromCache.executable, [\"--version\"], { timeoutMs: 20_000 });\n const m = /Lean \\(version ([^,]+),/.exec(v.stdout);\n if (v.code === 0 && m?.[1] === leanVersion)\n return { command: fromCache.executable, args: [], version: leanVersion };\n cached = `the toolchain in ${fromCache.dir} did not answer as Lean ${leanVersion} (delete it and run: eutaxy prover install lean)`;\n }\n for (const elan of candidates(\"elan\")) {\n const list = await run(elan, [\"toolchain\", \"list\"], { timeoutMs: 20_000 });\n if (list.code !== 0) continue;\n if (!list.stdout.split(\"\\n\").some((l) => l.trim().split(\" \")[0] === leanToolchain))\n return {\n unavailable: `elan has no ${leanToolchain}; ${installHint}${cached ? `; ${cached}` : \"\"}`,\n };\n return { command: elan, args: [\"run\", leanToolchain, \"lean\"], version: leanVersion };\n }\n for (const lean of candidates(\"lean\")) {\n const v = await run(lean, [\"--version\"], { timeoutMs: 20_000 });\n if (v.code !== 0) continue;\n const m = /Lean \\(version ([^,]+),/.exec(v.stdout);\n if (m?.[1] === leanVersion) return { command: lean, args: [], version: leanVersion };\n return {\n unavailable: `lean ${m?.[1] ?? \"of unknown version\"} found, but the engine is pinned to ${leanVersion}; ${installHint}${cached ? `; ${cached}` : \"\"}`,\n };\n }\n return { unavailable: `no Lean toolchain found; ${installHint}${cached ? `; ${cached}` : \"\"}` };\n}\n\n/** Parse Lean's diagnostics for the one file it was given. */\n/**\n * Lean's messages from `--json` output: one object per line, each with\n * its position. Lines that are not such an object (whatever a program\n * writes to the terminal) are not messages and are skipped, so nothing in\n * the checked file can pose as a message at a position it is not at.\n */\nexport function jsonDiagnostics(output: string): LeanDiagnostic[] {\n const out: LeanDiagnostic[] = [];\n for (const raw of output.split(\"\\n\")) {\n if (!raw.startsWith(\"{\")) continue;\n let m: { pos?: { line?: unknown; column?: unknown }; severity?: unknown; data?: unknown };\n try {\n m = JSON.parse(raw) as typeof m;\n } catch {\n continue;\n }\n const severity =\n m.severity === \"error\"\n ? \"error\"\n : m.severity === \"warning\"\n ? \"warning\"\n : m.severity === \"information\"\n ? \"info\"\n : undefined;\n if (severity === undefined || typeof m.pos?.line !== \"number\" || typeof m.data !== \"string\")\n continue;\n out.push({\n line: m.pos.line,\n column: typeof m.pos.column === \"number\" ? m.pos.column : 0,\n severity,\n message: m.data.trimEnd(),\n });\n }\n return out;\n}\n\nexport function diagnostics(output: string): LeanDiagnostic[] {\n const out: LeanDiagnostic[] = [];\n const re = /^(?:.*?):(\\d+):(\\d+): (error|warning|info): (.*)$/;\n let current:\n | { line: number; column: number; severity: LeanDiagnostic[\"severity\"]; lines: string[] }\n | undefined;\n const flush = (c: NonNullable<typeof current>) =>\n out.push({\n line: c.line,\n column: c.column,\n severity: c.severity,\n message: c.lines.join(\"\\n\").trimEnd(),\n });\n for (const raw of output.split(\"\\n\")) {\n const m = re.exec(raw);\n if (m) {\n if (current) flush(current);\n current = {\n line: Number(m[1]),\n column: Number(m[2]),\n severity: m[3] as LeanDiagnostic[\"severity\"],\n lines: [m[4] as string],\n };\n } else if (current) current.lines.push(raw);\n }\n if (current) flush(current);\n return out;\n}\n\nexport interface CheckedFile {\n readonly run: LeanRun;\n readonly diagnostics: readonly LeanDiagnostic[];\n}\n\n/** Write the source to a scratch directory pinned to the toolchain and check it. */\nexport async function checkLean(\n toolchain: LeanToolchain,\n source: string,\n options: { readonly timeoutMs?: number; readonly keep?: boolean } = {},\n): Promise<CheckedFile> {\n const dir = mkdtempSync(join(tmpdir(), \"eutaxy-lean-\"));\n try {\n writeFileSync(join(dir, \"lean-toolchain\"), `${leanToolchain}\\n`);\n writeFileSync(join(dir, \"Eutaxy.lean\"), source);\n const result = await run(toolchain.command, [...toolchain.args, \"--json\", \"Eutaxy.lean\"], {\n cwd: dir,\n timeoutMs: options.timeoutMs ?? 120_000,\n });\n return { run: result, diagnostics: jsonDiagnostics(`${result.stdout}\\n${result.stderr}`) };\n } finally {\n if (!options.keep) rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * Proofs supplied beside a spec file, for claims the engine's tactic\n * script does not close: `domain.props.lean` beside `domain.props.ts`.\n * Lemmas come first; then each `-- proof: <property>` line opens the\n * tactic proof of that property's statement, which Eutaxy emits and the\n * proof cannot change (it is fixed as a definition before any supplied\n * text). Lean's kernel checks the proof, and Eutaxy accepts it only when\n * it rests on Lean's standard axioms; what could switch checking off, add\n * an axiom or change how the statement reads is refused outright.\n */\n\nexport interface SuppliedProofs {\n /** The proof file's name, for verdicts. */\n readonly file: string;\n /** Everything before the first `-- proof:` line: lemmas the proofs use. */\n readonly lemmas: string;\n /** Each property's tactic proof, by property name (the names also when the file is refused). */\n readonly proofs: ReadonlyMap<string, string>;\n /** Why the file is refused, when it is; then none of its proofs is used, and its properties say why. */\n readonly refused?: string;\n /** The SHA-256 of the module source the proofs were written for, when the file says (a goal file does). */\n readonly sourceSha256?: string;\n /** The SHA-256 of the spec file the proofs were written for, when the file says. */\n readonly specSha256?: string;\n}\n\n/** The lines a goal file carries, and a proof file copied from one keeps, tying the proofs to the files they were written for. */\nexport const sourceHashMarker = \"-- eutaxy-source-sha256: \";\nexport const specHashMarker = \"-- eutaxy-spec-sha256: \";\n\n/** The axioms a supplied proof may rest on: Lean's standard ones. */\nexport const standardAxioms: ReadonlySet<string> = new Set([\n \"propext\",\n \"Classical.choice\",\n \"Quot.sound\",\n]);\n\n/**\n * Words a supplied proof may not use, anywhere in the file, comments and\n * strings included: what adds axioms or trusted code (`axiom`, `sorry`,\n * `unsafe`, `implemented_by`, `extern`, `opaque`, `native_decide`),\n * switches checks off (`set_option`), registers code Lean would run while\n * the file is checked (`attribute`, `initialize`, `simproc` and the like)\n * or changes how text reads (`macro`, `syntax`, `notation` and the like),\n * and `import`. The list narrows when a legitimate proof is refused and\n * grows only with a Lean bump that adds such a command (see\n * `leanToolchain`); never because of what a hostile file could do, which\n * the design answers.\n */\nconst refusedWords = [\n \"sorry\",\n \"admit\",\n \"axiom\",\n \"unsafe\",\n \"implemented_by\",\n \"extern\",\n \"opaque\",\n \"native_decide\",\n \"set_option\",\n \"macro\",\n \"macro_rules\",\n \"syntax\",\n \"notation\",\n \"infix\",\n \"infixl\",\n \"infixr\",\n \"prefix\",\n \"postfix\",\n \"elab\",\n \"elab_rules\",\n \"import\",\n \"attribute\",\n \"initialize\",\n \"simproc\",\n \"dsimproc\",\n \"simproc_decl\",\n \"dsimproc_decl\",\n // Section variables become hypotheses of the theorems after them: `variable (h : False)` would.\n \"section\",\n \"namespace\",\n \"variable\",\n \"include\",\n \"omit\",\n \"universe\",\n];\n\n/** Command families refused by how a word starts: `run_cmd`, `builtin_initialize`, `register_option`, `declare_syntax_cat`. */\nconst refusedStarts = [\"run_\", \"builtin_\", \"register_\", \"declare_\"];\n\n/**\n * Refused wherever they appear, inside a name too: every command run\n * while the file is checked starts with `#`, and every attribute (which\n * can hand Lean a tactic, an elaborator or a simplification procedure to\n * run) with `@[`.\n */\nconst refusedAnywhere = [\"#\", \"@[\"];\n\n/** Lean's ASCII identifier characters after the first. */\nconst identRest = /[A-Za-z0-9_'!?]/u;\n\n/**\n * Whether the text just before `at` continues a name, so that a word\n * starting there is part of that name rather than a token of its own.\n * Only a run of identifier characters that starts with an ASCII letter or\n * `_` counts: one that starts with a digit is a numeral, and Lean starts a\n * new token right after a numeral (`0xfsorry` is `0xf`, then `sorry`).\n * Anything else (`.`, `«`, Unicode) counts as a boundary, which refuses\n * more, never less.\n */\nfunction continuesName(text: string, at: number): boolean {\n let i = at;\n while (i > 0 && identRest.test(text[i - 1] as string)) i--;\n return i < at && /[A-Za-z_]/u.test(text[i] as string);\n}\n\n/** The first refused word or command the text holds, as a token of its own, or undefined. */\nexport function refusedIn(text: string): string | undefined {\n const anywhere = refusedAnywhere.find((w) => text.includes(w));\n if (anywhere !== undefined) return anywhere;\n for (const [words, whole] of [\n [refusedWords, true],\n [refusedStarts, false],\n ] as const) {\n for (const w of words) {\n for (let at = text.indexOf(w); at >= 0; at = text.indexOf(w, at + 1)) {\n if (continuesName(text, at)) continue;\n // A whole word followed by an identifier character is a longer name, which Lean reads as one.\n if (whole && identRest.test(text[at + w.length] ?? \"\")) continue;\n return w;\n }\n }\n }\n return undefined;\n}\n\n/** `-- proof: <property>`: any name the spec file can export, Unicode letters included. */\nconst marker = /^-- proof: (\\S+)\\s*$/u;\n\n/** Read a proof file: its lemmas, its proofs by property, or why it is refused. */\nexport function readSupplied(file: string, text: string): SuppliedProofs {\n const lemmas: string[] = [];\n const proofs = new Map<string, string[]>();\n let current: string[] = lemmas;\n let twice: string | undefined;\n for (const line of text.split(\"\\n\")) {\n const m = marker.exec(line);\n if (!m) {\n current.push(line);\n continue;\n }\n const name = m[1] as string;\n twice ??= proofs.has(name) ? name : undefined;\n current = [];\n proofs.set(name, current);\n }\n if (twice !== undefined) return refuse({ file, proofs }, `${file} proves ${twice} twice`);\n // Checked over the whole text, comments and strings too: telling them apart is lexing Lean, and a\n // lexer that slips (`\"/-\"` in a string read as a comment) would let a refused command through. A\n // refused word in a comment refuses the file as well, which costs a word, never soundness.\n const word = refusedIn(text);\n if (word !== undefined)\n return refuse(\n { file, proofs },\n `${file} uses ${word}, which a supplied proof may not (it could add an axiom, switch a check off, run code while the file is checked or change how the statement reads)`,\n );\n const hashLine = (marker: string): string | undefined => {\n const line = lemmas.find((l) => l.startsWith(marker));\n const hex = line?.slice(marker.length).trim();\n return hex !== undefined && /^[0-9a-f]{64}$/.test(hex) ? hex : undefined;\n };\n const sourceSha256 = hashLine(sourceHashMarker);\n const specSha256 = hashLine(specHashMarker);\n return {\n file,\n lemmas: lemmas.join(\"\\n\").trim(),\n proofs: new Map([...proofs].map(([k, v]) => [k, v.join(\"\\n\").replace(/\\s+$/, \"\")])),\n ...(sourceSha256 === undefined ? {} : { sourceSha256 }),\n ...(specSha256 === undefined ? {} : { specSha256 }),\n };\n}\n\n/** The file refused: none of its proofs is used, and every property it names says why. */\nexport function refuse(\n supplied: { readonly file: string; readonly proofs: ReadonlyMap<string, unknown> },\n reason: string,\n): SuppliedProofs {\n return {\n file: supplied.file,\n lemmas: \"\",\n proofs: new Map([...supplied.proofs.keys()].map((k) => [k, \"\"])),\n refused: reason,\n };\n}\n\n/** Lean's messages at one line: an audit is read only when Lean's own message is the only one there. */\nfunction onlyAt(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n): string | undefined {\n const at = messages.filter((m) => m.line === line);\n return at.length === 1 && at[0]?.severity === \"info\" ? at[0].message : undefined;\n}\n\n/**\n * The axioms Lean reports a theorem depends on: the message of the\n * `#print axioms` at `line`, Eutaxy's own audit command, and no other.\n * Undefined unless that message is the only one at the line: anything\n * else there (a forged copy, printed by code the file ran) makes the\n * audit unreadable rather than letting either message stand.\n */\nexport function axiomsOf(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n theorem: string,\n): string[] | undefined {\n const message = onlyAt(messages, line);\n if (message === undefined) return undefined;\n if (message === `'${theorem}' does not depend on any axioms`) return [];\n const prefix = `'${theorem}' depends on axioms: [`;\n if (message.startsWith(prefix) && message.endsWith(\"]\"))\n return message\n .slice(prefix.length, -1)\n .split(\",\")\n .map((x) => x.trim())\n .filter((x) => x.length > 0);\n return undefined;\n}\n\n/**\n * Whether Lean's message at the `#check` of a supplied theorem shows it\n * proves exactly its fixed statement `s_<name>`: no hypothesis added (a\n * section variable would show as `False → …`).\n */\nexport function provesExactly(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n theorem: string,\n): boolean {\n return onlyAt(messages, line) === `${theorem} : s_${theorem}`;\n}\n","/**\n * The goal file: the properties the tactic script gave up on, each with\n * the statement Lean was asked to prove, written in the form of the proof\n * file the engine accepts (`domain.props.lean`) with every proof left\n * open. A coding agent copies it beside the spec file, puts lemmas above\n * the proofs and tactics under them, and the engine checks them as it\n * checks any supplied proof: nothing new is trusted. The hashes tie the\n * proofs to the module and the spec they were written for; the engine\n * calls a proof file stale once either changed.\n */\n\nimport type { OpenGoal } from \"@eutaxy/prover\";\nimport { ident } from \"./emit.ts\";\nimport { leanVersion } from \"./lean.ts\";\nimport { refusedIn, sourceHashMarker, specHashMarker } from \"./supplied.ts\";\n\nexport interface GoalFileInput {\n /** The spec file's name, for the header: `domain.props.ts`. */\n readonly specFile: string;\n readonly sourceSha256: string;\n readonly specSha256: string;\n readonly goals: readonly OpenGoal[];\n}\n\n/** The proof file's name beside a spec file: `domain.props.lean` for `domain.props.ts`. */\nexport function proofFileFor(specFile: string): string {\n return specFile.replace(/\\.ts$/, \".lean\");\n}\n\n/** The goal file's name beside a spec file: `domain.props.goals.lean` for `domain.props.ts`. */\nexport function goalFileFor(specFile: string): string {\n return specFile.replace(/\\.ts$/, \".goals.lean\");\n}\n\n/** A line of generated commentary: one a proof file may hold, or a note that it was left out. */\nconst commentLine = (text: string): string =>\n refusedIn(text) === undefined\n ? text\n : \"-- (a line left out: it held a word a proof file may not use)\";\n\nconst comment = (text: string): string =>\n text\n .split(\"\\n\")\n .map((l) => commentLine(l.length > 0 ? `-- ${l}` : \"--\"))\n .join(\"\\n\");\n\n/**\n * Render the goal file: the header with the hashes, each goal described\n * in comments (the proof file's lemma area, where comments cost nothing),\n * then one open `-- proof:` part per goal at the end, since everything\n * after a `-- proof:` line belongs to that proof. The text avoids every\n * word a supplied proof may not use, so the file copied as is reads as a\n * proof file with open proofs: every generated line is checked, and one\n * that would refuse the file (a reason Lean gave, a file or function name\n * that is itself a refused word) is left out, with a note in its place.\n * The function is named by its Lean identifier, as the statement names it.\n */\nexport function renderGoals(input: GoalFileInput): string {\n const header = [\n `-- Open proof goals for ${input.specFile}, written by Eutaxy's Lean engine (Lean ${leanVersion}).`,\n \"-- Each goal below is a property the tactic script could not close, with the statement Eutaxy\",\n \"-- emits for it. To supply proofs, copy this file to\",\n `-- ${proofFileFor(input.specFile)} beside the spec file, put lemmas above the \\`-- proof:\\` lines and`,\n \"-- tactics under each, and run the engine again (eutaxy report --prover lean). The hashes tie the\",\n \"-- proofs to these versions of the module and the spec: once either changes, the proofs are stale\",\n \"-- until the goals are written again.\",\n `${sourceHashMarker}${input.sourceSha256}`,\n `${specHashMarker}${input.specSha256}`,\n ];\n const described = input.goals.map((g) =>\n [\n commentLine(`-- goal: ${g.property}, a property of ${ident.fn(g.function)}`),\n commentLine(`-- Lean said: ${g.reason}`),\n \"-- statement:\",\n comment(g.statement.replace(/^/gm, \" \")),\n ].join(\"\\n\"),\n );\n const open = input.goals.map((g) => `-- proof: ${g.property}\\n -- tactics here`);\n return `${[header.map(commentLine).join(\"\\n\"), ...described, ...open].join(\"\\n\\n\")}\\n`;\n}\n","/**\n * The engine: a module's functions through the subset reader, the emitter\n * and Lean, and each property's outcome back. One Lean run per module;\n * errors are mapped to theorems by line, so one failed proof does not hide\n * another. A proof that fails is `gave_up` (the engine is weak or the\n * claim is false; Lean does not say which), a function or property outside\n * the subset is `unsupported`, and no pinned toolchain is `unavailable`.\n * `total` is proved by Lean accepting the definition.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport type {\n ModuleProofs,\n OpenGoal,\n ProofOutcome,\n PropertyProof,\n Prover,\n ProveInput as ProverInput,\n} from \"@eutaxy/prover\";\nimport {\n builtinsAssumption,\n children,\n type Expr,\n listKinds,\n OutsideSubset,\n readSubset,\n restrictModule,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n} from \"@eutaxy/prover/reader\";\nimport type { FunctionSpec, Property, SpecError, SpecType } from \"@eutaxy/spec\";\nimport { dividesOutside, divisionOutside, type Emitted, emitModule, stated } from \"./emit.ts\";\nimport { checkLean, findLean, type LeanDiagnostic, leanVersion } from \"./lean.ts\";\nimport {\n axiomsOf,\n provesExactly,\n readSupplied,\n refuse,\n type SuppliedProofs,\n standardAxioms,\n} from \"./supplied.ts\";\n\nexport const engineName = \"lean\";\n\n/** The types this engine translates: the integers, Bool, String and records of those. */\nexport const leanTakes = (t: SubsetType): boolean =>\n t.kind === \"int\" ||\n t.kind === \"bool\" ||\n t.kind === \"string\" ||\n t.kind === \"record\" ||\n (t.kind === \"list\" && leanTakes(t.element));\n\nexport type { ModuleProofs, ProofOutcome, PropertyProof } from \"@eutaxy/prover\";\n\nexport interface ProveInput extends ProverInput {\n /** Extra Lean lines appended after the theorems (translation checks). */\n readonly extra?: readonly string[];\n}\n\n/** This engine's report, with the Lean it checked. */\nexport interface LeanModuleProofs extends ModuleProofs {\n /** The Lean source checked, when any function was in the subset. */\n readonly lean?: string;\n}\n\n/** What every PROVEN verdict of this engine rests on. */\nexport const engineAssumptions: readonly string[] = [\n \"number is modelled as the unbounded integers: no overflow, no fractions, no NaN\",\n \"string is modelled as Lean's String, a sequence of Unicode characters: a lone surrogate, which a JavaScript string can hold, is outside every string binder's domain\",\n \"the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled\",\n builtinsAssumption,\n `the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`,\n];\n\n/** What a PROVEN over arrays rests on besides: the list model. */\nexport const listAssumption =\n \"an array is modelled as a Lean List, dense: a sparse array, whose holes JavaScript's array methods skip, is outside every array binder's domain\";\n\n/** What a PROVEN that unfolds a recursive function rests on besides: that the JavaScript returns. */\nexport const recursionAssumption =\n \"a recursive function is modelled as returning on every input: JavaScript's call stack is bounded, so on a long enough list the code throws (RangeError) where the model returns\";\n\nconst proven: Extract<ProofOutcome, { kind: \"PROVEN\" }> = {\n kind: \"PROVEN\",\n engine: { name: engineName, version: leanVersion },\n assumptions: engineAssumptions,\n};\n\nconst unknown = (\n cause: \"gave_up\" | \"unsupported\" | \"unavailable\",\n reason: string,\n): ProofOutcome => ({\n kind: \"UNKNOWN\",\n cause,\n reason,\n});\n\n/** Every property of the functions, with one outcome. */\nfunction allWith(fns: readonly FunctionSpec[], outcome: ProofOutcome): PropertyProof[] {\n return fns.flatMap((fn) =>\n fn.properties.map((property) => ({ function: fn.name, property: property.name, outcome })),\n );\n}\n\n/** The emitted Lean for the module's functions in the subset, and the functions with specs outside it with why. */\nexport interface Prepared {\n readonly module: SubsetModule;\n /** The proofs supplied beside the spec file, when there is a proof file. */\n readonly supplied?: SuppliedProofs;\n readonly emitted: Emitted;\n /** The functions to report on. */\n readonly fns: readonly FunctionSpec[];\n /** Those of them the subset does not take, with the reason. */\n readonly outside: ReadonlyMap<string, string>;\n /** Specs that did not read. */\n readonly specErrors: readonly SpecError[];\n}\n\n/**\n * Read and emit. Every function the subset takes is emitted (callees\n * included); properties are stated for the ones with specs among them.\n */\nexport function prepare(input: ProveInput): Prepared {\n const specs = input.specs;\n const wanted = input.functions ? new Set(input.functions) : undefined;\n const fns = specs.functions.filter((f) => !wanted || wanted.has(f.name));\n // Nullable types and tagged unions are read, but this engine does not take them yet: the SMT engine does.\n // Division leaves the integers this engine models, except as Math.floor(x / c).\n const module = restrictModule(\n restrictModule(\n readSubset(\n input.source,\n fns.map((f) => f.name),\n input.modulePath === undefined ? {} : { path: input.modulePath },\n ),\n leanTakes,\n \"nullable types and tagged unions are not in the Lean engine's subset yet\",\n ),\n () => true,\n divisionOutside,\n new Set(),\n dividesOutside,\n );\n const outside = new Map<string, string>();\n for (const o of module.outside)\n if (fns.some((f) => f.name === o.name))\n outside.set(\n o.name,\n `outside the engine's subset${o.line > 0 ? ` (line ${o.line})` : \"\"}: ${o.message}`,\n );\n // A spec belongs to one declaration: the one the reader found at that offset. A nested function (in a\n // namespace, say) named like a top-level one must not lend its properties to the top-level body.\n for (const fn of fns) {\n const read = module.functions.find((f) => f.name === fn.name);\n if (read && read.offset !== fn.offset)\n outside.set(\n fn.name,\n `outside the engine's subset (line ${fn.line}): the ${fn.name} the spec names is not the module's top-level declaration of that name (line ${read.line})`,\n );\n }\n const properties: { function: string; property: Property }[] = fns\n .filter((fn) => !outside.has(fn.name))\n .flatMap((fn) =>\n fn.properties\n .filter((p) => p.kind === \"forall\")\n .map((property) => ({ function: fn.name, property })),\n );\n const specErrors = specs.errors;\n // Proofs supplied beside the spec file: `domain.props.lean` beside `domain.props.ts`. A file that\n // names the hashes of the source and spec it was written for (a goal file does) is stale once either\n // changed: its proofs are not used, and its properties say so, rather than failing one by one on a\n // statement that moved under them.\n const proofFile = input.specPath?.replace(/\\.ts$/, \".lean\");\n let supplied =\n proofFile !== undefined && existsSync(proofFile)\n ? readSupplied(basename(proofFile), readFileSync(proofFile, \"utf8\"))\n : undefined;\n if (supplied && !supplied.refused) {\n const stale = staleness(supplied, input);\n if (stale !== undefined) supplied = refuse(supplied, stale);\n }\n try {\n return {\n module,\n ...(supplied ? { supplied } : {}),\n emitted: emitModule(\n module,\n properties,\n input.extra,\n supplied && !supplied.refused ? supplied : undefined,\n ),\n fns,\n outside,\n specErrors,\n };\n } catch (err) {\n // The emitter refusing something the reader let through is an engine gap: every function is unsupported, none guessed.\n if (!(err instanceof OutsideSubset)) throw err;\n for (const fn of fns) outside.set(fn.name, `outside the engine's subset: ${err.message}`);\n const empty: Emitted = { source: \"\", theorems: [], skipped: [] };\n return { module, emitted: empty, fns, outside, specErrors };\n }\n}\n\nconst sha256 = (text: string): string => createHash(\"sha256\").update(text).digest(\"hex\");\n\n/** Why a proof file is stale, when it names the hashes of the files it was written for and either moved. */\nfunction staleness(supplied: SuppliedProofs, input: ProveInput): string | undefined {\n const moved: string[] = [];\n if (supplied.sourceSha256 !== undefined && supplied.sourceSha256 !== sha256(input.source))\n moved.push(\"the module\");\n if (\n supplied.specSha256 !== undefined &&\n input.specPath !== undefined &&\n existsSync(input.specPath)\n ) {\n if (supplied.specSha256 !== sha256(readFileSync(input.specPath, \"utf8\")))\n moved.push(\"the spec file\");\n }\n if (moved.length === 0) return undefined;\n return `${supplied.file} is stale: ${moved.join(\" and \")} changed since its proofs were written (the hashes it names no longer match); write the goals again and bring the proofs over`;\n}\n\n/**\n * A supplied proof's outcome: given up on when its lemmas or its tactics\n * do not compile, or when it rests on an axiom beyond Lean's standard\n * ones (`sorry` is one); PROVEN otherwise, saying it was supplied.\n */\nfunction suppliedOutcome(\n file: string,\n error: LeanDiagnostic | undefined,\n axioms: readonly string[] | undefined,\n exact: boolean,\n assumptions: readonly string[],\n): ProofOutcome {\n if (error)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} does not close: ${error.message.split(\"\\n\")[0]}`,\n );\n if (!exact)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} proves more hypotheses than its statement has (a section variable?), or Lean did not report its type`,\n );\n if (axioms === undefined)\n return unknown(\"gave_up\", `Lean did not report the axioms of the proof supplied in ${file}`);\n const beyond = axioms.filter((a) => !standardAxioms.has(a));\n if (beyond.length > 0)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} rests on ${beyond.join(\", \")}, beyond Lean's standard axioms`,\n );\n return {\n ...proven,\n assumptions: [\n ...assumptions,\n `the proof was supplied in ${file}, not found by the engine's tactic script; Lean's kernel checked it against the statement Eutaxy emitted, and it rests on no axioms beyond propext, Classical.choice and Quot.sound`,\n ],\n };\n}\n\n/** Prove a module's properties with the pinned Lean. */\nexport async function proveModule(input: ProveInput): Promise<LeanModuleProofs> {\n const { module, emitted, fns, outside, specErrors, supplied } = prepare(input);\n const inSubset = fns.filter((f) => !outside.has(f.name));\n const unsupported = fns\n .filter((f) => outside.has(f.name))\n .flatMap((f) =>\n f.properties.map((property) => ({\n function: f.name,\n property: property.name,\n outcome: unknown(\"unsupported\", outside.get(f.name) as string),\n })),\n );\n if (inSubset.length === 0) return { results: unsupported, specErrors };\n const lean = emitted.source;\n const rest = (outcome: ProofOutcome): LeanModuleProofs => ({\n results: [...unsupported, ...allWith(inSubset, outcome)],\n lean,\n specErrors,\n });\n const toolchain = await findLean();\n if (\"unavailable\" in toolchain) return rest(unknown(\"unavailable\", toolchain.unavailable));\n const timeoutMs = input.timeoutMs ?? 120_000;\n const checked = await checkLean(toolchain, lean, { timeoutMs });\n if (checked.run.timedOut)\n return rest(unknown(\"gave_up\", `Lean did not finish within ${timeoutMs} ms`));\n const errors = checked.diagnostics.filter((d) => d.severity === \"error\");\n const inTheorem = (d: LeanDiagnostic) =>\n emitted.theorems.find((t) => d.line >= t.from && d.line <= t.to);\n if (checked.run.code === null || (checked.run.code !== 0 && errors.length === 0))\n return rest(\n unknown(\n \"unavailable\",\n `Lean could not be run: ${checked.run.stderr.trim() || `exit ${checked.run.code}`}`,\n ),\n );\n const inLemmas = (d: LeanDiagnostic) =>\n emitted.lemmas !== undefined && d.line >= emitted.lemmas.from && d.line <= emitted.lemmas.to;\n const lemmaErrors = errors.filter(inLemmas);\n const elsewhere = errors.filter((d) => !inTheorem(d) && !inLemmas(d));\n if (elsewhere.length > 0) {\n // The emitted definitions themselves did not compile: an engine gap, never a verdict on the property.\n const where = elsewhere.map((d) => `line ${d.line}: ${d.message.split(\"\\n\")[0]}`).join(\"; \");\n return rest(unknown(\"unsupported\", `the emitted Lean did not compile: ${where}`));\n }\n const results: PropertyProof[] = [...unsupported];\n for (const fn of inSubset) {\n for (const property of fn.properties) {\n if (property.kind === \"total\") {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: {\n ...proven,\n assumptions: [\n ...engineAssumptions,\n ...modelAssumptions(property, fn.name, module),\n \"Lean accepted the definition, so it terminates on every input\",\n ],\n },\n });\n continue;\n }\n const skipped = emitted.skipped.find(\n (s) => s.function === fn.name && s.property === property.name,\n );\n if (skipped) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"unsupported\", skipped.reason),\n });\n continue;\n }\n if (supplied?.refused && supplied.proofs.has(property.name)) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"gave_up\", supplied.refused),\n });\n continue;\n }\n const theorem = emitted.theorems.find(\n (t) => t.function === fn.name && t.property === property.name,\n );\n const failed = theorem\n ? errors.filter((d) => d.line >= theorem.from && d.line <= theorem.to)\n : [];\n if (theorem?.supplied && supplied) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: suppliedOutcome(\n supplied.file,\n lemmaErrors[0] ?? failed[0],\n axiomsOf(checked.diagnostics, theorem.axiomsLine ?? 0, theorem.name),\n provesExactly(checked.diagnostics, theorem.typeLine ?? 0, theorem.name),\n [...engineAssumptions, ...modelAssumptions(property, fn.name, module)],\n ),\n });\n continue;\n }\n results.push({\n function: fn.name,\n property: property.name,\n outcome:\n failed.length === 0\n ? {\n ...proven,\n assumptions: [...engineAssumptions, ...modelAssumptions(property, fn.name, module)],\n }\n : unknown(\n \"gave_up\",\n `Lean could not close the proof: ${(failed[0] as LeanDiagnostic).message.split(\"\\n\")[0]}`,\n ),\n });\n }\n }\n // The open goals: every forall property given up on, with the statement Lean was asked to prove. The\n // list is present, empty or not, only here, where Lean answered; a timeout or an engine gap above\n // returns without it, so no one takes \"no answer\" for \"no open goals\".\n const goals: OpenGoal[] = [];\n for (const fn of inSubset)\n for (const property of fn.properties) {\n if (property.kind !== \"forall\") continue;\n const r = results.find((x) => x.function === fn.name && x.property === property.name);\n if (r?.outcome.kind !== \"UNKNOWN\" || r.outcome.cause !== \"gave_up\") continue;\n goals.push({\n function: fn.name,\n property: property.name,\n statement: stated(property, module).text,\n reason: r.outcome.reason,\n });\n }\n return { results, lean, specErrors, goals };\n}\n\n/** The engine as a `Prover`: available when the pinned toolchain is installed. */\nexport const leanProver: Prover = {\n name: engineName,\n async available() {\n const toolchain = await findLean();\n return \"unavailable\" in toolchain ? toolchain : { version: toolchain.version };\n },\n prove: (input) => proveModule(input),\n};\n\n/** The list and recursion models a proof rests on, where its claim may meet them. */\nfunction modelAssumptions(property: Property, fn: string, module: SubsetModule): string[] {\n // The module functions this claim's own arrows name, by the spec file's names for them: named at\n // all, called or not, so `(sum)(xs)` counts; a disclosure may err only toward saying more.\n const arrows = [property.when?.body ?? \"\", property.ensures?.body ?? \"\"].join(\"\\n\");\n const called = property.imports.filter((i) =>\n new RegExp(`(^|[^\\\\w$])${i.local.replace(/\\$/g, \"\\\\$\")}($|[^\\\\w$])`).test(arrows),\n );\n const roots = [fn, ...called.map((i) => i.fn)];\n return [\n ...(usesLists(property, roots, module) ? [listAssumption] : []),\n ...(reached(roots, module).some((f) => f.structural !== undefined)\n ? [recursionAssumption]\n : []),\n ];\n}\n\n/**\n * The functions a property's claim may unfold: its function, the module\n * functions its arrows call, and, through their calls, everything they\n * reach.\n */\nfunction reached(roots: readonly string[], module: SubsetModule): SubsetFunction[] {\n const byName = new Map(module.functions.map((f) => [f.name, f]));\n const out = new Map<string, SubsetFunction>();\n const visit = (name: string) => {\n const f = byName.get(name);\n if (!f || out.has(name)) return;\n out.set(name, f);\n const walk = (e: Expr): void => {\n if (e.kind === \"call\") visit(e.callee);\n for (const c of children(e)) walk(c);\n };\n walk(f.body);\n };\n for (const r of roots) visit(r);\n return [...out.values()];\n}\n\n/**\n * Whether a list can be in play in a property: a binder whose type holds\n * an array at any depth, or a function the claim may unfold that holds a\n * list in its types (through records too) or builds one.\n */\nfunction usesLists(property: Property, roots: readonly string[], module: SubsetModule): boolean {\n const records = new Map(module.records.map((r) => [r.name, r]));\n const seen = new Set<string>();\n const hasList = (t: SubsetType): boolean => {\n if (t.kind === \"list\") return true;\n if (t.kind === \"nullable\") return hasList(t.inner);\n if (t.kind === \"record\" && !seen.has(t.name)) {\n seen.add(t.name);\n return records.get(t.name)?.fields.some((f) => hasList(f.type)) ?? false;\n }\n return false;\n };\n const hasArray = (t: SpecType): boolean => {\n if (t.kind === \"array\") return true;\n if (t.kind === \"union\") return t.members.some(hasArray);\n if (t.kind === \"record\") return t.fields.some((f) => hasArray(f.type));\n return false;\n };\n const builds = (e: Expr): boolean => listKinds.has(e.kind) || children(e).some(builds);\n // The arrows' own array literals and methods, read from their text: a disclosure may err only toward saying more.\n const arrowLists = [property.when, property.ensures].some(\n (a) => a !== undefined && /\\[|\\.(map|flatMap|every|some|reduce|slice|length)\\b/.test(a.body),\n );\n return (\n property.binders.some((b) => hasArray(b.type)) ||\n arrowLists ||\n reached(roots, module).some(\n (f) => hasList(f.returns) || f.params.some((p) => hasList(p.type)) || builds(f.body),\n )\n );\n}\n","/**\n * SMT-LIB 2 for a module in the subset and the properties on it, as Z3\n * reads it. `number` is the IEEE double (the floating-point theory, so\n * NaN, the infinities and -0 are in every binder's domain and `===` is\n * `fp.eq`, as in JavaScript), `string` a sequence of 16-bit code units,\n * `boolean` Bool, a record a datatype with one constructor, a tagged\n * union a datatype with one constructor per member holding that member's\n * record (so a record may be a member of several unions: a member is\n * wrapped where one of its unions is expected, and unwrapped where a test\n * of the tag narrows the union to it), a nullable type an\n * option datatype (`none`, `some`), with a name narrowed by a null check\n * bound to its value in the branch the check guards. Each property is one\n * script: the definitions, the binders as constants with what their\n * TypeScript types say beyond their sorts, the precondition asserted, the\n * claim's negation asserted, `check-sat`; an `unsat` is a proof, a model\n * is a candidate counterexample. Values in Z3's models are decoded back to\n * JavaScript values by this module too.\n */\n\nimport {\n type Expr,\n isListExpr,\n OutsideSubset,\n type RecordType,\n readArrowBody,\n renameVars,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n type TypeContext,\n typeOf,\n type UnionType,\n} from \"@eutaxy/prover/reader\";\nimport { type Arrow, describeType, type Property, type SpecType } from \"@eutaxy/spec\";\n\nexport const F64 = \"(_ FloatingPoint 11 53)\";\nexport const STR = \"(Seq (_ BitVec 16))\";\n\n/** A name as an SMT-LIB symbol: simple when it can be, quoted with | otherwise. */\nexport function symbol(name: string): string {\n // A quoted symbol may hold anything but `|` and `\\`: those are escaped as `%7c` and `%5c`, with `%`\n // itself as `%25` first, in every name, so two names never meet in one symbol (a quoted symbol and\n // a simple one spelled alike are the same symbol; a record is named as the compiler prints its\n // type, which may spell any of them).\n const escaped = name.replace(/%/g, \"%25\").replace(/\\\\/g, \"%5c\").replace(/\\|/g, \"%7c\");\n return /^[A-Za-z~!@$%^&*_+=<>.?/-][A-Za-z0-9~!@$%^&*_+=<>.?/-]*$/.test(escaped)\n ? escaped\n : `|${escaped}|`;\n}\n\n/** TypeScript names as SMT symbols that cannot clash with each other or with the theories' names. */\nexport const ident = {\n fn: (name: string) => symbol(`f_${name}`),\n /** The datatype of a record, or of a union. */\n record: (name: string) => symbol(`R_${name}`),\n constructor: (name: string) => symbol(`mk_${name}`),\n /** A union's constructor for one member, holding the member's record, and its selector. */\n inject: (union: string, member: string) => symbol(`in.${union}.${member}`),\n project: (union: string, member: string) => symbol(`out.${union}.${member}`),\n // A dot, which no TypeScript identifier holds, so selectors of different records never coincide.\n field: (record: string, field: string) => symbol(`fld.${record}.${field}`),\n variable: (name: string) => symbol(`v_${name}`),\n /** The option datatype over a sort, and its constructors and selector. */\n option: (base: string) => symbol(`Opt.${base}`),\n none: (base: string) => symbol(`none.${base}`),\n some: (base: string) => symbol(`some.${base}`),\n val: (base: string) => symbol(`val.${base}`),\n};\n\n/** The short name a sort has inside option names: `Opt.F64`, `Opt.R_X`. */\nexport function sortName(t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return \"F64\";\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return \"Str\";\n case \"record\":\n case \"union\":\n return ident.record(t.name);\n case \"nullable\":\n return ident.option(sortName(t.inner, module));\n case \"null\":\n return fail(\"null has no sort of its own\");\n }\n}\n\nexport function sort(t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return F64;\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return STR;\n case \"record\":\n case \"union\":\n case \"nullable\":\n return sortName(t, module);\n case \"null\":\n return fail(\"null has no sort of its own\");\n }\n}\n\n/** A constructor applied: a bare symbol when there are no arguments. */\nfunction construct(name: string, values: readonly string[]): string {\n return values.length === 0\n ? ident.constructor(name)\n : `(${ident.constructor(name)} ${values.join(\" \")})`;\n}\n\n/** A double as a floating-point literal. */\nexport function numberTerm(n: number): string {\n if (Number.isNaN(n)) return \"(_ NaN 11 53)\";\n if (n === Number.POSITIVE_INFINITY) return \"(_ +oo 11 53)\";\n if (n === Number.NEGATIVE_INFINITY) return \"(_ -oo 11 53)\";\n if (Object.is(n, -0)) return \"(_ -zero 11 53)\";\n if (n === 0) return \"(_ +zero 11 53)\";\n // Exact bits, so a value round-trips whatever its magnitude.\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, n);\n const bits = view.getBigUint64(0);\n const sign = (bits >> 63n) & 1n;\n const exponent = (bits >> 52n) & 0x7ffn;\n const significand = bits & ((1n << 52n) - 1n);\n return `(fp #b${sign} #b${exponent.toString(2).padStart(11, \"0\")} #b${significand.toString(2).padStart(52, \"0\")})`;\n}\n\n/** A JavaScript string as a sequence of its UTF-16 code units. */\nexport function stringTerm(s: string): string {\n if (s.length === 0) return `(as seq.empty ${STR})`;\n const units: string[] = [];\n for (let i = 0; i < s.length; i++)\n units.push(`(seq.unit #x${s.charCodeAt(i).toString(16).padStart(4, \"0\")})`);\n return units.length === 1 ? (units[0] as string) : `(seq.++ ${units.join(\" \")})`;\n}\n\ninterface Env {\n readonly module: SubsetModule;\n readonly ctx: TypeContext;\n /** Each node's type per scope, computed once: emission asks for types at every level. */\n readonly types: WeakMap<Expr, Map<string, SubsetType>>;\n}\n\nfunction env(module: SubsetModule): Env {\n return {\n module,\n types: new WeakMap(),\n ctx: {\n records: new Map(module.records.map((r) => [r.name, r])),\n signatures: new Map(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n ),\n },\n };\n}\n\n/** Why a list, or an operation on one, is refused here. */\nconst listsOutside = \"arrays are not in this engine's subset (the Lean engine takes them)\";\n\nconst fail: (message: string) => never = (message) => {\n throw new OutsideSubset(message, 0);\n};\n\n/** `Number.isInteger(x)`: finite and equal to its truncation. */\nfunction isIntegerTerm(x: string): string {\n return `(and (not (fp.isNaN ${x})) (not (fp.isInfinite ${x})) (fp.eq ${x} (fp.roundToIntegral RTZ ${x})))`;\n}\n\n/** The members of a union, as records, in declaration order. */\nfunction membersOf(union: string, env: Env): RecordType[] {\n const u = env.module.unions.find((x) => x.name === union) ?? fail(`no union ${union}`);\n return u.members.map((m) => env.ctx.records.get(m.record) ?? fail(`no record ${m.record}`));\n}\n\nconst tester = (constructorSymbol: string): string =>\n constructorSymbol.startsWith(\"|\")\n ? `|is-${constructorSymbol.slice(1)}`\n : `is-${constructorSymbol}`;\n\n/** `===` of two terms of a type, as JavaScript has it. */\nfunction sameAs(a: string, b: string, t: SubsetType, env: Env): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return `(fp.eq ${a} ${b})`;\n case \"bool\":\n case \"string\":\n return `(= ${a} ${b})`;\n case \"nullable\": {\n const base = sortName(t.inner, env.module);\n return `(ite (and (${tester(ident.some(base))} ${a}) (${tester(ident.some(base))} ${b})) ${sameAs(`(${ident.val(base)} ${a})`, `(${ident.val(base)} ${b})`, t.inner, env)} (and (${tester(ident.none(base))} ${a}) (${tester(ident.none(base))} ${b})))`;\n }\n case \"record\":\n case \"union\":\n case \"null\":\n return fail(\"=== on records compares references in JavaScript; compare their fields instead\");\n }\n}\n\n/**\n * A term of type `actual` as a value of type `want`: a member record\n * wrapped in the union's constructor for it, a value wrapped in `some`\n * where a nullable is wanted, a nullable member mapped into the nullable\n * union. Anything else is already of the sort wanted.\n */\nfunction lift(inner: string, actual: SubsetType, want: SubsetType, module: SubsetModule): string {\n if (want.kind === \"union\" && actual.kind === \"record\")\n return `(${ident.inject(want.name, actual.name)} ${inner})`;\n if (want.kind !== \"nullable\") return inner;\n if (actual.kind === \"null\") return inner;\n if (actual.kind === \"nullable\") {\n if (want.inner.kind !== \"union\" || actual.inner.kind !== \"record\") return inner;\n const from = sortName(actual.inner, module);\n const to = sortName(want.inner, module);\n return `(ite (${tester(ident.none(from))} ${inner}) ${ident.none(to)} (${ident.some(to)} ${lift(`(${ident.val(from)} ${inner})`, actual.inner, want.inner, module)}))`;\n }\n return `(${ident.some(sortName(want.inner, module))} ${lift(inner, actual, want.inner, module)})`;\n}\n\n/**\n * A term of the expression's type, or of `expected` where one is given:\n * `null` and a non-null value become the option's constructors where a\n * nullable is expected, and a member record its union's where the union is.\n */\nexport function term(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n env: Env,\n expected?: SubsetType,\n): string {\n const t = (x: Expr, want?: SubsetType) => term(x, scope, env, want);\n if (isListExpr(e)) return fail(listsOutside);\n // A node's type depends on the scope it is typed in (narrowing), so the memo is keyed by both.\n const typed = (x: Expr): SubsetType => {\n const key = JSON.stringify([...scope]);\n let byScope = env.types.get(x);\n if (!byScope) {\n byScope = new Map();\n env.types.set(x, byScope);\n }\n let found = byScope.get(key);\n if (!found) {\n found = typeOf(x, scope, env.ctx, fail);\n byScope.set(key, found);\n }\n return found;\n };\n // A value where `want` is expected: a conditional, a let or a narrowing produce the expected sort\n // themselves; anything else is lifted to it (`lift`).\n const coerceIn = (x: Expr, want: SubsetType, sc: ReadonlyMap<string, SubsetType>): string => {\n if (\n x.kind === \"cond\" ||\n x.kind === \"let\" ||\n x.kind === \"narrow\" ||\n x.kind === \"narrowTag\" ||\n x.kind === \"null\"\n )\n return term(x, sc, env, want);\n const actual = sc === scope ? typed(x) : typeOf(x, sc, env.ctx, fail);\n return lift(term(x, sc, env, want), actual, want, env.module);\n };\n const coerce = (x: Expr, want: SubsetType): string => coerceIn(x, want, scope);\n // A narrowed body is a value where the narrowing stands: coerced to what is expected there.\n const narrowed = (body: Expr, inner: ReadonlyMap<string, SubsetType>): string =>\n expected ? coerceIn(body, expected, inner) : term(body, inner, env);\n switch (e.kind) {\n case \"int\":\n return numberTerm(Number(e.value));\n case \"bool\":\n return e.value ? \"true\" : \"false\";\n case \"string\":\n return stringTerm(e.value);\n case \"null\":\n if (expected?.kind !== \"nullable\") fail(\"null where no nullable type is expected\");\n return ident.none(sortName(expected.inner, env.module));\n case \"var\":\n return ident.variable(e.name);\n case \"narrow\": {\n const nt = scope.get(e.name);\n if (nt?.kind !== \"nullable\") fail(`${e.name} is narrowed but is not a nullable`);\n const base = sortName(nt.inner, env.module);\n const inner = new Map(scope);\n inner.set(e.name, nt.inner);\n return `(let ((${ident.variable(e.name)} (${ident.val(base)} ${ident.variable(e.name)}))) ${narrowed(e.body, inner)})`;\n }\n case \"narrowTag\": {\n // The name is bound to the member's record inside the union's value (the guard the node sits\n // under makes the constructor the right one), typed as the member in the body.\n const nt = scope.get(e.name);\n if (nt?.kind !== \"union\") fail(`${e.name} is narrowed by a tag but is not a union`);\n const inner = new Map(scope);\n inner.set(e.name, { kind: \"record\", name: e.member });\n const v = ident.variable(e.name);\n return `(let ((${v} (${ident.project(nt.name, e.member)} ${v}))) ${narrowed(e.body, inner)})`;\n }\n case \"neg\":\n return `(fp.neg ${t(e.operand)})`;\n case \"not\":\n return `(not ${t(e.operand)})`;\n case \"isInteger\":\n return isIntegerTerm(t(e.operand));\n case \"floor\":\n // Math.floor: toward negative infinity, -0, NaN and the infinities kept, as IEEE 754 rounds.\n return `(fp.roundToIntegral RTN ${t(e.operand)})`;\n case \"binary\": {\n const lt = typed(e.left);\n const rt = typed(e.right);\n switch (e.op) {\n case \"+\":\n return lt.kind === \"string\"\n ? `(seq.++ ${t(e.left)} ${t(e.right)})`\n : `(fp.add RNE ${t(e.left)} ${t(e.right)})`;\n case \"-\":\n return `(fp.sub RNE ${t(e.left)} ${t(e.right)})`;\n case \"*\":\n return `(fp.mul RNE ${t(e.left)} ${t(e.right)})`;\n case \"/\":\n return `(fp.div RNE ${t(e.left)} ${t(e.right)})`;\n case \"<\":\n return `(fp.lt ${t(e.left)} ${t(e.right)})`;\n case \"<=\":\n return `(fp.leq ${t(e.left)} ${t(e.right)})`;\n case \">\":\n return `(fp.gt ${t(e.left)} ${t(e.right)})`;\n case \">=\":\n return `(fp.geq ${t(e.left)} ${t(e.right)})`;\n case \"===\":\n case \"!==\": {\n let eq: string;\n if (lt.kind === \"null\" || rt.kind === \"null\") {\n // Against null: whether the nullable side is none.\n const side = lt.kind === \"null\" ? e.right : e.left;\n const st = lt.kind === \"null\" ? rt : lt;\n if (st.kind !== \"nullable\")\n fail(\"a comparison with null of something that is not nullable\");\n eq = `(${tester(ident.none(sortName(st.inner, env.module)))} ${t(side)})`;\n } else if (lt.kind === \"nullable\" && rt.kind !== \"nullable\") {\n const base = sortName(lt.inner, env.module);\n eq = `(and (${tester(ident.some(base))} ${t(e.left)}) ${sameAs(`(${ident.val(base)} ${t(e.left)})`, t(e.right), lt.inner, env)})`;\n } else if (rt.kind === \"nullable\" && lt.kind !== \"nullable\") {\n const base = sortName(rt.inner, env.module);\n eq = `(and (${tester(ident.some(base))} ${t(e.right)}) ${sameAs(t(e.left), `(${ident.val(base)} ${t(e.right)})`, rt.inner, env)})`;\n } else eq = sameAs(t(e.left), t(e.right), lt, env);\n return e.op === \"===\" ? eq : `(not ${eq})`;\n }\n case \"&&\":\n return `(and ${t(e.left)} ${t(e.right)})`;\n case \"||\":\n return `(or ${t(e.left)} ${t(e.right)})`;\n }\n break;\n }\n case \"cond\": {\n // Both branches of one sort: the expected one, or what the branches share.\n const want = expected ?? typed(e);\n return `(ite ${t(e.test)} ${coerce(e.ifTrue, want)} ${coerce(e.ifFalse, want)})`;\n }\n case \"call\": {\n const sig = env.ctx.signatures.get(e.callee) ?? fail(`no signature for ${e.callee}`);\n const args = e.args.map((a, i) =>\n coerce(a, (sig.params[i] as (typeof sig.params)[number]).type),\n );\n return args.length === 0 ? ident.fn(e.callee) : `(${ident.fn(e.callee)} ${args.join(\" \")})`;\n }\n case \"field\": {\n const o = typed(e.object);\n const obj = t(e.object);\n if (o.kind === \"union\") {\n // The field every member has: read from whichever member the value is.\n const members = membersOf(o.name, env);\n return members.reduceRight<string | undefined>((rest, m) => {\n const read = `(${ident.field(m.name, e.field)} (${ident.project(o.name, m.name)} ${obj}))`;\n return rest === undefined\n ? read\n : `(ite (${tester(ident.inject(o.name, m.name))} ${obj}) ${read} ${rest})`;\n }, undefined) as string;\n }\n if (o.kind !== \"record\") fail(`field ${e.field} read from a ${o.kind}`);\n return `(${ident.field(o.name, e.field)} ${obj})`;\n }\n case \"record\": {\n const type = typed(e);\n if (type.kind !== \"record\") fail(\"a record literal of no record type\");\n const rec = env.ctx.records.get(type.name) ?? fail(`no record ${type.name}`);\n // Fields in the declaration's order, whatever order the literal wrote them in.\n const values = rec.fields.map((f) => {\n const given =\n e.fields.find((x) => x.name === f.name) ?? fail(`${type.name} literal without ${f.name}`);\n return coerce(given.value, f.type);\n });\n return construct(type.name, values);\n }\n case \"let\": {\n const inner = new Map(scope);\n const bound = e.type ?? typed(e.value);\n inner.set(e.name, bound);\n const value = e.type ? coerce(e.value, e.type) : t(e.value);\n // The body is the let's value: lifted to what is expected where the let stands.\n return `(let ((${ident.variable(e.name)} ${value})) ${narrowed(e.body, inner)})`;\n }\n }\n}\n\nexport function emitFunction(f: SubsetFunction, module: SubsetModule): string {\n const e = env(module);\n const scope = new Map(f.params.map((p) => [p.name, p.type]));\n const params = f.params\n .map((p) => `(${ident.variable(p.name)} ${sort(p.type, module)})`)\n .join(\" \");\n // The body as a value of the declared return type (`coerce` is local to `term`; the rule is repeated).\n const body = (() => {\n const b = f.body;\n if (\n b.kind === \"cond\" ||\n b.kind === \"let\" ||\n b.kind === \"narrow\" ||\n b.kind === \"narrowTag\" ||\n b.kind === \"null\"\n )\n return term(b, scope, e, f.returns);\n return lift(term(b, scope, e, f.returns), typeOf(b, scope, e.ctx, fail), f.returns, module);\n })();\n return `(define-fun ${ident.fn(f.name)} (${params}) ${sort(f.returns, module)}\\n ${body})`;\n}\n\n/**\n * An option sort over every sort the module could mention: the primitives,\n * every record, every union. A body may join a\n * value with `null` in a `const` that no signature shows, so nothing is\n * left to discovery.\n */\nfunction optionSorts(module: SubsetModule): Map<string, SubsetType> {\n const out = new Map<string, SubsetType>();\n const bases: SubsetType[] = [\n { kind: \"int\" },\n { kind: \"bool\" },\n { kind: \"string\" },\n ...module.records.map((r): SubsetType => ({ kind: \"record\", name: r.name })),\n ...module.unions.map((u): SubsetType => ({ kind: \"union\", name: u.name })),\n ];\n for (const b of bases) out.set(sortName(b, module), b);\n return out;\n}\n\n/**\n * Every datatype in one declaration, so records, unions and options may\n * refer to one another in any order: a record is one constructor, a union\n * one per member holding its record, an option `none` and `some` over its\n * base sort.\n */\nexport function emitDatatypes(module: SubsetModule): string {\n const plain = module.records;\n const unions = module.unions;\n const options = optionSorts(module);\n const names = [\n ...plain.map((r) => ident.record(r.name)),\n ...unions.map((u) => ident.record(u.name)),\n ...[...options.keys()].map((base) => ident.option(base)),\n ];\n if (names.length === 0) return \"\";\n const constructorOf = (r: RecordType): string =>\n `(${ident.constructor(r.name)}${r.fields.map((f) => ` (${ident.field(r.name, f.name)} ${sort(f.type, module)})`).join(\"\")})`;\n const bodies = [\n ...plain.map((r) => `(${constructorOf(r)})`),\n ...unions.map(\n (u) =>\n `(${u.members.map((m) => `(${ident.inject(u.name, m.record)} (${ident.project(u.name, m.record)} ${ident.record(m.record)}))`).join(\" \")})`,\n ),\n ...[...options].map(\n ([base, inner]) =>\n `((${ident.none(base)}) (${ident.some(base)} (${ident.val(base)} ${sort(inner, module)})))`,\n ),\n ];\n return `(declare-datatypes (${names.map((n) => `(${n} 0)`).join(\" \")}) (${bodies.join(\" \")}))`;\n}\n\n/**\n * The subset type a binder ranges over, or `OutsideSubset`: `number` is\n * the double, a union of string literals is a string (constrained to the\n * literals in the script), a record is the module's datatype of that\n * name, `T | null` the option over `T`, a union of records the declared\n * union whose members match. Bigint and what the reader could not read\n * are outside.\n */\nexport function binderType(name: string, t: SpecType, module: SubsetModule): SubsetType {\n switch (t.kind) {\n case \"number\":\n return { kind: \"int\" };\n case \"boolean\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"literal\":\n if (typeof t.value === \"string\") return { kind: \"string\" };\n if (typeof t.value === \"boolean\") return { kind: \"bool\" };\n return { kind: \"int\" };\n case \"bigint\":\n fail(`binder ${name} over bigint: the subset has no bigint`);\n break;\n case \"union\": {\n const nulls = t.members.filter((m) => m.kind === \"null\");\n if (t.members.some((m) => m.kind === \"undefined\"))\n fail(`binder ${name} over ${describeType(t)}: undefined is not in the subset (null is)`);\n const rest = t.members.filter((m) => m.kind !== \"null\");\n let inner: SubsetType;\n if (rest.every((m) => m.kind === \"literal\" && typeof m.value === \"string\"))\n inner = { kind: \"string\" };\n else if (rest.every((m) => m.kind === \"literal\" && typeof m.value === \"boolean\"))\n inner = { kind: \"bool\" };\n else if (rest.length === 1) inner = binderType(name, rest[0] as SpecType, module);\n else if (rest.every((m) => m.kind === \"record\")) {\n const union = findUnion(rest as readonly Extract<SpecType, { kind: \"record\" }>[], module);\n if (!union)\n fail(\n `binder ${name} over ${describeType(t)}: no one union the module declares has exactly these members`,\n );\n inner = { kind: \"union\", name: union.name };\n } else fail(`binder ${name} over ${describeType(t)}: a union the subset does not read`);\n return nulls.length > 0 ? { kind: \"nullable\", inner } : inner;\n }\n case \"record\":\n if (t.name !== undefined && module.records.some((r) => r.name === t.name))\n return { kind: \"record\", name: t.name };\n fail(\n `binder ${name} over ${describeType(t)}: ${t.name === undefined ? \"an inline record type\" : `record type ${t.name} is outside the subset`}`,\n );\n break;\n case \"null\":\n case \"undefined\":\n fail(`binder ${name} over ${t.kind}`);\n break;\n case \"array\":\n fail(`binder ${name} over ${describeType(t)}: arrays are not in the engine's subset yet`);\n break;\n case \"unknown\":\n fail(`binder ${name} over ${t.text}, which the reader could not read`);\n }\n}\n\n/**\n * The one declared union these member types are, compared field by field\n * and type by type: a field holding one literal is that literal in the\n * union's member, a union of literals is a field of no literal, and\n * everything else reads to the field's own type. A record may be a member\n * of several unions, so tags and field names alone could name the wrong\n * one; when more than one union fits, none is chosen.\n */\nfunction findUnion(\n members: readonly Extract<SpecType, { kind: \"record\" }>[],\n module: SubsetModule,\n): UnionType | undefined {\n const recordOf = (name: string) => module.records.find((r) => r.name === name);\n // A nested record is compared by its fields, not its name: the spec reader and the subset reader\n // may name one inline type differently (`Extract<U, …>` against `U.a`).\n const recordFits = (sm: Extract<SpecType, { kind: \"record\" }>, rec: RecordType): boolean =>\n sm.fields.length === rec.fields.length &&\n rec.fields.every((f) => {\n const sf = sm.fields.find((x) => x.name === f.name);\n return sf !== undefined && fieldFits(sf.type, f);\n });\n const typeFits = (sf: SpecType, t: SubsetType): boolean => {\n if (t.kind === \"record\") {\n const rec = recordOf(t.name);\n return sf.kind === \"record\" && rec !== undefined && recordFits(sf, rec);\n }\n if (t.kind === \"nullable\" && sf.kind === \"union\" && sf.members.some((m) => m.kind === \"null\")) {\n const rest = sf.members.filter((m) => m.kind !== \"null\");\n const inner: SpecType =\n rest.length === 1 ? (rest[0] as SpecType) : { kind: \"union\", members: rest };\n return typeFits(inner, t.inner);\n }\n if (t.kind === \"union\") {\n const u = module.unions.find((x) => x.name === t.name);\n if (!u || sf.kind !== \"union\" || sf.members.length !== u.members.length) return false;\n return u.members.every((m) => {\n const rec = recordOf(m.record);\n return (\n rec !== undefined && sf.members.some((sm) => sm.kind === \"record\" && recordFits(sm, rec))\n );\n });\n }\n try {\n return JSON.stringify(binderType(\"field\", sf, module)) === JSON.stringify(t);\n } catch (err) {\n if (err instanceof OutsideSubset) return false;\n throw err;\n }\n };\n function fieldFits(sf: SpecType, f: RecordType[\"fields\"][number]): boolean {\n if (f.literal !== undefined) return sf.kind === \"literal\" && sf.value === f.literal;\n if (sf.kind === \"literal\") return false;\n return typeFits(sf, f.type);\n }\n const fitting = module.unions.filter((u) => {\n if (u.members.length !== members.length) return false;\n return u.members.every((m) => {\n const rec = recordOf(m.record);\n return rec !== undefined && members.some((sm) => recordFits(sm, rec));\n });\n });\n return fitting.length === 1 ? fitting[0] : undefined;\n}\n\n/**\n * What a binder's subset type says that its sort does not: a union's\n * members carry their tags, and so on\n * into fields and under an option. Undefined when the sort says it all.\n */\nexport function wellFormed(\n target: string,\n t: SubsetType,\n module: SubsetModule,\n): string | undefined {\n switch (t.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return undefined;\n case \"nullable\": {\n const base = sortName(t.inner, module);\n const inner = wellFormed(`(${ident.val(base)} ${target})`, t.inner, module);\n return inner === undefined\n ? undefined\n : `(or (${tester(ident.none(base))} ${target}) ${inner})`;\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name);\n if (!rec) return undefined;\n const parts: string[] = [];\n for (const f of rec.fields) {\n const read = `(${ident.field(rec.name, f.name)} ${target})`;\n if (f.literal !== undefined)\n parts.push(\n typeof f.literal === \"string\"\n ? `(= ${read} ${stringTerm(f.literal)})`\n : `(= ${read} ${f.literal ? \"true\" : \"false\"})`,\n );\n const inner = wellFormed(read, f.type, module);\n if (inner !== undefined) parts.push(inner);\n }\n return parts.length === 0\n ? undefined\n : parts.length === 1\n ? parts[0]\n : `(and ${parts.join(\" \")})`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name);\n if (!u) return undefined;\n const cases = u.members.map((m) => {\n const is = `(${tester(ident.inject(u.name, m.record))} ${target})`;\n const inner = wellFormed(\n `(${ident.project(u.name, m.record)} ${target})`,\n { kind: \"record\", name: m.record },\n module,\n );\n return inner === undefined ? is : `(and ${is} ${inner})`;\n });\n return `(or ${cases.join(\" \")})`;\n }\n }\n}\n\n/**\n * What a binder's TypeScript type says beyond its sort: a literal, or a\n * union of literals (with or without null), admits only those values,\n * which the solver must be told, since the sort alone would let it pick\n * any string or number.\n */\nexport function domainConstraint(\n symbolName: string,\n t: SpecType,\n subset: SubsetType,\n module: SubsetModule,\n): string | undefined {\n const literal = (target: string, v: string | number | boolean): string =>\n typeof v === \"string\"\n ? `(= ${target} ${stringTerm(v)})`\n : typeof v === \"number\"\n ? `(fp.eq ${target} ${numberTerm(v)})`\n : `(= ${target} ${v ? \"true\" : \"false\"})`;\n const literals: (string | number | boolean)[] = [];\n let withNull = false;\n if (t.kind === \"literal\") literals.push(t.value);\n else if (t.kind === \"union\") {\n for (const m of t.members) {\n if (m.kind === \"literal\") literals.push(m.value);\n else if (m.kind === \"null\") withNull = true;\n else return undefined;\n }\n } else return undefined;\n if (literals.length === 0) return undefined;\n const over = (target: string) => {\n const alternatives = literals.map((v) => literal(target, v));\n return alternatives.length === 1\n ? (alternatives[0] as string)\n : `(or ${alternatives.join(\" \")})`;\n };\n if (subset.kind === \"nullable\") {\n const base = sortName(subset.inner, module);\n const some = `(and (${tester(ident.some(base))} ${symbolName}) ${over(`(${ident.val(base)} ${symbolName})`)})`;\n return withNull ? `(or (${tester(ident.none(base))} ${symbolName}) ${some})` : some;\n }\n return over(symbolName);\n}\n\n/** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */\nfunction arrowTerm(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n try {\n const binders = property.binders;\n const scope = new Map<string, SubsetType>();\n const names = new Map<string, string>();\n arrow.params.forEach((p, i) => {\n const binder = binders[i];\n const type = types[i];\n if (p === null) fail(`a destructured parameter in ${what}`);\n if (!binder || !type) fail(`${what} takes more parameters than the function has`);\n scope.set(p, type);\n names.set(p, binder.name);\n });\n const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));\n const read = readArrowBody(arrow, scope, e.module, aliases);\n const t = typeOf(read, scope, e.ctx, fail);\n if (t.kind !== \"bool\")\n fail(`${what} is not boolean (a ${t.kind === \"record\" ? t.name : t.kind})`);\n const renamed = renameVars(read, names);\n const binderScope = new Map(binders.map((b, i) => [b.name, types[i] as SubsetType]));\n return term(renamed, binderScope, e);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);\n }\n}\n\n/** The definitions every script of the module starts with: datatypes, then functions, callees first. */\nexport function prelude(module: SubsetModule): string {\n const datatypes = emitDatatypes(module);\n return [\n \";; Generated by Eutaxy's first-party SMT engine from the module and its spec file.\",\n \"(set-option :produce-models true)\",\n ...(datatypes === \"\" ? [] : [datatypes]),\n ...module.functions.map((f) => emitFunction(f, module)),\n ].join(\"\\n\");\n}\n\nexport interface PropertyScript {\n readonly script: string;\n /** The binders' SMT names and types, in order, for reading a model back. */\n readonly binders: readonly {\n readonly name: string;\n readonly symbol: string;\n readonly type: SubsetType;\n }[];\n}\n\n/**\n * One property's script: the binders as constants, what their types say\n * beyond their sorts, the precondition asserted, the claim's negation\n * asserted. `unsat` proves the claim; `sat` comes with the binders' values.\n */\nexport function propertyScript(property: Property, module: SubsetModule): PropertyScript {\n if (property.kind !== \"forall\" || !property.ensures) fail(\"not a forall property\");\n const e = env(module);\n const types = property.binders.map((b) => binderType(b.name, b.type, module));\n const binders = property.binders.map((b, i) => ({\n name: b.name,\n symbol: ident.variable(b.name),\n type: types[i] as SubsetType,\n }));\n const lines = [\n prelude(module),\n ...binders.map((b) => `(declare-const ${b.symbol} ${sort(b.type, module)})`),\n // What a binder's subset type says that its sort does not: which member of a union, which tags.\n ...binders.flatMap((b) => {\n const c = wellFormed(b.symbol, b.type, module);\n return c === undefined ? [] : [`(assert ${c})`];\n }),\n ...property.binders.flatMap((b, i) => {\n const c = domainConstraint(\n (binders[i] as (typeof binders)[number]).symbol,\n b.type,\n types[i] as SubsetType,\n module,\n );\n return c === undefined ? [] : [`(assert ${c})`];\n }),\n ...(property.when ? [`(assert ${arrowTerm(property.when, \"when\", property, types, e)})`] : []),\n `(assert (not ${arrowTerm(property.ensures, \"ensures\", property, types, e)}))`,\n \"(check-sat)\",\n ...(binders.length > 0 ? [`(get-value (${binders.map((b) => b.symbol).join(\" \")}))`] : []),\n \"(get-info :reason-unknown)\",\n ];\n return { script: `${lines.join(\"\\n\")}\\n`, binders };\n}\n\n/** A TypeScript value of a subset type as a term, for translation checks. */\nexport function value(v: unknown, t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n if (typeof v !== \"number\") fail(`${String(v)} is not a number`);\n return numberTerm(v);\n case \"bool\":\n if (typeof v !== \"boolean\") fail(`${String(v)} is not a boolean`);\n return v ? \"true\" : \"false\";\n case \"string\":\n if (typeof v !== \"string\") fail(`${String(v)} is not a string`);\n return stringTerm(v);\n case \"nullable\": {\n const base = sortName(t.inner, module);\n return v === null ? ident.none(base) : `(${ident.some(base)} ${value(v, t.inner, module)})`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name) ?? fail(`no union ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a ${t.name}`);\n const tag = (v as Record<string, unknown>)[u.tag];\n const member =\n u.members.find((m) => m.tag === tag) ?? fail(`${t.name} value with tag ${String(tag)}`);\n return `(${ident.inject(u.name, member.record)} ${value(v, { kind: \"record\", name: member.record }, module)})`;\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a record`);\n const o = v as Record<string, unknown>;\n const extra = Object.keys(o).filter((k) => !rec.fields.some((f) => f.name === k));\n if (extra.length > 0) fail(`${t.name} value has unexpected fields ${extra.join(\", \")}`);\n return construct(\n t.name,\n rec.fields.map((f) => value(o[f.name], f.type, module)),\n );\n }\n case \"null\":\n return fail(\"a value of type null\");\n }\n}\n\n/** Equality of two terms of a type, as JavaScript would have it: `fp.eq` on numbers, field by field on records. */\nexport function equal(a: string, b: string, t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return `(fp.eq ${a} ${b})`;\n case \"bool\":\n case \"string\":\n return `(= ${a} ${b})`;\n case \"nullable\": {\n const base = sortName(t.inner, module);\n return `(ite (and (${tester(ident.some(base))} ${a}) (${tester(ident.some(base))} ${b})) ${equal(`(${ident.val(base)} ${a})`, `(${ident.val(base)} ${b})`, t.inner, module)} (and (${tester(ident.none(base))} ${a}) (${tester(ident.none(base))} ${b})))`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name) ?? fail(`no union ${t.name}`);\n const cases = u.members.map((m) => {\n const is = tester(ident.inject(u.name, m.record));\n const out = ident.project(u.name, m.record);\n return `(and (${is} ${a}) (${is} ${b}) ${equal(`(${out} ${a})`, `(${out} ${b})`, { kind: \"record\", name: m.record }, module)})`;\n });\n return `(or ${cases.join(\" \")})`;\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n const fields = rec.fields.map((f) =>\n equal(\n `(${ident.field(t.name, f.name)} ${a})`,\n `(${ident.field(t.name, f.name)} ${b})`,\n f.type,\n module,\n ),\n );\n if (fields.length === 0) return \"true\";\n return fields.length === 1 ? (fields[0] as string) : `(and ${fields.join(\" \")})`;\n }\n case \"null\":\n return fail(\"equality at type null\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Reading Z3's answers.\n\nexport type SExpr = string | readonly SExpr[];\n\n/** Z3's output as S-expressions and atoms, in order. */\nexport function parseSExprs(text: string): SExpr[] {\n const out: SExpr[] = [];\n const stack: SExpr[][] = [];\n let i = 0;\n const push = (x: SExpr) => {\n const top = stack[stack.length - 1];\n if (top) top.push(x);\n else out.push(x);\n };\n while (i < text.length) {\n const c = text[i] as string;\n if (/\\s/.test(c)) {\n i++;\n continue;\n }\n if (c === \";\") {\n while (i < text.length && text[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"(\") {\n stack.push([]);\n i++;\n continue;\n }\n if (c === \")\") {\n const done = stack.pop();\n if (done) push(done);\n i++;\n continue;\n }\n if (c === '\"') {\n let j = i + 1;\n let s = \"\";\n while (j < text.length) {\n if (text[j] === '\"' && text[j + 1] === '\"') {\n s += '\"';\n j += 2;\n } else if (text[j] === '\"') break;\n else s += text[j++];\n }\n push(`\"${s}\"`);\n i = j + 1;\n continue;\n }\n if (c === \"|\") {\n const j = text.indexOf(\"|\", i + 1);\n push(text.slice(i, j < 0 ? text.length : j + 1));\n i = j < 0 ? text.length : j + 1;\n continue;\n }\n let j = i;\n while (j < text.length && !/[\\s()]/.test(text[j] as string)) j++;\n push(text.slice(i, j));\n i = j;\n }\n while (stack.length > 0) {\n const done = stack.pop();\n if (done) push(done);\n }\n return out;\n}\n\n/** Thrown when a model value is not of the shape the type calls for. */\nexport class UnreadableModel extends Error {}\n\nconst bitsOf = (atom: string): bigint =>\n atom.startsWith(\"#b\") ? BigInt(`0b${atom.slice(2)}`) : BigInt(`0x${atom.slice(2)}`);\n\n/** A model value of the type as a JavaScript value. */\nexport function decode(x: SExpr, t: SubsetType, module: SubsetModule): unknown {\n switch (t.kind) {\n case \"bool\":\n if (x === \"true\") return true;\n if (x === \"false\") return false;\n throw new UnreadableModel(`not a boolean: ${show(x)}`);\n case \"int\": {\n if (Array.isArray(x) && x[0] === \"_\") {\n const special = x[1];\n if (special === \"NaN\") return Number.NaN;\n if (special === \"+oo\") return Number.POSITIVE_INFINITY;\n if (special === \"-oo\") return Number.NEGATIVE_INFINITY;\n if (special === \"+zero\") return 0;\n if (special === \"-zero\") return -0;\n }\n if (Array.isArray(x) && x[0] === \"fp\" && x.length === 4) {\n const sign = bitsOf(x[1] as string);\n const exponent = bitsOf(x[2] as string);\n const significand = bitsOf(x[3] as string);\n const view = new DataView(new ArrayBuffer(8));\n view.setBigUint64(0, (sign << 63n) | (exponent << 52n) | significand);\n return view.getFloat64(0);\n }\n throw new UnreadableModel(`not a double: ${show(x)}`);\n }\n case \"string\":\n return decodeString(x);\n case \"nullable\": {\n const base = sortName(t.inner, module);\n if (x === ident.none(base)) return null;\n if (Array.isArray(x) && x[0] === ident.some(base) && x.length === 2)\n return decode(x[1] as SExpr, t.inner, module);\n throw new UnreadableModel(`not a ${describeSubset(t)}: ${show(x)}`);\n }\n case \"union\": {\n const u = module.unions.find((y) => y.name === t.name);\n if (!u) throw new UnreadableModel(`no union ${t.name}`);\n const head = Array.isArray(x) ? x[0] : x;\n const member = u.members.find((m) => ident.inject(u.name, m.record) === head);\n if (!member || !Array.isArray(x) || x.length !== 2)\n throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);\n return decode(x[1] as SExpr, { kind: \"record\", name: member.record }, module);\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name);\n if (!rec) throw new UnreadableModel(`no record ${t.name}`);\n if (rec.fields.length === 0 && x === ident.constructor(t.name)) return {};\n if (\n !Array.isArray(x) ||\n x[0] !== ident.constructor(t.name) ||\n x.length !== rec.fields.length + 1\n )\n throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);\n const out: Record<string, unknown> = {};\n rec.fields.forEach((f, i) => {\n out[f.name] = decode(x[i + 1] as SExpr, f.type, module);\n });\n return out;\n }\n case \"null\":\n throw new UnreadableModel(\"a value of type null\");\n }\n}\n\nfunction describeSubset(t: SubsetType): string {\n return t.kind === \"nullable\"\n ? `${describeSubset(t.inner)} | null`\n : t.kind === \"record\" || t.kind === \"union\"\n ? t.name\n : t.kind;\n}\n\nfunction decodeString(x: SExpr): string {\n if (Array.isArray(x)) {\n if (x[0] === \"seq.unit\" && typeof x[1] === \"string\")\n return String.fromCharCode(Number(bitsOf(x[1])));\n if (x[0] === \"seq.++\") return x.slice(1).map(decodeString).join(\"\");\n if (x[0] === \"as\" && x[1] === \"seq.empty\") return \"\";\n if (x[0] === \"_\" && x[1] === \"seq.empty\") return \"\";\n }\n throw new UnreadableModel(`not a string: ${show(x)}`);\n}\n\nfunction show(x: SExpr): string {\n return typeof x === \"string\" ? x : `(${x.map(show).join(\" \")})`;\n}\n\nexport interface Answer {\n readonly result: \"sat\" | \"unsat\" | \"unknown\" | \"error\";\n /** The binders' values when `sat`, by SMT symbol. */\n readonly values: ReadonlyMap<string, SExpr>;\n readonly reason: string;\n /** Every `(error …)` Z3 printed, except the one for a model asked after `unsat`, which the script expects. */\n readonly errors: readonly string[];\n}\n\n/** What a property's script came back with. */\nexport function readAnswer(output: string): Answer {\n const parts = parseSExprs(output);\n const first = parts.find((p) => p === \"sat\" || p === \"unsat\" || p === \"unknown\");\n const errors = parts\n .filter((p): p is readonly SExpr[] => Array.isArray(p) && p[0] === \"error\")\n .map((e) => show(e))\n .filter((e) => !/model is not available/.test(e));\n const values = new Map<string, SExpr>();\n let reason = \"\";\n for (const p of parts) {\n if (!Array.isArray(p)) continue;\n if (p[0] === \":reason-unknown\" && typeof p[1] === \"string\") reason = p[1].replace(/^\"|\"$/g, \"\");\n if (p.every((x) => Array.isArray(x) && x.length === 2 && typeof x[0] === \"string\"))\n for (const pair of p as readonly (readonly [string, SExpr])[]) values.set(pair[0], pair[1]);\n }\n if (first === undefined)\n return { result: \"error\", values, reason: errors.join(\"; \") || output.trim(), errors };\n return { result: first as Answer[\"result\"], values, reason, errors };\n}\n","/**\n * Running Z3 over a process boundary. The engine is pinned to one Z3\n * release, looked for in Eutaxy's cache first (where `eutaxy prover install\n * smt` puts the upstream release named in `z3Downloads`), then as a `z3`\n * on the PATH (or in Homebrew's and the usual local prefixes) that must\n * report that version. Nothing is downloaded during a check; a missing\n * solver is `unavailable`, with how to install it. Every\n * run carries a resource limit, Z3's own machine-independent budget, so\n * the same script gives the same outcome on every machine; a wall-clock\n * timeout is only the safety net.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { type Host, host, installed, type Toolchain } from \"@eutaxy/prover/toolchain\";\n\n/** The Z3 release the engine's contract corpus is checked against. */\nexport const z3Version = \"5.3.2\";\n/** How to put the pinned solver on this machine. */\nexport const installHint = `run: eutaxy prover install smt (or put Z3 ${z3Version} on the PATH, from https://github.com/Z3Prover/z3/releases/tag/z3-${z3Version} or Homebrew: brew install z3)`;\n\nconst z3Release = `https://github.com/Z3Prover/z3/releases/download/z3-${z3Version}`;\nconst z3File = (name: string, sha256: string, bytes: number) => ({\n file: name,\n url: `${z3Release}/${name}`,\n sha256,\n bytes,\n});\n/**\n * The upstream release files `eutaxy prover install smt` downloads, one per\n * platform, as published on Z3's GitHub release with the checksums it\n * reports; the file names carry the version, and a test holds them to\n * `z3Version`. The Linux builds need glibc 2.39 (x64) or 2.38 (arm64).\n */\nexport const z3Downloads: Toolchain = {\n name: \"smt\",\n version: z3Version,\n executable: \"bin/z3\",\n files: {\n \"linux-x64\": z3File(\n \"z3-5.3.2-x64-glibc-2.39.zip\",\n \"26d463cddad3901cbf86e3868c784914539f4e3f9b4de1a0b8dc2969806d60e2\",\n 69479256,\n ),\n \"linux-arm64\": z3File(\n \"z3-5.3.2-arm64-glibc-2.38.zip\",\n \"30b6a718a6cfe1b2db056038cc32eda5410f6d02e5937622b5238645347f59d5\",\n 64803341,\n ),\n \"darwin-x64\": z3File(\n \"z3-5.3.2-x64-osx-13.3.zip\",\n \"b911dc193f7447a14fba001e8e8a0c2866a544274bb003e76a9e864f03b4d557\",\n 54270076,\n ),\n \"darwin-arm64\": z3File(\n \"z3-5.3.2-arm64-osx-13.3.zip\",\n \"524290057c943a044ec3d1372db65a9c93f333d9817d58191154c4719ff7f8ad\",\n 53576249,\n ),\n \"win32-x64\": z3File(\n \"z3-5.3.2-x64-win.zip\",\n \"a75aa2b0383a8ee355387a54daad796911d6a965076751eea18d21a27f38e983\",\n 70867398,\n ),\n },\n};\n/** The resource budget a check runs under (Z3's `rlimit`, in its own units), unless configured. */\nexport const defaultResourceLimit = 50_000_000;\n\nexport interface Z3Run {\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n readonly timedOut: boolean;\n}\n\nexport interface Z3Solver {\n readonly command: string;\n readonly version: string;\n}\n\nfunction run(\n command: string,\n args: readonly string[],\n options: { readonly cwd?: string; readonly timeoutMs: number },\n): Promise<Z3Run> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(command, args, { cwd: options.cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n } catch (err) {\n resolve({ code: null, stdout: \"\", stderr: String(err), timedOut: false });\n return;\n }\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, options.timeoutMs);\n child.stdout?.on(\"data\", (d: Buffer) => {\n stdout += d.toString();\n });\n child.stderr?.on(\"data\", (d: Buffer) => {\n stderr += d.toString();\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ code: null, stdout, stderr: `${stderr}${String(err)}`, timedOut });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n });\n}\n\n/**\n * Candidates for the `z3` executable: the one `eutaxy prover install smt`\n * put in the cache, `EUTAXY_Z3`, the PATH, then the prefixes package\n * managers install into.\n */\nexport function candidates(h: Host = host()): string[] {\n const fromEnv = h.env[\"EUTAXY_Z3\"];\n const fromCache = installed(z3Downloads, h);\n return [\n ...(fromCache ? [fromCache.executable] : []),\n ...(fromEnv ? [fromEnv] : []),\n \"z3\",\n \"/opt/homebrew/bin/z3\",\n \"/usr/local/bin/z3\",\n \"/usr/bin/z3\",\n ];\n}\n\n/**\n * The pinned solver if it is installed: a `z3` of exactly that version,\n * wherever among the candidates it is; another version is reported only\n * when no candidate is the pinned one.\n */\nexport async function findZ3(\n where: readonly string[] = candidates(),\n): Promise<Z3Solver | { readonly unavailable: string }> {\n let other: string | undefined;\n for (const z3 of where) {\n const v = await run(z3, [\"--version\"], { timeoutMs: 20_000 });\n if (v.code !== 0) continue;\n const m = /Z3 version (\\S+)/.exec(v.stdout);\n if (m?.[1] === z3Version) return { command: z3, version: z3Version };\n other ??= m?.[1] ?? \"of unknown version\";\n }\n if (other !== undefined)\n return {\n unavailable: `z3 ${other} found, but the engine is pinned to ${z3Version}; ${installHint}`,\n };\n return { unavailable: `no z3 found; ${installHint}` };\n}\n\nexport interface SolvedScript {\n readonly run: Z3Run;\n /** Whether Z3 reported the resource limit exceeded. */\n readonly resourceLimit: boolean;\n}\n\n/** Write the script to a scratch file and run Z3 on it under the resource limit. */\nexport async function solve(\n solver: Z3Solver,\n script: string,\n options: {\n readonly timeoutMs?: number;\n readonly resourceLimit?: number;\n readonly keep?: boolean;\n } = {},\n): Promise<SolvedScript> {\n const dir = mkdtempSync(join(tmpdir(), \"eutaxy-smt-\"));\n try {\n const file = join(dir, \"property.smt2\");\n writeFileSync(file, script);\n const result = await run(\n solver.command,\n [`rlimit=${options.resourceLimit ?? defaultResourceLimit}`, \"-smt2\", file],\n { cwd: dir, timeoutMs: options.timeoutMs ?? 120_000 },\n );\n return { run: result, resourceLimit: /resource limit/i.test(result.stdout) };\n } finally {\n if (!options.keep) rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * The engine: a module's functions through the subset reader, the emitter\n * and Z3, one script per property, and each property's outcome back. An\n * `unsat` is `PROVEN` under the engine's models of the language. A model\n * is a candidate counterexample, never a verdict: the engine runs the\n * spec file's own `when` and `ensures` on it, and only a claim that fails\n * on the real function is `REFUTED`, with the input shrunk as the TESTED\n * rung shrinks; a model the function does not confirm is a modelling gap,\n * `UNKNOWN` (`unsupported`) with the input. A resource limit reached is\n * `gave_up`; a function or property outside the subset is `unsupported`;\n * no pinned solver is `unavailable`.\n */\n\nimport { existsSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n conforms,\n evaluate,\n type ModuleProofs,\n type ProofOutcome,\n type PropertyProof,\n type Prover,\n type ProveInput as ProverInput,\n render,\n shrinkRefutation,\n} from \"@eutaxy/prover\";\nimport {\n builtinsAssumption,\n listKinds,\n OutsideSubset,\n readSubset,\n restrictModule,\n type SubsetModule,\n} from \"@eutaxy/prover/reader\";\nimport { type Fn, type Forall, type FunctionSpec, isSpec, type Property } from \"@eutaxy/spec\";\nimport {\n decode,\n equal,\n type PropertyScript,\n prelude,\n propertyScript,\n readAnswer,\n UnreadableModel,\n} from \"./emit.ts\";\nimport { findZ3, solve, z3Version } from \"./z3.ts\";\n\nexport const engineName = \"smt\";\n\nexport interface ProveInput extends ProverInput {\n /** Extra Bool terms over the module's definitions that must hold (translation checks): each is checked unsatisfiable when negated. */\n readonly extra?: readonly string[];\n /** Z3's resource budget per property, in its own units. */\n readonly resourceLimit?: number;\n}\n\n/** This engine's report, with the definitions it ran. */\nexport interface SmtModuleProofs extends ModuleProofs {\n /** The prelude shared by every script, when any function was in the subset. */\n readonly smt?: string;\n}\n\n/** What every PROVEN verdict of this engine rests on. */\nexport const engineAssumptions: readonly string[] = [\n \"number is modelled as the IEEE double (the floating-point theory): NaN, the infinities and -0 are in every binder's domain, and === is fp.eq\",\n \"string is modelled as a sequence of 16-bit code units, as JavaScript holds it\",\n \"the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled\",\n builtinsAssumption,\n `Z3 ${z3Version} found the claim's negation unsatisfiable under a resource limit; no proof object was checked by a kernel`,\n];\n\nconst proven: Extract<ProofOutcome, { kind: \"PROVEN\" }> = {\n kind: \"PROVEN\",\n engine: { name: engineName, version: z3Version },\n assumptions: engineAssumptions,\n};\n\nconst unknown = (\n cause: \"gave_up\" | \"unsupported\" | \"unavailable\",\n reason: string,\n): ProofOutcome => ({ kind: \"UNKNOWN\", cause, reason });\n\n/** The scripts for the module's functions in the subset, and the functions with specs outside it with why. */\nexport interface Prepared {\n readonly module: SubsetModule;\n readonly fns: readonly FunctionSpec[];\n readonly outside: ReadonlyMap<string, string>;\n /** One script per statable forall property. */\n readonly scripts: ReadonlyMap<string, PropertyScript>;\n /** Properties the emitter could not state, with why. */\n readonly skipped: ReadonlyMap<string, string>;\n readonly prelude: string;\n}\n\nconst key = (fn: string, property: string): string => `${fn}\\u0000${property}`;\n\n/** Read and emit: every function the subset takes, and a script per property of the ones with specs. */\nexport function prepare(input: ProveInput): Prepared {\n const wanted = input.functions ? new Set(input.functions) : undefined;\n const fns = input.specs.functions.filter((f) => !wanted || wanted.has(f.name));\n // Lists are read, but this engine does not take them: functions using one are outside here, so the\n // prelude never meets them and the module's other functions still go through.\n const module = restrictModule(\n readSubset(\n input.source,\n fns.map((f) => f.name),\n input.modulePath === undefined ? {} : { path: input.modulePath },\n ),\n (t) => t.kind !== \"list\" && t.kind !== \"nothing\",\n \"arrays are not in this engine's subset (the Lean engine takes them)\",\n listKinds,\n );\n const outside = new Map<string, string>();\n for (const o of module.outside)\n if (fns.some((f) => f.name === o.name))\n outside.set(\n o.name,\n `outside the engine's subset${o.line > 0 ? ` (line ${o.line})` : \"\"}: ${o.message}`,\n );\n for (const fn of fns) {\n const read = module.functions.find((f) => f.name === fn.name);\n if (read && read.offset !== fn.offset)\n outside.set(\n fn.name,\n `outside the engine's subset (line ${fn.line}): the ${fn.name} the spec names is not the module's top-level declaration of that name (line ${read.line})`,\n );\n }\n const scripts = new Map<string, PropertyScript>();\n const skipped = new Map<string, string>();\n let pre = \"\";\n try {\n pre = prelude(module);\n for (const fn of fns) {\n if (outside.has(fn.name)) continue;\n for (const property of fn.properties) {\n if (property.kind !== \"forall\") continue;\n try {\n scripts.set(key(fn.name, property.name), propertyScript(property, module));\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n skipped.set(key(fn.name, property.name), err.message);\n }\n }\n }\n } catch (err) {\n // The emitter refusing something the reader let through is an engine gap: every function is unsupported, none guessed.\n if (!(err instanceof OutsideSubset)) throw err;\n for (const fn of fns) outside.set(fn.name, `outside the engine's subset: ${err.message}`);\n scripts.clear();\n }\n return { module, fns, outside, scripts, skipped, prelude: pre };\n}\n\n/**\n * The spec file as a module. A relative import written without `.ts`\n * (`./domain`, `./domain.js`), which the simulator's loader resolves and\n * Node does not, is completed in a sibling copy that is imported and then\n * removed, so the copy's own relative imports still resolve.\n */\nasync function importSpecFile(specPath: string): Promise<Record<string, unknown>> {\n try {\n return (await import(pathToFileURL(specPath).href)) as Record<string, unknown>;\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code !== \"ERR_MODULE_NOT_FOUND\" && code !== \"ERR_UNSUPPORTED_DIR_IMPORT\") throw err;\n const source = readFileSync(specPath, \"utf8\");\n const dir = dirname(specPath);\n const rewritten = source.replace(\n /(from\\s*[\"'])(\\.{1,2}\\/[^\"']+?)(\\.js)?([\"'])/g,\n (whole, pre: string, rel: string, _js: string | undefined, post: string) =>\n existsSync(join(dir, `${rel}.ts`)) ? `${pre}${rel}.ts${post}` : whole,\n );\n if (rewritten === source) throw err;\n const copy = join(dir, `.eutaxy-replay-${process.pid}-${Date.now()}.props.ts`);\n writeFileSync(copy, rewritten);\n try {\n return (await import(pathToFileURL(copy).href)) as Record<string, unknown>;\n } finally {\n rmSync(copy, { force: true });\n }\n }\n}\n\n/** The spec file's export for a property, loaded for replay, or why it could not be. */\nasync function loadSpec(\n specPath: string | undefined,\n property: Property,\n fn: string,\n): Promise<Forall<Fn> | string> {\n if (specPath === undefined)\n return \"the engine was not given the spec file's path to replay the counterexample\";\n let ns: Record<string, unknown>;\n try {\n ns = await importSpecFile(specPath);\n } catch (err) {\n return `the spec file could not be loaded to replay the counterexample: ${String(err)}`;\n }\n const exported = Object.hasOwn(ns, property.name) ? ns[property.name] : undefined;\n if (!isSpec(exported) || exported.kind !== \"forall\")\n return `the spec file exports no forall named ${property.name} to replay the counterexample with`;\n if (typeof exported.fn !== \"function\" || exported.fn.name !== fn)\n return `the spec file's ${property.name} is not on ${fn}`;\n return exported;\n}\n\n/** Prove a module's properties with the pinned Z3. */\nexport async function proveModule(input: ProveInput): Promise<SmtModuleProofs> {\n const { fns, outside, scripts, skipped, module, prelude: smt } = prepare(input);\n const specErrors = input.specs.errors;\n const inSubset = fns.filter((f) => !outside.has(f.name));\n const results: PropertyProof[] = fns\n .filter((f) => outside.has(f.name))\n .flatMap((f) =>\n f.properties.map((property) => ({\n function: f.name,\n property: property.name,\n outcome: unknown(\"unsupported\", outside.get(f.name) as string),\n })),\n );\n if (inSubset.length === 0) return { results, specErrors };\n const allWith = (outcome: ProofOutcome): SmtModuleProofs => ({\n results: [\n ...results,\n ...inSubset.flatMap((fn) =>\n fn.properties.map((p) => ({ function: fn.name, property: p.name, outcome })),\n ),\n ],\n smt,\n specErrors,\n });\n const solver = await findZ3();\n if (\"unavailable\" in solver) return allWith(unknown(\"unavailable\", solver.unavailable));\n const options = {\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n ...(input.resourceLimit === undefined ? {} : { resourceLimit: input.resourceLimit }),\n };\n // Translation checks first: a definition that does not compute what the TypeScript computes is an engine gap.\n if (input.extra && input.extra.length > 0) {\n const script = [\n smt,\n ...input.extra.flatMap((x) => [\"(push)\", `(assert (not ${x}))`, \"(check-sat)\", \"(pop)\"]),\n \"\",\n ].join(\"\\n\");\n const checked = await solve(solver, script, options);\n const answers = checked.run.stdout\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => /^(sat|unsat|unknown)$/.test(l));\n if (checked.run.timedOut)\n return allWith(unknown(\"gave_up\", \"Z3 did not finish the translation checks in time\"));\n // The budget ran out on a check: nothing is known about the definitions, and nothing is claimed.\n if (answers.includes(\"unknown\"))\n return allWith(unknown(\"gave_up\", \"Z3 reached its resource limit on a translation check\"));\n const failed = answers.findIndex((a) => a !== \"unsat\");\n const errors = readAnswer(checked.run.stdout).errors;\n if (\n checked.run.code !== 0 ||\n errors.length > 0 ||\n answers.length !== input.extra.length ||\n failed >= 0\n )\n return allWith(\n unknown(\n \"unsupported\",\n `the emitted SMT failed a translation check${failed >= 0 ? ` (${input.extra[failed]})` : \"\"}: ${errors[0] ?? (checked.run.stderr || checked.run.stdout).trim().split(\"\\n\")[0] ?? \"\"}`,\n ),\n );\n }\n for (const fn of inSubset) {\n for (const property of fn.properties) {\n if (property.kind === \"total\") {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\n \"unsupported\",\n \"total is not decided by this engine (Lean proves it by acceptance)\",\n ),\n });\n continue;\n }\n const k = key(fn.name, property.name);\n const why = skipped.get(k);\n if (why !== undefined) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"unsupported\", why),\n });\n continue;\n }\n const script = scripts.get(k);\n if (!script) continue;\n const solved = await solve(solver, script.script, options);\n results.push({\n function: fn.name,\n property: property.name,\n outcome: await outcomeOf(solved, script, module, property, fn.name, input),\n });\n }\n }\n return { results, smt, specErrors };\n}\n\nasync function outcomeOf(\n solved: Awaited<ReturnType<typeof solve>>,\n script: PropertyScript,\n module: SubsetModule,\n property: Property,\n fn: string,\n input: ProveInput,\n): Promise<ProofOutcome> {\n if (solved.run.timedOut)\n return unknown(\"gave_up\", `Z3 did not finish within ${input.timeoutMs ?? 120_000} ms`);\n if (solved.run.code === null)\n return unknown(\"unavailable\", `Z3 could not be run: ${solved.run.stderr.trim()}`);\n const answer = readAnswer(solved.run.stdout);\n // An error Z3 printed means a command was dropped; whatever verdict line followed is not about the\n // claim. (The exit code says nothing here: Z3 exits non-zero for the model asked after `unsat` too.)\n if (answer.errors.length > 0)\n return unknown(\"unsupported\", `the emitted SMT did not run: ${answer.errors[0]}`);\n if (answer.result === \"unsat\") return proven;\n if (answer.result === \"unknown\")\n return unknown(\n \"gave_up\",\n solved.resourceLimit\n ? `Z3 reached its resource limit${answer.reason ? ` (${answer.reason})` : \"\"}`\n : `Z3 gave up: ${answer.reason || \"unknown\"}`,\n );\n if (answer.result === \"error\")\n return unknown(\"unsupported\", `the emitted SMT did not run: ${answer.reason}`);\n // sat: a candidate counterexample, replayed through the spec file's own claim.\n let values: unknown[];\n try {\n values = script.binders.map((b) => {\n const v = answer.values.get(b.symbol);\n if (v === undefined) throw new UnreadableModel(`no value for ${b.name} in the model`);\n return decode(v, b.type, module);\n });\n } catch (err) {\n if (!(err instanceof UnreadableModel)) throw err;\n return unknown(\"unsupported\", `Z3's model could not be read: ${err.message}`);\n }\n const rendered = property.binders.map((b, i) => `${b.name} = ${render(values[i])}`).join(\", \");\n // The solver saw the sorts; the claim quantifies over the TypeScript types, which may be narrower.\n if (!property.binders.every((b, i) => conforms(b.type, values[i])))\n return unknown(\n \"unsupported\",\n `Z3's model lies outside the parameter types (${rendered}): the engine's model of the types is wider than the types`,\n );\n const spec = await loadSpec(input.specPath, property, fn);\n if (typeof spec === \"string\") return unknown(\"unsupported\", `${spec} (the model: ${rendered})`);\n const evaluation = evaluate(spec, values);\n if (\"malformed\" in evaluation)\n return unknown(\n \"unsupported\",\n `the property could not be evaluated on the model (${rendered}): ${evaluation.malformed}`,\n );\n if (evaluation.outcome !== \"refuted\")\n return unknown(\n \"unsupported\",\n `the claim ${evaluation.outcome === \"held\" ? \"held\" : \"was outside its precondition\"} on the model Z3 gave (${rendered}): the engine's model of the language differs from the runtime here`,\n );\n const smallest = shrinkRefutation(spec, property.binders, values, evaluation);\n return {\n kind: \"REFUTED\",\n engine: { name: engineName, version: z3Version },\n counterexample: {\n binders: property.binders.map((b, i) => ({\n name: b.name,\n value: render(smallest.values[i]),\n })),\n ...(smallest.error === undefined ? {} : { error: smallest.error }),\n },\n assumptions: [\n \"found as a model of the claim's negation by Z3, confirmed by running the spec on it, then shrunk\",\n ],\n };\n}\n\n/** The engine as a `Prover`: available when the pinned solver is installed. */\nexport const smtProver: Prover = {\n name: engineName,\n async available() {\n const solver = await findZ3();\n return \"unavailable\" in solver ? solver : { version: solver.version };\n },\n prove: (input) => proveModule(input),\n};\n\nexport { equal };\n","/**\n * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before\n * running Vitest: a test that performs the check inside workerd and prints\n * the verdict on one marked line, and a Vitest config with the Cloudflare\n * plugin pointed at the scenario's wrangler config.\n */\n\n/** Key under which the generated test stores its result in the Vitest task meta, read back from the JSON reporter. */\nexport const metaKey = \"eutaxy\";\n\nexport interface GeneratedCheck {\n readonly seed: string;\n readonly maxRuns?: number;\n /** Replaces the scenario's time budget. */\n readonly budgetMs?: number;\n /** Exhaustive exploration instead of seeded. */\n readonly exhaustive?: boolean;\n /** Import specifier of the scenario from the generated test (e.g. \"../scenario.sim.ts\"). */\n readonly scenarioImport: string;\n}\n\n/**\n * The generated test: the module globs (Vite resolves them at build time,\n * so they must be written in the test) and one call to `checkInWorkerd`,\n * which does the rest.\n */\nexport function checkTestSource(g: GeneratedCheck): string {\n const options =\n `seed: ${JSON.stringify(g.seed)}` +\n (g.maxRuns === undefined ? \"\" : `, maxRuns: ${g.maxRuns}`) +\n (g.budgetMs === undefined ? \"\" : `, budgetMs: ${g.budgetMs}`) +\n (g.exhaustive ? \", exhaustive: true\" : \"\");\n return `// Generated by eutaxy check; deleted after the run.\nimport { checkInWorkerd } from \"eutaxy/cloudflare\";\nimport { env } from \"cloudflare:workers\";\nimport * as durableObjects from \"cloudflare:test\";\nimport { test } from \"vitest\";\nimport scenario from ${JSON.stringify(g.scenarioImport)};\nimport { specEntries } from \"./specs.ts\";\n\nconst sqlFiles = import.meta.glob(\"../**/*.sql\", { query: \"?raw\", import: \"default\", eager: true }) as Record<string, string>;\nconst modules = import.meta.glob([\"../**/*.ts\", \"!../**/*.test.ts\", \"!../**/*.sim.ts\", \"!../**/node_modules/**\", \"!../**/.eutaxy/**\"]);\n\ntest(\"eutaxy check\", async ({ task }) => {\n task.meta[${JSON.stringify(metaKey)}] = await checkInWorkerd({ scenario, env, durableObjects, sqlFiles, modules, specEntries, ${options} });\n});\n`;\n}\n\nexport function vitestConfigSource(\n wranglerConfigPath: string,\n testPath: string,\n outputFile: string,\n): string {\n return `// Generated by eutaxy check; deleted after the run.\nimport { cloudflareTest } from \"@cloudflare/vitest-plugin\";\nimport { defineConfig } from \"vitest/config\";\n\nexport default defineConfig({\n plugins: [cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })],\n test: {\n include: [${JSON.stringify(testPath)}],\n testTimeout: 600_000,\n reporters: [\"json\"],\n outputFile: ${JSON.stringify(outputFile)},\n },\n});\n`;\n}\n","import type { Violated } from \"@eutaxy/core\";\nimport { emitRegressionTest } from \"@eutaxy/report\";\n\nexport interface CloudflareRegressionOptions {\n /** Import path of the scenario module, relative to the emitted file. */\n readonly scenarioPath: string;\n /** Import path of the Worker module. */\n readonly workerPath: string;\n /** D1 binding name to schema file path, imported with `?raw`. */\n readonly schemaPaths: Readonly<Record<string, string>>;\n /**\n * The time budget the check ran with, when it replaced the scenario's: the\n * replay gets the same, so I/O that finished within it does not time out.\n */\n readonly budgetMs?: number;\n /** The platform's retry limit, when the scenario was checked with a non-default one. */\n readonly maxRetries?: number;\n /** The scenario sets up Durable Objects: pass the Cloudflare test helpers to the platform. */\n readonly durableObjects?: boolean;\n /**\n * Pass the Worker module's exports to the platform: the scenario sets up\n * Workflows (their classes are among them) or drives a named entrypoint.\n */\n readonly exports?: boolean;\n /** @deprecated Use `exports`. */\n readonly workflows?: boolean;\n readonly expect?: \"holds\" | \"violates\";\n readonly engineModule?: string;\n /** Core modules to observe during the replay (import path, functions), for `refines`. */\n readonly specModules?: readonly {\n readonly path: string;\n readonly functions: readonly string[];\n }[];\n}\n\n/** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */\nexport function cloudflareRegressionTest(\n verdict: Violated,\n options: CloudflareRegressionOptions,\n): string {\n const bindings = Object.keys(options.schemaPaths).sort();\n const withExports = options.exports === true || options.workflows === true;\n const imports = [\n 'import { createCloudflarePlatform } from \"eutaxy/cloudflare\";',\n 'import { env } from \"cloudflare:workers\";',\n ...(options.durableObjects ? ['import * as cloudflareTest from \"cloudflare:test\";'] : []),\n `import scenario from ${JSON.stringify(options.scenarioPath)};`,\n ...bindings.map(\n (b) => `import schema_${b} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`,\n ),\n withExports\n ? `import * as worker from ${JSON.stringify(options.workerPath)};`\n : `import handler from ${JSON.stringify(options.workerPath)};`,\n ...(options.specModules ?? []).map(\n (m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`,\n ),\n ];\n const schemas = `{ ${bindings.map((b) => `${b}: schema_${b}`).join(\", \")} }`;\n const retries = options.maxRetries === undefined ? \"\" : `, maxRetries: ${options.maxRetries}`;\n const objects = options.durableObjects ? \", durableObjects: cloudflareTest\" : \"\";\n const handler = withExports ? \"handler: worker.default\" : \"handler\";\n const exports = withExports ? \", exports: worker\" : \"\";\n return emitRegressionTest(verdict, {\n imports,\n platform: `createCloudflarePlatform({ env, ${handler}, schemas: ${schemas}${retries}${objects}${exports} })`,\n scenario:\n options.budgetMs === undefined\n ? \"scenario\"\n : `{ ...scenario, bounds: { ...scenario.bounds, budgetMs: ${options.budgetMs} } }`,\n ...(options.expect ? { expect: options.expect } : {}),\n ...(options.engineModule ? { engineModule: options.engineModule } : {}),\n ...(options.specModules && options.specModules.length > 0\n ? {\n observe: options.specModules.map((m, i) => ({\n namespace: `core_${i}`,\n functions: m.functions,\n })),\n }\n : {}),\n });\n}\n","/** How the two halves of `eutaxy check` name a module next to the scenario. Imports nothing, so workerd can load it. */\n\n/** Normalize a module path from a scenario's `specs` to a key: \"./domain.ts\". */\nexport function specKey(path: string): string {\n const posix = path\n .split(\"\\\\\")\n .join(\"/\")\n .replace(/^(\\.\\/)+/, \"\");\n return `./${posix}`;\n}\n\n/** The key Vite's `import.meta.glob` gives a path next to the scenario, seen from `.eutaxy/`. */\nexport function globKey(path: string): string {\n return `.${specKey(path)}`;\n}\n","/**\n * Spec files for `eutaxy check`: every `<module>.props.ts` next to the\n * scenario, read with its module into `SpecIR` on the Node side, and the\n * generated `specs.ts` that hands workerd each module's specs together\n * with a loader for its spec file. Which of them a run checks is the\n * scenario's `specs`, read where the scenario is loaded, inside the\n * generated test; a spec file loads only when its module is named.\n */\n\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { basename, dirname, join, relative } from \"node:path\";\nimport { readSpecs } from \"@eutaxy/prover/reader\";\nimport type { ModuleSpecs } from \"@eutaxy/spec\";\nimport { specKey } from \"./keys.ts\";\n\nexport { specKey } from \"./keys.ts\";\n\n/** The suffix a spec file carries beside its module: `domain.ts` has `domain.props.ts`. */\nexport const specSuffix = \".props.ts\";\n\nexport interface SpecModule {\n /** The module's path relative to the scenario's directory, as a scenario names it: \"./domain.ts\". */\n readonly key: string;\n /** The module's absolute path. */\n readonly path: string;\n /** The spec file's absolute path. */\n readonly specPath: string;\n readonly specs: ModuleSpecs;\n}\n\nconst skipDirs = new Set([\"node_modules\", \".eutaxy\", \"dist\", \".git\"]);\n\n/** Read one module and its spec file; their imports resolve from where they are. */\nexport function readSpecModule(modulePath: string, specPath: string): ModuleSpecs {\n return readSpecs({\n module: readFileSync(modulePath, \"utf8\"),\n spec: readFileSync(specPath, \"utf8\"),\n modulePath,\n specPath,\n });\n}\n\n/** Spec files under `dir`, each with its module; a spec file without a module beside it is an error entry. */\nexport function findSpecModules(dir: string): SpecModule[] {\n const out: SpecModule[] = [];\n const walk = (at: string): void => {\n for (const entry of readdirSync(at, { withFileTypes: true })) {\n const path = join(at, entry.name);\n if (entry.isDirectory()) {\n if (!skipDirs.has(entry.name)) walk(path);\n continue;\n }\n if (!entry.name.endsWith(specSuffix)) continue;\n const modulePath = join(at, `${entry.name.slice(0, -specSuffix.length)}.ts`);\n const key = specKey(relative(dir, modulePath));\n if (!existsSync(modulePath)) {\n out.push({\n key,\n path: modulePath,\n specPath: path,\n specs: {\n functions: [],\n errors: [\n {\n line: 1,\n message: `${entry.name} has no module ${basename(modulePath)} beside it`,\n },\n ],\n },\n });\n continue;\n }\n out.push({ key, path: modulePath, specPath: path, specs: readSpecModule(modulePath, path) });\n }\n };\n walk(dir);\n return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n}\n\n/** A file `eutaxy check` writes into `.eutaxy/`, by its path there. */\nexport interface GeneratedFile {\n readonly name: string;\n readonly source: string;\n}\n\n/** A path as an import specifier from `.eutaxy/`: forward slashes, relative, `.ts` kept (Vite resolves it). */\nfunction importFrom(workDir: string, target: string): string {\n const rel = relative(workDir, target).split(\"\\\\\").join(\"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\n/**\n * The generated `specs.ts`: each module's key mapped to its specs (plain\n * data read on the Node side) and a loader of its spec file. The loader is\n * lazy, so a spec file elsewhere that does not compile cannot stop a check\n * of a scenario that does not name its module.\n */\nexport function specFiles(modules: readonly SpecModule[], workDir: string): GeneratedFile[] {\n const header = \"// Generated by eutaxy check; deleted after the run.\";\n const lines = [\n header,\n \"// The `any`: this file runs in the user's Vitest, which does not type-check it; `SpecEntry` in workerd.ts is the shape.\",\n \"export const specEntries: Record<string, { specs: any; load: () => Promise<any> }> = {\",\n ...modules.map(\n (m) =>\n ` ${JSON.stringify(m.key)}: { specs: ${JSON.stringify(m.specs)}, load: () => import(${JSON.stringify(importFrom(workDir, m.specPath))}) },`,\n ),\n \"};\",\n ];\n return [{ name: \"specs.ts\", source: `${lines.join(\"\\n\")}\\n` }];\n}\n\n/** The directory a generated file's import is resolved from. */\nexport function specWorkDir(dir: string): string {\n return dirname(join(dir, \".eutaxy\", \"specs.ts\"));\n}\n","/**\n * `eutaxy check <scenario.sim.ts>`: run a scenario inside workerd through\n * the user's Vitest and the Cloudflare plugin, print the verdict as text or\n * JSON, and on a violation write a regression test next to the scenario.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport {\n canonicalJson,\n type JsonValue,\n type ScenarioVerdict,\n type SpecVerdict,\n type Violated,\n} from \"@eutaxy/core\";\nimport { aggregate, type EngineReport, type Prover } from \"@eutaxy/prover\";\nimport { leanProver } from \"@eutaxy/prover-lean\";\nimport { smtProver } from \"@eutaxy/prover-smt\";\nimport { renderSpecs, renderText } from \"@eutaxy/report\";\nimport { checkTestSource, metaKey, vitestConfigSource } from \"./generate.ts\";\nimport { cloudflareRegressionTest } from \"./regression.ts\";\nimport { findSpecModules, type SpecModule, specFiles, specKey } from \"./specs.ts\";\nimport type { CheckTransport } from \"./workerd.ts\";\n\nexport interface CheckOptions {\n readonly scenario: string;\n readonly cwd: string;\n readonly wrangler?: string;\n readonly seed?: string;\n readonly maxRuns?: number;\n /** Replaces the scenario's time budget. */\n readonly budgetMs?: number;\n /** Run every schedule within the bounds once instead of drawing them from the seed. */\n readonly exhaustive?: boolean;\n /** Engines to run the PROVEN rung with, by name, on the scenario's spec modules. */\n readonly provers?: readonly string[];\n readonly json: boolean;\n /** Where to write the regression test on a violation; default `<name>.regression.test.ts` beside the scenario. */\n readonly out?: string;\n readonly noRegression: boolean;\n /** Emit a regression test that asserts the violation (for corpora) rather than one that expects it fixed. */\n readonly expectViolation: boolean;\n /** Keep the generated `.eutaxy/` files for inspection. */\n readonly keep: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport const exitCodes = { BOUNDED: 0, VIOLATED: 1, UNSUPPORTED: 2, error: 3 } as const;\n\n/** The engines `--prover` can name. */\nexport const provers: Readonly<Record<string, Prover>> = { lean: leanProver, smt: smtProver };\n\n/** The engines named, or the error naming the first unknown one. */\nexport function enginesNamed(\n names: readonly string[],\n): { readonly engines: Prover[] } | { readonly error: string } {\n const engines: Prover[] = [];\n for (const name of names) {\n const engine = provers[name];\n if (!engine)\n return { error: `unknown prover ${name}; known: ${Object.keys(provers).join(\", \")}` };\n engines.push(engine);\n }\n return { engines };\n}\n\n/**\n * The PROVEN rung, on the Node side: each engine on each observed spec\n * module's source, the outcomes folded into the simulator's verdicts.\n * An engine that is not installed proves nothing and says so.\n */\nexport async function proveSpecs(\n dir: string,\n observed: readonly { readonly module: string; readonly functions: readonly string[] }[],\n specs: readonly SpecVerdict[],\n engines: readonly Prover[],\n modules: readonly SpecModule[] = findSpecModules(dir),\n /** Told each engine's report on each module, for what the verdicts do not carry: the open goals. */\n onReport?: (module: SpecModule, report: EngineReport) => void,\n): Promise<readonly SpecVerdict[]> {\n let out = specs;\n for (const m of observed) {\n // Verdicts carry the module as a normalized key (\"./domain.ts\"); the observed path is as the scenario wrote it.\n const key = specKey(m.module);\n const found = modules.find((s) => s.key === key);\n const withSpecs = m.functions.filter((f) =>\n specs.some((v) => v.module === key && v.function === f),\n );\n if (!found || withSpecs.length === 0) continue;\n const source = readFileSync(found.path, \"utf8\");\n const reports: EngineReport[] = [];\n for (const engine of engines) {\n const report: EngineReport = {\n engine: engine.name,\n proofs: await engine.prove({\n source,\n specs: found.specs,\n functions: withSpecs,\n modulePath: found.path,\n specPath: found.specPath,\n }),\n };\n reports.push(report);\n onReport?.(found, report);\n }\n out = aggregate(key, out, reports);\n }\n return out;\n}\n\nfunction findWrangler(dir: string, explicit: string | undefined, cwd: string): string | null {\n if (explicit) return resolve(cwd, explicit);\n for (const name of [\"wrangler.jsonc\", \"wrangler.json\", \"wrangler.toml\"]) {\n const p = join(dir, name);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction vitestBin(from: string): string {\n const req = createRequire(join(from, \"package.json\"));\n return join(dirname(req.resolve(\"vitest/package.json\")), \"vitest.mjs\");\n}\n\nfunction runVitest(\n bin: string,\n configPath: string,\n cwd: string,\n): Promise<{ code: number; output: string }> {\n return new Promise((resolveRun) => {\n const child = spawn(process.execPath, [bin, \"run\", \"--config\", configPath], {\n cwd,\n env: { ...process.env, CI: \"1\", FORCE_COLOR: \"0\" },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let output = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n output += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n output += d.toString();\n });\n child.on(\"close\", (code) => resolveRun({ code: code ?? 1, output }));\n });\n}\n\n/** The transport the generated test left in its task meta, via Vitest's JSON reporter. */\nfunction readTransport(reportPath: string): CheckTransport | null {\n if (!existsSync(reportPath)) return null;\n const report = JSON.parse(readFileSync(reportPath, \"utf8\")) as {\n testResults?: { assertionResults?: { meta?: Record<string, unknown> }[] }[];\n };\n for (const file of report.testResults ?? []) {\n for (const t of file.assertionResults ?? []) {\n const m = t.meta?.[metaKey];\n if (m) return m as CheckTransport;\n }\n }\n return null;\n}\n\nfunction toPosix(p: string): string {\n const s = p.split(\"\\\\\").join(\"/\");\n return s.startsWith(\".\") ? s : `./${s}`;\n}\n\nexport async function runCheck(o: CheckOptions): Promise<number> {\n const scenarioPath = resolve(o.cwd, o.scenario);\n if (!existsSync(scenarioPath)) {\n o.stderr(`scenario not found: ${scenarioPath}\\n`);\n return exitCodes.error;\n }\n const dir = dirname(scenarioPath);\n const name = basename(scenarioPath)\n .replace(/\\.sim\\.ts$/, \"\")\n .replace(/\\.ts$/, \"\");\n const wrangler = findWrangler(dir, o.wrangler, o.cwd);\n if (!wrangler || !existsSync(wrangler)) {\n o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\\n`);\n return exitCodes.error;\n }\n const workDir = join(dir, \".eutaxy\");\n const testPath = join(workDir, `${name}.check.test.ts`);\n const configPath = join(workDir, \"vitest.config.mts\");\n mkdirSync(workDir, { recursive: true });\n try {\n writeFileSync(\n testPath,\n checkTestSource({\n seed: o.seed ?? name,\n ...(o.maxRuns === undefined ? {} : { maxRuns: o.maxRuns }),\n ...(o.budgetMs === undefined ? {} : { budgetMs: o.budgetMs }),\n ...(o.exhaustive ? { exhaustive: true } : {}),\n scenarioImport: `../${basename(scenarioPath)}`,\n }),\n );\n const specModules = findSpecModules(dir);\n for (const f of specFiles(specModules, workDir)) {\n mkdirSync(dirname(join(workDir, f.name)), { recursive: true });\n writeFileSync(join(workDir, f.name), f.source);\n }\n const reportPath = join(workDir, \"vitest-report.json\");\n rmSync(reportPath, { force: true }); // never read a report left by an earlier --keep run\n writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));\n const { code, output } = await runVitest(vitestBin(dir), configPath, dir);\n const transport = code === 0 ? readTransport(reportPath) : null;\n if (!transport) {\n o.stderr(`eutaxy check could not read a verdict from Vitest (exit ${code}):\\n${output}\\n`);\n return exitCodes.error;\n }\n if (transport.specErrors && transport.specErrors.length > 0) {\n for (const e of transport.specErrors)\n o.stderr(`${e.module}${e.line > 0 ? `:${e.line}` : \"\"}: ${e.message}\\n`);\n return exitCodes.error;\n }\n const report = transport.report as { verdict: ScenarioVerdict; specs?: readonly SpecVerdict[] };\n const verdict = report.verdict;\n let specs = report.specs ?? [];\n if (o.provers && o.provers.length > 0) {\n const named = enginesNamed(o.provers);\n if (\"error\" in named) {\n o.stderr(`${named.error}\\n`);\n return exitCodes.error;\n }\n specs = await proveSpecs(dir, transport.observed ?? [], specs, named.engines, specModules);\n }\n // The regression test's path goes into the JSON report too (an optional field of schema 1), so a\n // caller that reads the report knows where the replay is without parsing the text.\n const regressionPath =\n verdict.kind === \"VIOLATED\" && !o.noRegression\n ? o.out\n ? resolve(o.cwd, o.out)\n : join(dir, `${name}.regression.test.ts`)\n : undefined;\n const printed = {\n ...(transport.report as object),\n ...(o.provers && o.provers.length > 0 ? { specs } : {}),\n ...(regressionPath === undefined\n ? {}\n : { regressionTest: toPosix(relative(o.cwd, regressionPath) || regressionPath) }),\n };\n if (o.json) o.stdout(`${canonicalJson(printed as JsonValue)}\\n`);\n else o.stdout(`${renderText(verdict)}\\n${specs.length > 0 ? `\\n${renderSpecs(specs)}\\n` : \"\"}`);\n\n if (regressionPath !== undefined) {\n const outPath = regressionPath;\n const outDir = dirname(outPath);\n const schemaPaths: Record<string, string> = {};\n for (const step of transport.setup) {\n if (step.kind === \"d1\") {\n schemaPaths[String(step[\"binding\"])] = toPosix(\n relative(outDir, resolve(dir, String(step[\"schemaFile\"]))),\n );\n }\n }\n const source = cloudflareRegressionTest(verdict as Violated, {\n scenarioPath: toPosix(relative(outDir, scenarioPath)),\n workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),\n schemaPaths,\n ...(o.budgetMs === undefined ? {} : { budgetMs: o.budgetMs }),\n ...(transport.setup.some((s) => s.kind === \"durable_object\")\n ? { durableObjects: true }\n : {}),\n ...(transport.setup.some((s) => s.kind === \"workflow\") ||\n (transport.drive?.kind === \"rpc\" && transport.drive[\"entrypoint\"] !== undefined)\n ? { exports: true }\n : {}),\n ...(o.expectViolation ? { expect: \"violates\" as const } : {}),\n ...((transport.observed ?? []).length > 0\n ? {\n specModules: (transport.observed ?? []).map((m) => ({\n path: toPosix(relative(outDir, resolve(dir, m.module))),\n functions: m.functions,\n })),\n }\n : {}),\n });\n mkdirSync(outDir, { recursive: true });\n writeFileSync(outPath, source);\n if (!o.json)\n o.stdout(`\\nRegression test written to ${relative(o.cwd, outPath) || outPath}\\n`);\n }\n // A refuted spec fails the check like a violation does; so does a conflict between engines.\n if (\n verdict.kind !== \"VIOLATED\" &&\n specs.some((v) => v.kind === \"REFUTED\" || v.kind === \"CONFLICT\")\n )\n return exitCodes.VIOLATED;\n return exitCodes[verdict.kind];\n } finally {\n if (!o.keep) rmSync(workDir, { recursive: true, force: true });\n }\n}\n","/**\n * Reading the two archive formats the prover releases come in, with Node's\n * standard library alone: a tar stream compressed with zstd (Lean) and a zip\n * (Z3). Entries are written under one destination directory; an entry whose\n * path would leave it, or a link pointing out of it, is refused, since the\n * archive is downloaded. The tar is read as it decompresses, so a release\n * of hundreds of megabytes never sits in memory; a zip is read from its\n * central directory, entry by entry.\n */\n\nimport {\n chmodSync,\n closeSync,\n copyFileSync,\n createReadStream,\n existsSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n symlinkSync,\n writeFileSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport { createZstdDecompress, inflateRawSync } from \"node:zlib\";\n\nexport class ArchiveError extends Error {}\n\n/** The entry's place under `dest`, refused when it would be outside. */\nfunction placeOf(dest: string, name: string): string {\n if (name.includes(\"\\0\")) throw new ArchiveError(\"an entry name holds a NUL byte\");\n const target = resolve(dest, name);\n if (target !== dest && !target.startsWith(dest + sep))\n throw new ArchiveError(\n `entry ${JSON.stringify(name)} would be written outside the toolchain directory`,\n );\n return target;\n}\n\n/** A symlink's target must stay under `dest` too. */\nfunction checkLink(dest: string, at: string, linkTo: string): void {\n const target = resolve(dirname(at), linkTo);\n if (target !== dest && !target.startsWith(dest + sep))\n throw new ArchiveError(\n `link ${JSON.stringify(linkTo)} would point outside the toolchain directory`,\n );\n}\n\nfunction ensureDir(dir: string): void {\n mkdirSync(dir, { recursive: true });\n}\n\nfunction setMode(path: string, mode: number): void {\n if (process.platform === \"win32\") return;\n const bits = mode & 0o777;\n if (bits !== 0) chmodSync(path, bits | 0o600);\n}\n\n/** Tar header fields, from a 512-byte block. */\ninterface TarHeader {\n readonly name: string;\n readonly mode: number;\n readonly size: number;\n readonly type: string;\n readonly linkName: string;\n}\n\nconst text = (block: Buffer, start: number, length: number): string => {\n const slice = block.subarray(start, start + length);\n const end = slice.indexOf(0);\n return slice.subarray(0, end < 0 ? slice.length : end).toString(\"utf8\");\n};\n\n/** An octal field, or GNU base-256 when the high bit of the first byte is set. */\nconst numeric = (block: Buffer, start: number, length: number): number => {\n const first = block[start] as number;\n if (first & 0x80) {\n let n = 0;\n for (let i = start + 1; i < start + length; i++) n = n * 256 + (block[i] as number);\n return n;\n }\n const t = text(block, start, length).trim();\n return t.length === 0 ? 0 : Number.parseInt(t, 8);\n};\n\nfunction parseHeader(block: Buffer): TarHeader {\n const magic = text(block, 257, 6);\n const name = text(block, 0, 100);\n const prefix = magic.startsWith(\"ustar\") ? text(block, 345, 155) : \"\";\n return {\n name: prefix.length > 0 ? `${prefix}/${name}` : name,\n mode: numeric(block, 100, 8),\n size: numeric(block, 124, 12),\n type: block[156] === 0 ? \"0\" : String.fromCharCode(block[156] as number),\n linkName: text(block, 157, 100),\n };\n}\n\n/** `length key=value\\n` records of a pax extended header. */\nfunction paxRecords(data: Buffer): Map<string, string> {\n const out = new Map<string, string>();\n let at = 0;\n while (at < data.length) {\n const space = data.indexOf(0x20, at);\n if (space < 0) break;\n const length = Number.parseInt(data.subarray(at, space).toString(\"latin1\"), 10);\n if (!Number.isInteger(length) || length <= 0) break;\n const record = data.subarray(space + 1, at + length - 1).toString(\"utf8\");\n const eq = record.indexOf(\"=\");\n if (eq > 0) out.set(record.slice(0, eq), record.slice(eq + 1));\n at += length;\n }\n return out;\n}\n\n/** Where an entry's remaining bytes go: a file being written, a small header read whole, or nowhere. */\ntype Sink =\n | { readonly fd: number; readonly at: string; readonly mode: number }\n | { readonly chunks: Buffer[]; readonly kind: \"pax\" | \"longname\" }\n | { readonly skip: true };\n\n/**\n * Reads a tar stream block by block as its chunks arrive. A file entry's\n * bytes are written to disk as they come; pax and GNU long-name entries are\n * read into memory (they are small) and apply to the entry that follows.\n */\nclass TarReader {\n readonly dest: string;\n buffer: Buffer = Buffer.alloc(0);\n current: { remaining: number; padding: number; sink: Sink } | undefined;\n /** Overrides for the next entry from a pax or long-name entry. */\n next: { path?: string; linkpath?: string; size?: number } = {};\n zeroBlocks = 0;\n ended = false;\n entries = 0;\n\n constructor(dest: string) {\n this.dest = dest;\n }\n\n push(chunk: Buffer): void {\n this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk]);\n for (;;) {\n if (this.ended) return;\n if (this.current) {\n const take = Math.min(this.current.remaining, this.buffer.length);\n if (take > 0) {\n const part = this.buffer.subarray(0, take);\n if (\"fd\" in this.current.sink) writeSync(this.current.sink.fd, part);\n else if (\"chunks\" in this.current.sink) this.current.sink.chunks.push(Buffer.from(part));\n this.buffer = this.buffer.subarray(take);\n this.current.remaining -= take;\n }\n if (this.current.remaining > 0) return;\n const skip = Math.min(this.current.padding, this.buffer.length);\n this.buffer = this.buffer.subarray(skip);\n this.current.padding -= skip;\n if (this.current.padding > 0) return;\n this.finish();\n continue;\n }\n if (this.buffer.length < 512) return;\n const block = this.buffer.subarray(0, 512);\n this.buffer = this.buffer.subarray(512);\n if (block.every((b) => b === 0)) {\n if (++this.zeroBlocks >= 2) this.ended = true;\n continue;\n }\n this.zeroBlocks = 0;\n this.begin(parseHeader(block));\n }\n }\n\n begin(header: TarHeader): void {\n const size = this.next.size ?? header.size;\n const padding = (512 - (size % 512)) % 512;\n if (header.type === \"x\" || header.type === \"L\") {\n const kind = header.type === \"x\" ? \"pax\" : \"longname\";\n this.current = { remaining: size, padding, sink: { chunks: [], kind } };\n return;\n }\n const name = this.next.path ?? header.name;\n const linkName = this.next.linkpath ?? header.linkName;\n this.next = {};\n this.entries++;\n const at = placeOf(this.dest, name);\n if (header.type === \"0\" || header.type === \"7\") {\n ensureDir(dirname(at));\n const fd = openSync(at, \"w\");\n this.current = { remaining: size, padding, sink: { fd, at, mode: header.mode } };\n if (size === 0) this.finish();\n return;\n }\n if (header.type === \"5\") ensureDir(at);\n else if (header.type === \"2\") {\n checkLink(this.dest, at, linkName);\n ensureDir(dirname(at));\n rmSync(at, { force: true });\n symlinkSync(linkName, at);\n } else if (header.type === \"1\") {\n ensureDir(dirname(at));\n copyFileSync(placeOf(this.dest, linkName), at);\n }\n // Devices, FIFOs and vendor types carry nothing a toolchain needs; data any of these has is skipped.\n if (size > 0) this.current = { remaining: size, padding, sink: { skip: true } };\n }\n\n finish(): void {\n const current = this.current as NonNullable<TarReader[\"current\"]>;\n this.current = undefined;\n if (\"fd\" in current.sink) {\n closeSync(current.sink.fd);\n setMode(current.sink.at, current.sink.mode);\n return;\n }\n if (!(\"chunks\" in current.sink)) return;\n const data = Buffer.concat(current.sink.chunks);\n if (current.sink.kind === \"longname\") {\n this.next.path = text(data, 0, data.length);\n return;\n }\n const records = paxRecords(data);\n const path = records.get(\"path\");\n const linkpath = records.get(\"linkpath\");\n const size = records.get(\"size\");\n if (path !== undefined) this.next.path = path;\n if (linkpath !== undefined) this.next.linkpath = linkpath;\n if (size !== undefined) this.next.size = Number(size);\n }\n\n /** Close the file being written, if any. */\n release(): void {\n if (this.current && \"fd\" in this.current.sink) closeSync(this.current.sink.fd);\n }\n\n end(): void {\n this.release();\n if (this.current)\n throw new ArchiveError(\"the tar stream ended inside an entry; the file is truncated\");\n }\n}\n\n/** Unpack a zstd-compressed tar into `dest`, which must exist and be empty. */\nexport async function extractTarZst(file: string, dest: string): Promise<number> {\n const reader = new TarReader(resolve(dest));\n const source = createReadStream(file).pipe(createZstdDecompress());\n try {\n for await (const chunk of source) reader.push(chunk as Buffer);\n } catch (err) {\n reader.release();\n source.destroy();\n throw err;\n }\n reader.end();\n return reader.entries;\n}\n\nconst ZIP_EOCD = 0x06054b50;\nconst ZIP64_EOCD = 0x06064b50;\nconst ZIP64_LOCATOR = 0x07064b50;\nconst ZIP_CENTRAL = 0x02014b50;\nconst ZIP_LOCAL = 0x04034b50;\n\n/** The central directory's position and entry count, through the zip64 records when the plain ones overflow. */\nfunction centralDirectory(zip: Buffer): { offset: number; entries: number } {\n const start = Math.max(0, zip.length - 22 - 65_535);\n let eocd = -1;\n for (let i = zip.length - 22; i >= start; i--)\n if (zip.readUInt32LE(i) === ZIP_EOCD) {\n eocd = i;\n break;\n }\n if (eocd < 0) throw new ArchiveError(\"not a zip file: no end-of-central-directory record\");\n let entries: number = zip.readUInt16LE(eocd + 10);\n let offset: number = zip.readUInt32LE(eocd + 16);\n if (entries === 0xffff || offset === 0xffffffff) {\n const locator = eocd - 20;\n if (locator < 0 || zip.readUInt32LE(locator) !== ZIP64_LOCATOR)\n throw new ArchiveError(\"zip64 archive without its locator\");\n const at = Number(zip.readBigUInt64LE(locator + 8));\n if (zip.readUInt32LE(at) !== ZIP64_EOCD)\n throw new ArchiveError(\"zip64 archive without its end record\");\n entries = Number(zip.readBigUInt64LE(at + 32));\n offset = Number(zip.readBigUInt64LE(at + 48));\n }\n return { offset, entries };\n}\n\n/** Sizes and offset of one entry, from its zip64 extra field when the plain ones overflow. */\nfunction zip64Fields(\n extra: Buffer,\n plain: { compressed: number; uncompressed: number; offset: number },\n): { compressed: number; uncompressed: number; offset: number } {\n let at = 0;\n while (at + 4 <= extra.length) {\n const id = extra.readUInt16LE(at);\n const size = extra.readUInt16LE(at + 2);\n if (id === 0x0001) {\n let p = at + 4;\n const out = { ...plain };\n if (out.uncompressed === 0xffffffff) {\n out.uncompressed = Number(extra.readBigUInt64LE(p));\n p += 8;\n }\n if (out.compressed === 0xffffffff) {\n out.compressed = Number(extra.readBigUInt64LE(p));\n p += 8;\n }\n if (out.offset === 0xffffffff) out.offset = Number(extra.readBigUInt64LE(p));\n return out;\n }\n at += 4 + size;\n }\n return plain;\n}\n\n/** Unpack a zip into `dest`, which must exist and be empty. */\nexport function extractZip(file: string, dest: string): number {\n const root = resolve(dest);\n const zip = readFileSync(file);\n const { offset, entries } = centralDirectory(zip);\n let at = offset;\n for (let i = 0; i < entries; i++) {\n if (zip.readUInt32LE(at) !== ZIP_CENTRAL)\n throw new ArchiveError(\"a central directory entry is not where the zip says it is\");\n const madeBy = zip.readUInt16LE(at + 4) >> 8;\n const method = zip.readUInt16LE(at + 10);\n const nameLength = zip.readUInt16LE(at + 28);\n const extraLength = zip.readUInt16LE(at + 30);\n const commentLength = zip.readUInt16LE(at + 32);\n const externalAttributes = zip.readUInt32LE(at + 38);\n const name = zip.subarray(at + 46, at + 46 + nameLength).toString(\"utf8\");\n const extra = zip.subarray(at + 46 + nameLength, at + 46 + nameLength + extraLength);\n const sizes = zip64Fields(extra, {\n compressed: zip.readUInt32LE(at + 20),\n uncompressed: zip.readUInt32LE(at + 24),\n offset: zip.readUInt32LE(at + 42),\n });\n at += 46 + nameLength + extraLength + commentLength;\n const local = sizes.offset;\n if (zip.readUInt32LE(local) !== ZIP_LOCAL)\n throw new ArchiveError(\n `entry ${JSON.stringify(name)} has no local header where the zip says`,\n );\n const dataStart = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);\n const raw = zip.subarray(dataStart, dataStart + sizes.compressed);\n const mode = madeBy === 3 ? externalAttributes >>> 16 : 0;\n const place = placeOf(root, name);\n const isDirectory = name.endsWith(\"/\") || (mode & 0o170000) === 0o040000;\n if (isDirectory) {\n ensureDir(place);\n continue;\n }\n let data: Buffer;\n if (method === 0) data = raw;\n else if (method === 8) data = inflateRawSync(raw);\n else\n throw new ArchiveError(\n `entry ${JSON.stringify(name)} uses compression method ${method}; only stored and deflated entries are read`,\n );\n if (data.length !== sizes.uncompressed)\n throw new ArchiveError(`entry ${JSON.stringify(name)} did not inflate to its declared size`);\n ensureDir(dirname(place));\n if ((mode & 0o170000) === 0o120000) {\n const linkTo = data.toString(\"utf8\");\n checkLink(root, place, linkTo);\n rmSync(place, { force: true });\n symlinkSync(linkTo, place);\n continue;\n }\n writeFileSync(place, data);\n setMode(place, mode);\n }\n return entries;\n}\n\n/**\n * When an archive puts everything under one top-level directory, as the\n * releases do (`lean-4.35.0-linux/`, `z3-5.3.2-x64-glibc-2.39/`), move\n * its contents up so the executable is at the path the table names.\n */\nexport function flattenSingleDirectory(dest: string): void {\n const entries = readdirSync(dest, { withFileTypes: true });\n if (entries.length !== 1 || !(entries[0] as { isDirectory(): boolean }).isDirectory()) return;\n const inner = join(dest, (entries[0] as { name: string }).name);\n for (const name of readdirSync(inner)) {\n const to = join(dest, name);\n if (existsSync(to)) throw new ArchiveError(`cannot flatten the archive: ${name} exists twice`);\n renameSync(join(inner, name), to);\n }\n rmSync(inner, { recursive: true, force: true });\n}\n","/**\n * `eutaxy prover install <name>`: the pinned release of a prover put in\n * Eutaxy's cache, where the engines look first. The file for this platform\n * is downloaded (or copied from a mirror or an offline directory given with\n * `--from`), its SHA-256 checked against the engine's table before anything\n * is unpacked, unpacked beside a marker written last, and deleted. A\n * mismatch or a failed download installs nothing. Nothing is run: the\n * engines check the version when they look the toolchain up.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n createReadStream,\n existsSync,\n mkdirSync,\n openSync,\n renameSync,\n rmSync,\n writeFileSync,\n writeSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport {\n cacheDir,\n executableName,\n type Host,\n host,\n type InstallMarker,\n installed,\n markerFile,\n type Platform,\n platformOf,\n platforms,\n type Toolchain,\n toolchainDir,\n} from \"@eutaxy/prover/toolchain\";\nimport { leanDownloads } from \"@eutaxy/prover-lean\";\nimport { z3Downloads } from \"@eutaxy/prover-smt\";\nimport { reportSchemaVersion } from \"@eutaxy/report\";\nimport { extractTarZst, extractZip, flattenSingleDirectory } from \"./archive.ts\";\nimport { exitCodes } from \"./check.ts\";\n\n/** The toolchains the command installs, by the engine name it takes. */\nexport const toolchains: Readonly<Record<string, Toolchain>> = {\n lean: leanDownloads,\n smt: z3Downloads,\n};\n\nexport class InstallError extends Error {}\n\nexport interface InstallOptions {\n readonly toolchain: Toolchain;\n readonly host?: Host;\n /** A mirror URL or a directory holding the release file under its upstream name. */\n readonly from?: string;\n /** How to download, for tests; the global `fetch` otherwise. */\n readonly fetch?: typeof fetch;\n /** Progress lines while a download runs. */\n readonly progress?: (text: string) => void;\n}\n\nexport interface InstallResult {\n readonly name: string;\n readonly version: string;\n readonly platform: Platform;\n readonly file: string;\n readonly source: string;\n readonly sha256: string;\n readonly bytes: number;\n readonly dir: string;\n readonly executable: string;\n /** False when the toolchain was already in the cache and nothing was downloaded. */\n readonly downloaded: boolean;\n}\n\nconst isUrl = (s: string): boolean => /^https?:\\/\\//.test(s);\n\n/** Write a byte stream to `path`, hashing it as it goes; the hash and the byte count come back. */\nasync function store(\n bytes: AsyncIterable<Uint8Array>,\n path: string,\n progress: ((written: number) => void) | undefined,\n): Promise<{ sha256: string; bytes: number }> {\n const hash = createHash(\"sha256\");\n const fd = openSync(path, \"w\");\n let written = 0;\n let reported = 0;\n try {\n for await (const chunk of bytes) {\n writeSync(fd, chunk);\n hash.update(chunk);\n written += chunk.byteLength;\n if (progress && written - reported >= 50_000_000) {\n reported = written;\n progress(written);\n }\n }\n } finally {\n closeSync(fd);\n }\n return { sha256: hash.digest(\"hex\"), bytes: written };\n}\n\nexport async function installToolchain(options: InstallOptions): Promise<InstallResult> {\n const { toolchain } = options;\n const h = options.host ?? host();\n const platform = platformOf(h);\n const release = platform === undefined ? undefined : toolchain.files[platform];\n if (platform === undefined || release === undefined)\n throw new InstallError(\n `no ${toolchain.name} ${toolchain.version} release for ${h.platform}-${h.arch}; the platforms are ${platforms.join(\", \")}`,\n );\n const cache = cacheDir(h);\n const dir = toolchainDir(cache, toolchain);\n const already = installed(toolchain, h);\n if (already)\n return {\n name: toolchain.name,\n version: toolchain.version,\n platform,\n file: already.marker.file,\n source: already.marker.source,\n sha256: already.marker.sha256,\n bytes: release.bytes,\n dir,\n executable: already.executable,\n downloaded: false,\n };\n const source =\n options.from === undefined\n ? release.url\n : isUrl(options.from)\n ? `${options.from.replace(/\\/+$/, \"\")}/${release.file}`\n : join(options.from, release.file);\n // Staging paths of this invocation alone, so two installs sharing a cache never touch each other's files.\n const stamp = `${process.pid}-${randomBytes(4).toString(\"hex\")}`;\n const downloads = join(cache, \"downloads\");\n const archive = join(downloads, `${release.file}.${stamp}.part`);\n const mb = (n: number) => `${Math.round(n / 1_000_000)} MB`;\n try {\n mkdirSync(downloads, { recursive: true });\n let bytes: AsyncIterable<Uint8Array>;\n if (isUrl(source)) {\n const fetchImpl = options.fetch ?? fetch;\n let response: Response;\n try {\n response = await fetchImpl(source);\n } catch (err) {\n throw new InstallError(\n `could not download ${source}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (!response.ok || response.body === null)\n throw new InstallError(\n `could not download ${source}: HTTP ${response.status} ${response.statusText}`,\n );\n options.progress?.(`downloading ${release.file} (${mb(release.bytes)}) from ${source}`);\n bytes = Readable.fromWeb(response.body as import(\"node:stream/web\").ReadableStream);\n } else {\n if (!existsSync(source)) throw new InstallError(`no ${release.file} in ${options.from}`);\n bytes = createReadStream(source);\n }\n let stored: { sha256: string; bytes: number };\n try {\n stored = await store(bytes, archive, (n) =>\n options.progress?.(`${mb(n)} of ${mb(release.bytes)}`),\n );\n } catch (err) {\n throw new InstallError(\n `could not download ${source}: ${err instanceof Error ? err.message : String(err)}; nothing was installed`,\n );\n }\n if (stored.sha256 !== release.sha256)\n throw new InstallError(\n `checksum mismatch for ${release.file} from ${source}: expected sha256 ${release.sha256}, got ${stored.sha256} (${stored.bytes} bytes, ${release.bytes} expected); nothing was installed`,\n );\n const partial = `${dir}.partial-${stamp}`;\n mkdirSync(partial, { recursive: true });\n try {\n options.progress?.(`unpacking ${release.file}`);\n if (release.file.endsWith(\".zip\")) extractZip(archive, partial);\n else if (release.file.endsWith(\".tar.zst\")) await extractTarZst(archive, partial);\n else throw new InstallError(`${release.file} is neither a .zip nor a .tar.zst`);\n flattenSingleDirectory(partial);\n const executable = executableName(toolchain, h);\n if (!existsSync(join(partial, executable)))\n throw new InstallError(`${release.file} holds no ${executable}; nothing was installed`);\n // The named executable must run whatever mode the archive gave it (a zip made elsewhere carries none).\n if (h.platform !== \"win32\") chmodSync(join(partial, executable), 0o755);\n const marker: InstallMarker = {\n name: toolchain.name,\n version: toolchain.version,\n platform,\n file: release.file,\n sha256: stored.sha256,\n source,\n };\n writeFileSync(join(partial, markerFile), `${JSON.stringify(marker, null, 2)}\\n`);\n rmSync(dir, { recursive: true, force: true });\n renameSync(partial, dir);\n } catch (err) {\n rmSync(partial, { recursive: true, force: true });\n throw err instanceof InstallError\n ? err\n : new InstallError(\n `could not unpack ${release.file}: ${err instanceof Error ? err.message : String(err)}; nothing was installed`,\n );\n }\n return {\n name: toolchain.name,\n version: toolchain.version,\n platform,\n file: release.file,\n source,\n sha256: stored.sha256,\n bytes: stored.bytes,\n dir,\n executable: join(dir, executableName(toolchain, h)),\n downloaded: true,\n };\n } catch (err) {\n // Anything but an install error here is the file system refusing (the cache not writable, say).\n throw err instanceof InstallError\n ? err\n : new InstallError(\n `could not install ${toolchain.name} ${toolchain.version} in ${cache}: ${err instanceof Error ? err.message : String(err)}`,\n );\n } finally {\n try {\n rmSync(archive, { force: true });\n } catch {\n // The download never got there (the cache is not a directory, say); the error above says why.\n }\n }\n}\n\nexport interface RunInstallOptions {\n readonly toolchain: Toolchain;\n readonly from?: string | undefined;\n readonly json: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n readonly host?: Host;\n readonly fetch?: typeof fetch;\n}\n\n/** The command: the result as text or `--json` on stdout, progress and errors on stderr; exit 0, or 3 on an error. */\nexport async function runInstall(options: RunInstallOptions): Promise<number> {\n try {\n const result = await installToolchain({\n toolchain: options.toolchain,\n ...(options.host === undefined ? {} : { host: options.host }),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n ...(options.from === undefined ? {} : { from: options.from }),\n progress: (text) => options.stderr(`${text}\\n`),\n });\n if (options.json) {\n options.stdout(\n `${JSON.stringify({ schemaVersion: reportSchemaVersion, command: \"prover install\", ...result }, null, 2)}\\n`,\n );\n } else if (result.downloaded) {\n options.stdout(\n `${result.name} ${result.version} installed in ${result.dir}\\n ${result.file} from ${result.source}\\n sha256 ${result.sha256}\\n`,\n );\n } else {\n options.stdout(\n `${result.name} ${result.version} already installed in ${result.dir} (${result.file}, sha256 ${result.sha256})\\n`,\n );\n }\n return exitCodes.BOUNDED;\n } catch (err) {\n if (!(err instanceof InstallError)) throw err;\n options.stderr(`${err.message}\\n`);\n return exitCodes.error;\n }\n}\n","/**\n * `eutaxy report [dir]`: every spec file under a directory through the\n * ladder, on the Node side. No scenario runs, so the ladder starts at\n * `TESTED` (inputs drawn from the parameter types); `--prover` adds the\n * `PROVEN` rung. Each module runs in a child process of its own, started\n * on this file: what the module prints goes to stderr, its state starts\n * fresh, and a property that never returns ends with the module's budget.\n * A process, not a worker thread: Node strips types with WebAssembly, and\n * V8 shares compiled wasm code between the threads of a process; V8 on\n * Node 24 can abort while one thread frees that code as another uses it\n * (seen as SIGSEGV, SIGBUS or SIGTRAP of the whole process).\n * A module that only loads inside workerd gets `UNKNOWN` until an engine\n * reads it.\n */\n\nimport { fork } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { registerHooks } from \"node:module\";\nimport { basename, relative, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { canonicalJson, type JsonValue, type SpecVerdict } from \"@eutaxy/core\";\nimport { checkSpecModule, type OpenGoal, type Prover } from \"@eutaxy/prover\";\nimport { goalFileFor, leanProver, renderGoals } from \"@eutaxy/prover-lean\";\nimport { renderSpecReport, renderSpecReportJson } from \"@eutaxy/report\";\nimport { enginesNamed, exitCodes, proveSpecs } from \"./check.ts\";\nimport { findSpecModules, type SpecModule } from \"./specs.ts\";\n\nexport interface ReportOptions {\n /** The directory to search for spec files, relative to `cwd`; default `cwd` itself. */\n readonly dir?: string;\n readonly cwd: string;\n /** The seed the `TESTED` rung draws from; default \"report\". */\n readonly seed?: string;\n /** Engines to run the `PROVEN` rung with, by name. */\n readonly provers?: readonly string[];\n /** How long one module's properties may take at `TESTED`; default 60 s. */\n readonly moduleBudgetMs?: number;\n /** Only the module whose spec file this is (a path, relative to `cwd`), for a proof checked on its own. */\n readonly only?: string;\n /** Write each module's open Lean goals beside its spec file (`<spec>.goals.lean`) and list them. */\n readonly goals?: boolean;\n readonly json: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\n/** The argument a module's process is started with, so this file knows to run it. */\nconst moduleFlag = \"--eutaxy-report-module\";\n\ninterface ModuleInput {\n readonly module: SpecModule;\n readonly seed: string;\n}\n\n/** What a module's process sends back; tagged, since the module itself may call `process.send`. */\ninterface ModuleOutput {\n readonly kind: \"eutaxy-report-verdicts\";\n readonly verdicts: SpecVerdict[];\n}\n\nfunction unknownAll(\n m: SpecModule,\n cause: \"gave_up\" | \"unavailable\",\n reason: string,\n): SpecVerdict[] {\n return m.specs.functions.flatMap((fn) =>\n fn.properties.map(\n (p): SpecVerdict => ({\n module: m.key,\n function: fn.name,\n property: p.name,\n text: p.text,\n kind: \"UNKNOWN\",\n cause,\n reason,\n assumptions: [],\n }),\n ),\n );\n}\n\n/**\n * Inside the module's process: a relative import from a `.ts` file that Node cannot\n * resolve is tried as TypeScript resolves it, so `./domain.js` and\n * `./domain` find `domain.ts` (or `domain/index.ts`), as `tsc` would.\n */\nfunction resolveAsTypeScript(): void {\n registerHooks({\n resolve(specifier, context, nextResolve) {\n try {\n return nextResolve(specifier, context);\n } catch (err) {\n const relative = specifier.startsWith(\"./\") || specifier.startsWith(\"../\");\n if (!relative || !context.parentURL?.endsWith(\".ts\")) throw err;\n const stem = specifier.endsWith(\".js\") ? specifier.slice(0, -3) : specifier;\n for (const candidate of [`${stem}.ts`, `${stem}/index.ts`]) {\n try {\n return nextResolve(candidate, context);\n } catch {}\n }\n throw err;\n }\n },\n });\n}\n\n/** Inside the module's process: load the module and its spec file, run the `TESTED` rung. */\nasync function testHere(m: SpecModule, seed: string): Promise<SpecVerdict[]> {\n resolveAsTypeScript();\n let namespace: Readonly<Record<string, unknown>>;\n let props: Readonly<Record<string, unknown>>;\n try {\n namespace = (await import(pathToFileURL(m.path).href)) as Record<string, unknown>;\n props = (await import(pathToFileURL(m.specPath).href)) as Record<string, unknown>;\n } catch (err) {\n return unknownAll(\n m,\n \"unavailable\",\n `the module or its spec file did not load in Node: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return checkSpecModule(\n m.key,\n m.specs,\n props,\n namespace,\n { calls: [], unobservable: {} },\n { checked: false, tested: { seed } },\n );\n}\n\nconst send = process.send?.bind(process);\nif (process.argv[2] === moduleFlag && send) {\n process.once(\"disconnect\", () => process.exit(0));\n process.once(\"message\", async (input: ModuleInput) => {\n const verdicts = await testHere(input.module, input.seed);\n // Exit once the verdicts and everything the module wrote are out, whatever timers it left.\n send({ kind: \"eutaxy-report-verdicts\", verdicts } satisfies ModuleOutput, () =>\n process.stdout.write(\"\", () => process.stderr.write(\"\", () => process.exit(0))),\n );\n });\n}\n\n/**\n * One module's verdicts at the `TESTED` rung, from a child process. What\n * the module writes goes to `stderr`; a module that does not load, or does\n * not finish within the budget, leaves each property `UNKNOWN`.\n */\nexport function testModule(\n m: SpecModule,\n seed: string,\n budgetMs: number,\n stderr: (text: string) => void,\n): Promise<SpecVerdict[]> {\n return new Promise((done) => {\n const child = fork(fileURLToPath(import.meta.url), [moduleFlag], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n serialization: \"advanced\",\n });\n child.stdout?.on(\"data\", (d: Buffer) => stderr(d.toString()));\n child.stderr?.on(\"data\", (d: Buffer) => stderr(d.toString()));\n // Settled on `close`, once the process has exited and all it wrote is read; `reported` holds\n // its verdicts if it sent them, and `ended` why it stopped otherwise.\n let reported: SpecVerdict[] | undefined;\n let ended: SpecVerdict[] | undefined;\n let settled = false;\n const settle = (verdicts: SpecVerdict[]) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n done(verdicts);\n };\n const timer = setTimeout(() => {\n ended = unknownAll(\n m,\n \"gave_up\",\n `the module's properties did not finish within ${budgetMs} ms on generated inputs (one may never return)`,\n );\n child.kill(\"SIGKILL\");\n // A process the module started may still hold the pipes open.\n child.stdout?.destroy();\n child.stderr?.destroy();\n }, budgetMs);\n child.on(\"message\", (message: Partial<ModuleOutput> | null) => {\n if (message?.kind === \"eutaxy-report-verdicts\" && Array.isArray(message.verdicts))\n reported ??= message.verdicts;\n });\n child.once(\"error\", (err) => {\n ended ??= unknownAll(m, \"unavailable\", `the module's process failed: ${err.message}`);\n // A process that never started (no pid) emits no `close`.\n if (child.pid === undefined) settle(ended);\n else child.kill(\"SIGKILL\");\n });\n child.once(\"close\", (code, signal) => {\n settle(\n reported ??\n ended ??\n unknownAll(\n m,\n \"unavailable\",\n `the module's process exited (${signal ?? code}) before reporting`,\n ),\n );\n });\n child.send({ module: m, seed } satisfies ModuleInput);\n });\n}\n\n/** One open goal as the report lists it: where its goal file is, and the goal itself. */\nexport interface WrittenGoal extends OpenGoal {\n readonly module: string;\n /** The goal file, relative to the working directory. */\n readonly file: string;\n}\n\n/**\n * Write a module's open Lean goals beside its spec file as\n * `<spec>.goals.lean`, a proof file with every proof open, and list them.\n * No open goal removes a goal file left from an earlier run.\n */\nfunction writeGoals(m: SpecModule, goals: readonly OpenGoal[], cwd: string): WrittenGoal[] {\n const path = goalFileFor(m.specPath);\n if (goals.length === 0) {\n rmSync(path, { force: true });\n return [];\n }\n const sha = (text: string) => createHash(\"sha256\").update(text).digest(\"hex\");\n writeFileSync(\n path,\n renderGoals({\n specFile: basename(m.specPath),\n sourceSha256: sha(readFileSync(m.path, \"utf8\")),\n specSha256: sha(readFileSync(m.specPath, \"utf8\")),\n goals,\n }),\n );\n const file = relative(cwd, path).split(\"\\\\\").join(\"/\");\n return goals.map((g) => ({ module: m.key, file, ...g }));\n}\n\nexport async function runReport(o: ReportOptions): Promise<number> {\n const root = resolve(o.cwd, o.dir ?? \".\");\n let engines: Prover[] = [];\n if (o.provers && o.provers.length > 0) {\n const named = enginesNamed(o.provers);\n if (\"error\" in named) {\n o.stderr(`${named.error}\\n`);\n return exitCodes.error;\n }\n engines = named.engines;\n }\n let modules: SpecModule[];\n try {\n modules = findSpecModules(root);\n } catch (err) {\n o.stderr(`cannot read ${root}: ${err instanceof Error ? err.message : String(err)}\\n`);\n return exitCodes.error;\n }\n if (o.only !== undefined) {\n const spec = resolve(o.cwd, o.only);\n modules = modules.filter((m) => m.specPath === spec);\n if (modules.length === 0) {\n o.stderr(`no spec file ${spec} under ${root}\\n`);\n return exitCodes.error;\n }\n }\n if (modules.length === 0) {\n o.stderr(`no spec files (*.props.ts) under ${root}\\n`);\n return exitCodes.error;\n }\n if (o.goals && !engines.some((e) => e.name === leanProver.name)) {\n o.stderr(\"--goals needs the lean engine among --prover\\n\");\n return exitCodes.error;\n }\n const errors = modules.flatMap((m) =>\n m.specs.errors.map((e) => `${m.key}${e.line > 0 ? `:${e.line}` : \"\"}: ${e.message}`),\n );\n if (errors.length > 0) {\n for (const e of errors) o.stderr(`${e}\\n`);\n return exitCodes.error;\n }\n let specs: readonly SpecVerdict[] = [];\n for (const m of modules)\n specs = [\n ...specs,\n ...(await testModule(m, o.seed ?? \"report\", o.moduleBudgetMs ?? 60_000, o.stderr)),\n ];\n const goals: WrittenGoal[] = [];\n if (engines.length > 0)\n specs = await proveSpecs(\n root,\n modules.map((m) => ({ module: m.key, functions: m.specs.functions.map((f) => f.name) })),\n specs,\n engines,\n modules,\n o.goals\n ? (m, report) => {\n if (report.engine !== leanProver.name) return;\n // An engine that did not answer (not installed, timed out, or the emitted Lean did not\n // compile) lists no goals; a goal file left from an earlier run stands until it answers.\n if (report.proofs.goals === undefined) return;\n goals.push(...writeGoals(m, report.proofs.goals, o.cwd));\n }\n : undefined,\n );\n if (o.json) {\n const json = JSON.parse(renderSpecReportJson(specs)) as Record<string, unknown>;\n o.stdout(\n `${canonicalJson({ ...json, ...(o.goals ? { goals } : {}) } as unknown as JsonValue)}\\n`,\n );\n } else {\n o.stdout(`${renderSpecReport(specs)}\\n`);\n if (o.goals)\n o.stdout(\n goals.length === 0\n ? \"\\nNo open Lean goals.\\n\"\n : `\\n${goals.length} open Lean goal${goals.length === 1 ? \"\" : \"s\"} written to ${[...new Set(goals.map((g) => g.file))].join(\", \")}\\n`,\n );\n }\n // The codes check uses: 1 for a refuted or conflicting spec, 0 otherwise; UNKNOWN fails nothing.\n return specs.some((v) => v.kind === \"REFUTED\" || v.kind === \"CONFLICT\")\n ? exitCodes.VIOLATED\n : exitCodes.BOUNDED;\n}\n","/** The published package's version, as the MCP server reports it; the release tooling keeps it in step. */\nexport const eutaxyVersion = \"0.12.0\"; // x-release-please-version\n","/**\n * `eutaxy mcp`: a Model Context Protocol server over stdio, so a coding\n * agent runs the loop \"check, read the report, fix or prove, check again\"\n * through one tool. One JSON-RPC message per line on stdin and stdout,\n * logs on stderr, exit when stdin closes; written with the standard\n * library alone. It speaks both eras of the protocol: the stateless\n * `2026-07-28` revision, every request carrying its version and client\n * capabilities in `_meta` and `server/discover` answering what is\n * supported; and the `2025-11-25` revision (and its predecessors) with the\n * `initialize` handshake today's clients open with. The tools are pure\n * functions of the repository's files that return the JSON report, as\n * structured content beside its text; a verdict is a result whatever it\n * says, and only a command that could not run is a tool error. Eutaxy\n * never calls a model: every verdict depends only on files.\n */\n\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { type CheckOptions, exitCodes, provers, runCheck } from \"./check.ts\";\nimport { type ReportOptions, runReport } from \"./report.ts\";\nimport { eutaxyVersion } from \"./version.ts\";\n\n/** The protocol revisions served: the stateless one by `_meta`, the handshake ones by `initialize`. */\nexport const modernVersions: readonly string[] = [\"2026-07-28\"];\nexport const legacyVersions: readonly string[] = [\n \"2025-11-25\",\n \"2025-06-18\",\n \"2025-03-26\",\n \"2024-11-05\",\n];\n\nconst protocolVersionKey = \"io.modelcontextprotocol/protocolVersion\";\nconst clientCapabilitiesKey = \"io.modelcontextprotocol/clientCapabilities\";\nconst serverInfoKey = \"io.modelcontextprotocol/serverInfo\";\n\nexport const serverInfo = { name: \"eutaxy\", version: eutaxyVersion } as const;\n\nexport const instructions = [\n \"Eutaxy checks Cloudflare Workers by deterministic simulation and proves properties of their pure TypeScript core.\",\n \"`check` runs a scenario file (*.sim.ts) and returns the verdict: BOUNDED (no violation within the bounds), VIOLATED (with the shrunk schedule, and a regression test written beside the scenario that replays it), or UNSUPPORTED.\",\n \"`report` runs every spec file (*.props.ts) under a directory through the TESTED rung and, with engines named, the PROVEN rung.\",\n \"`goals` lists the properties the Lean engine could not prove and writes each module's open goals beside its spec file as <spec>.goals.lean, a proof file with every proof open: copy it to <spec>.lean, add lemmas and tactics, then call `prove` on the spec file. A proof whose source or spec changed since the goals were written is stale, never PROVEN.\",\n \"`prover_status` says which proof engines are installed; `eutaxy prover install lean` or `smt` installs one.\",\n \"Verdicts depend only on files in the repository; nothing here calls a model.\",\n].join(\"\\n\");\n\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json };\ntype Params = Record<string, unknown>;\n\ninterface Request {\n readonly id: string | number;\n readonly method: string;\n readonly params: Params;\n /** The `_meta` the request carries, when it is of the stateless era. */\n readonly modern: boolean;\n}\n\n/** What a tool answers: structured content, its text form, and whether the tool itself failed. */\nexport interface ToolResult {\n readonly structured: Json;\n readonly text: string;\n readonly isError?: boolean;\n}\n\n/** The commands the tools run, injectable for tests; the real ones otherwise. */\nexport interface Runners {\n readonly check: (o: CheckOptions) => Promise<number>;\n readonly report: (o: ReportOptions) => Promise<number>;\n readonly status: () => Promise<Json>;\n}\n\nexport interface McpContext {\n readonly cwd: string;\n /** Where logs go: stderr. */\n readonly log: (text: string) => void;\n readonly runners?: Partial<Runners>;\n}\n\nconst realRunners: Runners = {\n check: runCheck,\n report: runReport,\n status: async () => {\n const engines: Json[] = [];\n for (const [name, engine] of Object.entries(provers)) {\n const a = await engine.available();\n engines.push({\n name,\n ...(\"unavailable\" in a\n ? { installed: false, reason: a.unavailable }\n : { installed: true, version: a.version }),\n });\n }\n return { engines };\n },\n};\n\nclass ToolError extends Error {}\n\n/** A command's exit code and what it printed. */\nasync function capture(\n run: (stdout: (t: string) => void, stderr: (t: string) => void) => Promise<number>,\n): Promise<{ code: number; stdout: string; stderr: string }> {\n let stdout = \"\";\n let stderr = \"\";\n const code = await run(\n (t) => {\n stdout += t;\n },\n (t) => {\n stderr += t;\n },\n );\n return { code, stdout, stderr };\n}\n\n/** The report a command printed as JSON, or a tool error with what it said instead. */\nfunction reported(what: string, r: { code: number; stdout: string; stderr: string }): Json {\n if (r.code === exitCodes.error)\n throw new ToolError(`${what} could not run (exit 3): ${r.stderr.trim() || r.stdout.trim()}`);\n try {\n return JSON.parse(r.stdout) as Json;\n } catch {\n throw new ToolError(`${what} printed no JSON report: ${(r.stdout + r.stderr).trim()}`);\n }\n}\n\nconst str = (args: Params, key: string, required = false): string | undefined => {\n const v = args[key];\n if (v === undefined) {\n if (required) throw new ToolError(`${key} is required`);\n return undefined;\n }\n if (typeof v !== \"string\" || v.length === 0)\n throw new ToolError(`${key} must be a non-empty string`);\n return v;\n};\nconst bool = (args: Params, key: string): boolean | undefined => {\n const v = args[key];\n if (v === undefined) return undefined;\n if (typeof v !== \"boolean\") throw new ToolError(`${key} must be a boolean`);\n return v;\n};\nconst positiveInt = (args: Params, key: string): number | undefined => {\n const v = args[key];\n if (v === undefined) return undefined;\n if (typeof v !== \"number\" || !Number.isInteger(v) || v <= 0)\n throw new ToolError(`${key} must be a positive integer`);\n return v;\n};\nconst strings = (args: Params, key: string): string[] | undefined => {\n const v = args[key];\n if (v === undefined) return undefined;\n if (!Array.isArray(v) || !v.every((x) => typeof x === \"string\" && x.length > 0))\n throw new ToolError(`${key} must be an array of non-empty strings`);\n return v as string[];\n};\nconst only = (args: Params, allowed: readonly string[]): void => {\n const extra = Object.keys(args).find((k) => !allowed.includes(k));\n if (extra !== undefined)\n throw new ToolError(`unknown argument ${extra}; the arguments are ${allowed.join(\", \")}`);\n};\n\ninterface Tool {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n readonly inputSchema: Json;\n readonly run: (args: Params, ctx: McpContext, runners: Runners) => Promise<ToolResult>;\n}\n\nconst engineNames = Object.keys(provers);\nconst proversSchema: Json = {\n type: \"array\",\n items: { type: \"string\", enum: engineNames },\n description: `Proof engines for the PROVEN rung: ${engineNames.join(\", \")}`,\n};\n\nconst asResult = (structured: Json, isError = false): ToolResult => ({\n structured,\n text: JSON.stringify(structured, null, 2),\n ...(isError ? { isError: true } : {}),\n});\n\nexport const tools: readonly Tool[] = [\n {\n name: \"check\",\n title: \"Check a scenario\",\n description:\n \"Run a scenario file (*.sim.ts) in the simulator and return the JSON report: the verdict (BOUNDED, VIOLATED with the shrunk schedule, or UNSUPPORTED), the spec verdicts, and on a violation the path of the regression test written beside the scenario (regressionTest). Exit code 1 is a violation or a refuted spec, not an error.\",\n inputSchema: {\n type: \"object\",\n properties: {\n scenario: {\n type: \"string\",\n description: \"Path of the scenario file, relative to the working directory\",\n },\n wrangler: {\n type: \"string\",\n description: \"Wrangler config path; default: the one beside the scenario\",\n },\n seed: { type: \"string\", description: \"Exploration seed; default: the scenario file name\" },\n maxRuns: { type: \"integer\", minimum: 1, description: \"Cap on exploration runs\" },\n budgetMs: {\n type: \"integer\",\n minimum: 1,\n description: \"Time budget in milliseconds, replacing the scenario's\",\n },\n exhaustive: { type: \"boolean\", description: \"Run every schedule within the bounds once\" },\n provers: proversSchema,\n regression: {\n type: \"boolean\",\n description: \"Write the regression test on a violation; default true\",\n },\n out: { type: \"string\", description: \"Where to write the regression test\" },\n },\n required: [\"scenario\"],\n additionalProperties: false,\n },\n async run(args, ctx, runners) {\n only(args, [\n \"scenario\",\n \"wrangler\",\n \"seed\",\n \"maxRuns\",\n \"budgetMs\",\n \"exhaustive\",\n \"provers\",\n \"regression\",\n \"out\",\n ]);\n const scenario = str(args, \"scenario\", true) as string;\n const wrangler = str(args, \"wrangler\");\n const seed = str(args, \"seed\");\n const maxRuns = positiveInt(args, \"maxRuns\");\n const budgetMs = positiveInt(args, \"budgetMs\");\n const engines = strings(args, \"provers\");\n const out = str(args, \"out\");\n const r = await capture((stdout, stderr) =>\n runners.check({\n scenario,\n cwd: ctx.cwd,\n ...(wrangler === undefined ? {} : { wrangler }),\n ...(seed === undefined ? {} : { seed }),\n ...(maxRuns === undefined ? {} : { maxRuns }),\n ...(budgetMs === undefined ? {} : { budgetMs }),\n exhaustive: bool(args, \"exhaustive\") === true,\n ...(engines === undefined ? {} : { provers: engines }),\n json: true,\n ...(out === undefined ? {} : { out }),\n noRegression: bool(args, \"regression\") === false,\n expectViolation: false,\n keep: false,\n stdout,\n stderr,\n }),\n );\n return asResult({ exitCode: r.code, report: reported(\"check\", r) });\n },\n },\n {\n name: \"report\",\n title: \"Report on the spec files\",\n description:\n \"Run every spec file (*.props.ts) under a directory through the TESTED rung and, with engines named, the PROVEN rung; return the JSON report of spec verdicts. Exit code 1 is a refuted or conflicting spec, not an error.\",\n inputSchema: {\n type: \"object\",\n properties: {\n dir: { type: \"string\", description: \"Directory to search; default: the working directory\" },\n provers: proversSchema,\n seed: { type: \"string\", description: \"Seed for the TESTED rung; default report\" },\n },\n additionalProperties: false,\n },\n async run(args, ctx, runners) {\n only(args, [\"dir\", \"provers\", \"seed\"]);\n const dir = str(args, \"dir\");\n const engines = strings(args, \"provers\");\n const seed = str(args, \"seed\");\n const r = await capture((stdout, stderr) =>\n runners.report({\n cwd: ctx.cwd,\n ...(dir === undefined ? {} : { dir }),\n ...(engines === undefined ? {} : { provers: engines }),\n ...(seed === undefined ? {} : { seed }),\n json: true,\n stdout,\n stderr,\n }),\n );\n return asResult({ exitCode: r.code, report: reported(\"report\", r) });\n },\n },\n {\n name: \"goals\",\n title: \"List the open proof goals\",\n description:\n \"Run the Lean engine on every spec file under a directory and list the properties it could not prove, each with the statement it tried; write each module's open goals beside its spec file as <spec>.goals.lean, a proof file with every proof open (copy it to <spec>.lean, add lemmas and tactics, then call prove). Needs the lean engine installed.\",\n inputSchema: {\n type: \"object\",\n properties: {\n dir: { type: \"string\", description: \"Directory to search; default: the working directory\" },\n },\n additionalProperties: false,\n },\n async run(args, ctx, runners) {\n only(args, [\"dir\"]);\n const dir = str(args, \"dir\");\n const r = await capture((stdout, stderr) =>\n runners.report({\n cwd: ctx.cwd,\n ...(dir === undefined ? {} : { dir }),\n provers: [\"lean\"],\n goals: true,\n json: true,\n stdout,\n stderr,\n }),\n );\n return asResult({ exitCode: r.code, report: reported(\"goals\", r) });\n },\n },\n {\n name: \"prove\",\n title: \"Check the proofs supplied for a spec file\",\n description:\n \"Run the Lean engine on one module, the one whose spec file (*.props.ts) is given, with the proofs supplied beside it in <spec>.lean, and return its spec verdicts: PROVEN where a proof closes (Lean's kernel checked it against the statement Eutaxy emitted), UNKNOWN with the reason where it does not, or where the proof file is stale (written for another version of the module or the spec).\",\n inputSchema: {\n type: \"object\",\n properties: {\n spec: {\n type: \"string\",\n description: \"Path of the spec file, relative to the working directory\",\n },\n },\n required: [\"spec\"],\n additionalProperties: false,\n },\n async run(args, ctx, runners) {\n only(args, [\"spec\"]);\n const spec = str(args, \"spec\", true) as string;\n const r = await capture((stdout, stderr) =>\n runners.report({\n cwd: ctx.cwd,\n dir: dirname(spec),\n only: spec,\n provers: [\"lean\"],\n json: true,\n stdout,\n stderr,\n }),\n );\n return asResult({ exitCode: r.code, report: reported(\"prove\", r) });\n },\n },\n {\n name: \"prover_status\",\n title: \"Which proof engines are installed\",\n description:\n \"For each proof engine (lean, smt): whether its pinned toolchain is installed and its version, or why not and how to install it (eutaxy prover install <name>).\",\n inputSchema: { type: \"object\", additionalProperties: false },\n async run(args, _ctx, runners) {\n only(args, []);\n return asResult(await runners.status());\n },\n },\n];\n\ninterface Response {\n readonly jsonrpc: \"2.0\";\n readonly id: string | number | null;\n readonly result?: Json;\n readonly error?: { readonly code: number; readonly message: string; readonly data?: Json };\n}\n\nconst errorResponse = (\n id: string | number | null,\n code: number,\n message: string,\n data?: Json,\n): Response => ({\n jsonrpc: \"2.0\",\n id,\n error: { code, message, ...(data === undefined ? {} : { data }) },\n});\n\n/** A result in the requester's era: the stateless one carries `resultType` and the server's identity. */\nconst resultResponse = (req: Request, result: { [key: string]: Json }): Response => ({\n jsonrpc: \"2.0\",\n id: req.id,\n result: req.modern\n ? { resultType: \"complete\", ...result, _meta: { [serverInfoKey]: serverInfo } }\n : result,\n});\n\nconst toolListing = (): Json =>\n tools.map((t) => ({\n name: t.name,\n title: t.title,\n description: t.description,\n inputSchema: t.inputSchema,\n }));\n\nasync function callTool(req: Request, ctx: McpContext): Promise<Response> {\n const name = req.params[\"name\"];\n const tool = tools.find((t) => t.name === name);\n if (typeof name !== \"string\" || !tool)\n return errorResponse(req.id, -32602, `Unknown tool: ${String(name)}`);\n const args = req.params[\"arguments\"] ?? {};\n if (typeof args !== \"object\" || args === null || Array.isArray(args))\n return errorResponse(req.id, -32602, \"arguments must be an object\");\n const runners: Runners = { ...realRunners, ...ctx.runners };\n let result: ToolResult;\n try {\n result = await tool.run(args as Params, ctx, runners);\n } catch (err) {\n // The tool itself failed: an execution error the model can act on, not a protocol error.\n const message = err instanceof Error ? err.message : String(err);\n result = { structured: { error: message }, text: message, isError: true };\n }\n return resultResponse(req, {\n content: [{ type: \"text\", text: result.text }],\n structuredContent: result.structured,\n isError: result.isError === true,\n });\n}\n\n/**\n * One line in, at most one line out: the response to a request, nothing\n * for a notification. A request of the stateless era whose version is not\n * served gets the `UnsupportedProtocolVersion` error with what is.\n */\nexport async function handleLine(line: string, ctx: McpContext): Promise<string | undefined> {\n let message: unknown;\n try {\n message = JSON.parse(line);\n } catch {\n return JSON.stringify(errorResponse(null, -32700, \"Parse error\"));\n }\n if (Array.isArray(message))\n return JSON.stringify(\n errorResponse(null, -32600, \"Invalid Request: batches are not supported\"),\n );\n if (typeof message !== \"object\" || message === null)\n return JSON.stringify(errorResponse(null, -32600, \"Invalid Request\"));\n const m = message as Record<string, unknown>;\n const id = m[\"id\"];\n const idOk = typeof id === \"string\" || typeof id === \"number\";\n if (m[\"jsonrpc\"] !== \"2.0\" || typeof m[\"method\"] !== \"string\")\n return JSON.stringify(\n errorResponse(idOk ? (id as string | number) : null, -32600, \"Invalid Request\"),\n );\n if (id === undefined) return undefined; // a notification: initialized, cancelled, progress; nothing to answer\n if (!idOk)\n return JSON.stringify(\n errorResponse(null, -32600, \"Invalid Request: id must be a string or a number\"),\n );\n const params = (\n typeof m[\"params\"] === \"object\" && m[\"params\"] !== null ? m[\"params\"] : {}\n ) as Params;\n const meta = (\n typeof params[\"_meta\"] === \"object\" && params[\"_meta\"] !== null ? params[\"_meta\"] : {}\n ) as Params;\n const requested = meta[protocolVersionKey];\n const req: Request = {\n id: id as string | number,\n method: m[\"method\"],\n params,\n modern: typeof requested === \"string\",\n };\n if (req.modern) {\n if (!modernVersions.includes(requested as string))\n return JSON.stringify(\n errorResponse(req.id, -32022, \"Unsupported protocol version\", {\n supported: [...modernVersions],\n requested: requested as string,\n }),\n );\n if (typeof meta[clientCapabilitiesKey] !== \"object\" || meta[clientCapabilitiesKey] === null)\n return JSON.stringify(\n errorResponse(req.id, -32602, `Invalid params: _meta.${clientCapabilitiesKey} is required`),\n );\n }\n let response: Response;\n try {\n response = await dispatch(req, ctx);\n } catch (err) {\n response = errorResponse(\n req.id,\n -32603,\n `Internal error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return JSON.stringify(response);\n}\n\nasync function dispatch(req: Request, ctx: McpContext): Promise<Response> {\n switch (req.method) {\n case \"initialize\": {\n const asked = req.params[\"protocolVersion\"];\n const version =\n typeof asked === \"string\" && legacyVersions.includes(asked)\n ? asked\n : (legacyVersions[0] as string);\n return resultResponse(req, {\n protocolVersion: version,\n capabilities: { tools: {} },\n serverInfo,\n instructions,\n });\n }\n case \"ping\":\n return resultResponse(req, {});\n case \"server/discover\":\n return resultResponse(req, {\n supportedVersions: [...modernVersions],\n capabilities: { tools: {} },\n instructions,\n });\n case \"tools/list\":\n return resultResponse(req, { tools: toolListing() });\n case \"tools/call\":\n return callTool(req, ctx);\n default:\n return errorResponse(req.id, -32601, `Method not found: ${req.method}`);\n }\n}\n\n/** Serve on the process's standard streams until stdin closes. Requests are answered one at a time, in order. */\nexport async function serveStdio(ctx: McpContext): Promise<number> {\n const lines = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });\n for await (const line of lines) {\n if (line.trim().length === 0) continue;\n const out = await handleLine(line, ctx);\n if (out !== undefined) process.stdout.write(`${out}\\n`);\n }\n return exitCodes.BOUNDED;\n}\n","import { parseArgs } from \"./args.ts\";\nimport { exitCodes, runCheck } from \"./check.ts\";\nimport { runInstall, toolchains } from \"./install.ts\";\nimport { serveStdio } from \"./mcp.ts\";\nimport { runReport } from \"./report.ts\";\n\nconst usage = `eutaxy — deterministic simulation checks and spec verdicts for Cloudflare Workers\n\nUsage:\n eutaxy check <scenario.sim.ts> [options]\n eutaxy report [dir] [--prover <names>] [--seed <seed>] [--json]\n eutaxy prover install <lean|smt> [--from <url or directory>] [--json]\n eutaxy mcp\n\ncheck options:\n --wrangler <path> wrangler config (default: wrangler.jsonc/json/toml beside the scenario)\n --seed <seed> exploration seed (default: the scenario file name)\n --max-runs <n> cap on exploration runs in addition to the scenario's time budget\n --budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)\n --exhaustive run every schedule within the bounds once (with partial-order reduction)\n --prover <names> also run the PROVEN rung with these engines on the scenario's specs\n (comma-separated; known: lean, smt)\n --json print the versioned JSON report instead of text\n --out <path> where to write the regression test on a violation\n --no-regression do not write a regression test\n --expect-violation write a regression test that asserts the violation (for corpora)\n --keep keep the generated .eutaxy/ files\n\nreport runs every spec file (*.props.ts) under dir (default: the current directory)\nthrough the TESTED rung, on inputs drawn from the parameter types with the seed\n(default: report), and the PROVEN rung with --prover. No scenario runs, so nothing\nis CHECKED.\n\nprover install puts the pinned Lean or Z3 release for this platform in Eutaxy's cache\n(EUTAXY_CACHE_DIR, else the platform's user cache), where --prover finds it first:\ndownloaded from the upstream GitHub release, or from a mirror or offline directory\nholding the same file (--from), and checked against the engine's SHA-256 before it is\nunpacked. Nothing is downloaded at any other time.\n\nreport options: --goals writes each module's open Lean goals beside its spec file as\n<spec>.goals.lean (a proof file with every proof open) and lists them; needs --prover lean.\n\nmcp serves the Model Context Protocol over stdio (one JSON-RPC message per line, logs on\nstderr) for a coding agent: tools check, report, goals, prove and prover_status, each\nreturning the JSON report. Point the agent's MCP configuration at \"eutaxy mcp\".\n\nExit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.\nreport: 0, or 1 for a REFUTED or CONFLICT spec, 3 error. prover install: 0, or 3.\n`;\n\nexport interface Io {\n readonly cwd: string;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport async function main(argv: readonly string[], io: Io): Promise<number> {\n const { positionals, flags } = parseArgs(argv, [\n \"json\",\n \"no-regression\",\n \"expect-violation\",\n \"keep\",\n \"help\",\n \"exhaustive\",\n \"goals\",\n ]);\n const command = positionals[0];\n if (!command || command === \"help\" || flags[\"help\"] === true) {\n io.stdout(usage);\n return command ? exitCodes.BOUNDED : exitCodes.error;\n }\n // A value flag given without one would otherwise read as absent: `--prover` alone must not quietly\n // skip the PROVEN rung.\n for (const k of [\"wrangler\", \"seed\", \"max-runs\", \"budget-ms\", \"prover\", \"out\", \"from\"])\n if (flags[k] === true) {\n io.stderr(`--${k} needs a value\\n`);\n return exitCodes.error;\n }\n const str = (k: string): string | undefined =>\n typeof flags[k] === \"string\" ? (flags[k] as string) : undefined;\n const provers = (str(\"prover\") ?? \"\")\n .split(\",\")\n .map((n) => n.trim())\n .filter((n) => n.length > 0);\n if (command === \"mcp\") {\n if (positionals.length !== 1 || Object.keys(flags).length > 0) {\n io.stderr(`mcp takes no arguments\\n\\n${usage}`);\n return exitCodes.error;\n }\n return serveStdio({ cwd: io.cwd, log: io.stderr });\n }\n if (command === \"prover\") {\n const names = Object.keys(toolchains).join(\"|\");\n if (positionals[1] !== \"install\" || positionals.length !== 3) {\n io.stderr(`prover takes: install <${names}>\\n\\n${usage}`);\n return exitCodes.error;\n }\n const other = Object.keys(flags).find((k) => ![\"from\", \"json\"].includes(k));\n if (other !== undefined) {\n io.stderr(`prover install does not take --${other}\\n`);\n return exitCodes.error;\n }\n const toolchain = toolchains[positionals[2] as string];\n if (toolchain === undefined) {\n io.stderr(\n `unknown engine ${positionals[2]}; the engines are ${names.replaceAll(\"|\", \", \")}\\n`,\n );\n return exitCodes.error;\n }\n return runInstall({\n toolchain,\n from: str(\"from\"),\n json: flags[\"json\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\n }\n if (command === \"report\") {\n if (positionals.length > 2) {\n io.stderr(`report takes one directory\\n\\n${usage}`);\n return exitCodes.error;\n }\n const other = Object.keys(flags).find((k) => ![\"prover\", \"seed\", \"json\", \"goals\"].includes(k));\n if (other !== undefined) {\n io.stderr(`report does not take --${other}\\n`);\n return exitCodes.error;\n }\n const dir = positionals[1];\n return runReport({\n cwd: io.cwd,\n ...(dir === undefined ? {} : { dir }),\n ...(provers.length > 0 ? { provers } : {}),\n ...(str(\"seed\") ? { seed: str(\"seed\") as string } : {}),\n ...(flags[\"goals\"] === true ? { goals: true } : {}),\n json: flags[\"json\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\n }\n if (command !== \"check\") {\n io.stderr(`unknown command ${command}\\n\\n${usage}`);\n return exitCodes.error;\n }\n const scenario = positionals[1];\n if (!scenario) {\n io.stderr(`check needs a scenario file\\n\\n${usage}`);\n return exitCodes.error;\n }\n const maxRunsText = str(\"max-runs\");\n const maxRuns = maxRunsText === undefined ? undefined : Number(maxRunsText);\n if (maxRuns !== undefined && !(Number.isInteger(maxRuns) && maxRuns > 0)) {\n io.stderr(`--max-runs must be a positive integer, got ${JSON.stringify(maxRunsText)}\\n`);\n return exitCodes.error;\n }\n const budgetText = str(\"budget-ms\");\n const budgetMs = budgetText === undefined ? undefined : Number(budgetText);\n if (budgetMs !== undefined && !(Number.isInteger(budgetMs) && budgetMs > 0)) {\n io.stderr(`--budget-ms must be a positive integer, got ${JSON.stringify(budgetText)}\\n`);\n return exitCodes.error;\n }\n return runCheck({\n scenario,\n cwd: io.cwd,\n ...(provers.length > 0 ? { provers } : {}),\n ...(str(\"wrangler\") ? { wrangler: str(\"wrangler\") as string } : {}),\n ...(str(\"seed\") ? { seed: str(\"seed\") as string } : {}),\n ...(maxRuns === undefined ? {} : { maxRuns }),\n ...(budgetMs === undefined ? {} : { budgetMs }),\n exhaustive: flags[\"exhaustive\"] === true,\n json: flags[\"json\"] === true,\n ...(str(\"out\") ? { out: str(\"out\") as string } : {}),\n noRegression: flags[\"no-regression\"] === true,\n expectViolation: flags[\"expect-violation\"] === true,\n keep: flags[\"keep\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\n}\n","import {\n describeVerdict,\n type Platform,\n type ScenarioSpec,\n type ScenarioVerdict,\n} from \"@eutaxy/core\";\nimport { type ExploreOptions, explore } from \"@eutaxy/engine\";\n\n/** Explore a scenario on a platform and return its verdict. */\nexport function check(\n spec: ScenarioSpec,\n platform: Platform,\n options: ExploreOptions = { seed: spec.name },\n): Promise<ScenarioVerdict> {\n return explore(spec, platform, options);\n}\n\n/** For use from a test: passes only when the scenario is BOUNDED. */\nexport async function expectHolds(\n spec: ScenarioSpec,\n platform: Platform,\n options?: ExploreOptions,\n): Promise<void> {\n const verdict = await check(spec, platform, options);\n if (verdict.kind !== \"BOUNDED\") throw new Error(describeVerdict(verdict));\n}\n","/**\n * The D1 binding proxy. Every statement execution is an effect point: the\n * engine decides the fault, the real Miniflare-backed D1 performs the query,\n * and the log records call, result and fault in the documented shape.\n */\n\nimport {\n canonicalJson,\n type EffectPoint,\n type FaultKind,\n type JsonValue,\n type RunHooks,\n readFaults,\n toJson,\n writeFaults,\n} from \"@eutaxy/core\";\n\n/** Whether a binding is a D1 database (what the proxies and the differential wrap). */\nexport function isD1(value: unknown): value is D1Database {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { prepare?: unknown }).prepare === \"function\" &&\n typeof (value as { batch?: unknown }).batch === \"function\"\n );\n}\n\nexport interface ProxyContext {\n readonly hooks: RunHooks;\n /** The invocation currently running; only one runs at a time, even with several in flight. */\n readonly currentInvocation: () => string;\n}\n\nfunction point(\n ctx: ProxyContext,\n target: string,\n op: string,\n args: JsonValue,\n allowed: readonly FaultKind[],\n): EffectPoint {\n return { invocation: ctx.currentInvocation(), target, op, args, allowed };\n}\n\nfunction metaOf(result: D1Result<unknown>): JsonValue {\n return { changes: result.meta.changes ?? 0, lastRowId: result.meta.last_row_id ?? null };\n}\n\nclass StatementProxy {\n private readonly real: D1PreparedStatement;\n private readonly target: string;\n private readonly ctx: ProxyContext;\n readonly sql: string;\n readonly params: readonly unknown[];\n\n constructor(\n real: D1PreparedStatement,\n target: string,\n ctx: ProxyContext,\n sql: string,\n params: readonly unknown[],\n ) {\n this.real = real;\n this.target = target;\n this.ctx = ctx;\n this.sql = sql;\n this.params = params;\n }\n\n /** The real statement, for `batch()`. */\n get statement(): D1PreparedStatement {\n return this.real;\n }\n\n private args(): JsonValue {\n return { sql: this.sql, params: toJson(this.params) };\n }\n\n bind(...values: unknown[]): StatementProxy {\n return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);\n }\n\n run<T = Record<string, unknown>>(): Promise<D1Result<T>> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"run\", this.args(), writeFaults),\n () => this.real.run<T>(),\n (r) => metaOf(r),\n );\n }\n\n all<T = Record<string, unknown>>(): Promise<D1Result<T>> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"all\", this.args(), readFaults),\n () => this.real.all<T>(),\n (r) => ({ rows: r.results.length, changes: r.meta.changes ?? 0 }),\n );\n }\n\n first<T = unknown>(colName?: string): Promise<T | null> {\n return this.ctx.hooks.effect(\n point(\n this.ctx,\n this.target,\n \"first\",\n { ...(this.args() as object), column: colName ?? null } as JsonValue,\n readFaults,\n ),\n () => (colName === undefined ? this.real.first<T>() : this.real.first<T>(colName)),\n (r) => ({ row: toJson(r) }),\n );\n }\n\n raw<T = unknown[]>(options?: { columnNames?: boolean }): Promise<T[]> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"raw\", this.args(), readFaults),\n () =>\n (options\n ? this.real.raw<T>(options as { columnNames: true })\n : this.real.raw<T>()) as Promise<T[]>,\n (r) => ({ rows: r.length }),\n );\n }\n}\n\n/** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */\nexport function proxyD1(real: D1Database, binding: string, ctx: ProxyContext): D1Database {\n const target = `D1:${binding}`;\n const modelled = {\n prepare(sql: string): StatementProxy {\n return new StatementProxy(real.prepare(sql), target, ctx, sql, []);\n },\n batch<T = Record<string, unknown>>(\n statements: readonly (StatementProxy | D1PreparedStatement)[],\n ): Promise<D1Result<T>[]> {\n const unwrapped = statements.map((s) => (s instanceof StatementProxy ? s.statement : s));\n const args = {\n statements: statements.map((s) =>\n s instanceof StatementProxy\n ? { sql: s.sql, params: toJson(s.params) }\n : \"<unproxied statement>\",\n ),\n };\n return ctx.hooks.effect(\n point(ctx, target, \"batch\", args, writeFaults),\n () => real.batch<T>(unwrapped as D1PreparedStatement[]),\n (rs) => ({\n changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),\n statements: rs.length,\n }),\n );\n },\n exec(sql: string): Promise<D1ExecResult> {\n return ctx.hooks.effect(\n point(ctx, target, \"exec\", { sql }, writeFaults),\n () => real.exec(sql),\n (r) => ({ count: r.count, duration: 0 }),\n );\n },\n };\n return new Proxy(real, {\n get(obj, prop, receiver) {\n if (prop in modelled) return modelled[prop as keyof typeof modelled];\n const value = Reflect.get(obj, prop, receiver) as unknown;\n if (typeof value === \"function\") {\n ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);\n return (value as (...a: unknown[]) => unknown).bind(obj);\n }\n return value;\n },\n }) as D1Database;\n}\n\n/**\n * Statements in a schema file. Splits on semicolons outside string literals,\n * quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE\n * expressions) whole by tracking BEGIN/CASE ... END nesting.\n */\nexport function splitSql(sql: string): readonly string[] {\n const out: string[] = [];\n let cur = \"\";\n let depth = 0;\n let i = 0;\n const isWordChar = (c: string | undefined): boolean => c !== undefined && /[A-Za-z0-9_]/.test(c);\n while (i < sql.length) {\n const c = sql[i] as string;\n const next = sql[i + 1];\n if (c === \"-\" && next === \"-\") {\n while (i < sql.length && sql[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"/\" && next === \"*\") {\n const end = sql.indexOf(\"*/\", i + 2);\n i = end === -1 ? sql.length : end + 2;\n continue;\n }\n if (c === \"'\" || c === '\"' || c === \"`\" || c === \"[\") {\n const close = c === \"[\" ? \"]\" : c;\n let j = i + 1;\n for (;;) {\n const k = sql.indexOf(close, j);\n if (k === -1) {\n j = sql.length;\n break;\n }\n if (close !== \"]\" && sql[k + 1] === close) {\n j = k + 2; // a doubled quote inside the literal\n continue;\n }\n j = k + 1;\n break;\n }\n cur += sql.slice(i, j);\n i = j;\n continue;\n }\n if (isWordChar(c) && !isWordChar(sql[i - 1])) {\n let j = i;\n while (isWordChar(sql[j])) j++;\n const word = sql.slice(i, j);\n const upper = word.toUpperCase();\n if (upper === \"BEGIN\" || upper === \"CASE\") depth++;\n else if (upper === \"END\" && depth > 0) depth--;\n cur += word;\n i = j;\n continue;\n }\n if (c === \";\" && depth === 0) {\n const statement = cur.trim();\n if (statement.length > 0) out.push(statement);\n cur = \"\";\n i++;\n continue;\n }\n cur += c;\n i++;\n }\n const last = cur.trim();\n if (last.length > 0) out.push(last);\n return out;\n}\n\n/** Drop every user table and re-apply the schema, using the real binding (not an effect). */\nexport async function resetD1(real: D1Database, schema: string): Promise<void> {\n const tables = await real\n .prepare(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\'\",\n )\n .all<{ name: string }>();\n for (const { name } of tables.results) {\n await real.prepare(`DROP TABLE IF EXISTS \"${name.replace(/\"/g, '\"\"')}\"`).run();\n }\n for (const statement of splitSql(schema)) {\n await real.prepare(statement).run();\n }\n}\n\n/** Every user table's rows, sorted canonically, read through the real binding (not an effect). */\nexport async function snapshotD1(\n real: D1Database,\n): Promise<{ readonly [table: string]: readonly JsonValue[] }> {\n const tables = await real\n .prepare(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\' ORDER BY name\",\n )\n .all<{ name: string }>();\n const out: Record<string, JsonValue[]> = {};\n for (const { name } of tables.results) {\n const rows = await real\n .prepare(`SELECT * FROM \"${name.replace(/\"/g, '\"\"')}\"`)\n .all<Record<string, unknown>>();\n out[name] = rows.results\n .map((r) => toJson(r))\n .map((j) => [canonicalJson(j), j] as const)\n .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))\n .map(([, j]) => j);\n }\n return out;\n}\n","/** What a delivery hands the Worker besides the event: its `ExecutionContext`, and the background work it collects. */\n\nimport type { FaultKind, RunHooks } from \"@eutaxy/core\";\nimport { CrashSignal } from \"@eutaxy/engine\";\nimport type { WorkerHandler } from \"./platform.ts\";\n\nconst CUT_OFF: readonly FaultKind[] = [\"cut_off\"];\n\n/** The Worker a delivery runs: its default export and the proxied bindings it sees. */\nexport interface RunningWorker {\n readonly handler: WorkerHandler;\n readonly env: object;\n}\n\n/**\n * The `ExecutionContext` handed to a handler; `waitUntil` work is collected to\n * run after it returns. A rejection is kept in `failures` when given: a\n * scheduled invocation's status is that of its first failed `waitUntil`\n * (Cloudflare, Scheduled handler); a queue or HTTP delivery's is not.\n */\nexport function executionContext(\n background: Promise<unknown>[],\n failures?: unknown[],\n): ExecutionContext {\n return {\n waitUntil: (promise: Promise<unknown>) => {\n background.push(\n promise.then(\n () => undefined,\n (error: unknown) => {\n failures?.push(error);\n },\n ),\n );\n },\n passThroughOnException: () => {},\n props: {},\n } as unknown as ExecutionContext;\n}\n\n/**\n * Background work extends the invocation but never changes the acknowledgement or the response.\n * A cut-off here is the isolate dying after them: work not yet started is lost.\n */\nexport async function drainBackground(\n hooks: RunHooks,\n inv: { isCrashed(): boolean; readonly crashed: Promise<void> },\n invocation: string,\n target: string,\n background: readonly Promise<unknown>[],\n): Promise<boolean> {\n if (background.length === 0 || inv.isCrashed()) return false;\n try {\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"background\",\n args: { pending: background.length },\n allowed: CUT_OFF,\n },\n () => null,\n () => null,\n );\n await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);\n return false;\n } catch (err) {\n if (!(err instanceof CrashSignal)) throw err;\n return true;\n }\n}\n","/**\n * Durable Object alarms in virtual time. Eutaxy takes over each object's\n * alarm methods (on its storage and inside transactions), so the runtime\n * never schedules an alarm on the real clock, whose time is far ahead of\n * the virtual one. A set alarm is kept per object, so it survives eviction\n * as a real one does, and becomes an event due at its virtual time; when\n * the run reaches it, the object's `alarm()` handler runs as one effect.\n *\n * Semantics, as Cloudflare documents them (developers.cloudflare.com/\n * durable-objects/api/base/#alarm): an object has one alarm, a later\n * `setAlarm` replaces it, execution is at least once, and a handler that\n * throws is retried with exponential backoff starting at two seconds, up to\n * six retries, with `{ retryCount, isRetry }`. `setAlarm` inside a\n * transaction takes effect only if the transaction commits.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n invocationOf,\n type JsonValue,\n type RunHooks,\n readFaults,\n redelivery,\n} from \"@eutaxy/core\";\nimport { runInvocation } from \"@eutaxy/engine\";\n\n/** `EventRef.source` of an alarm event. */\nexport const alarmSource = \"durable_object_alarm\";\n\n/** Cloudflare retries a failed alarm handler up to six times, after 2 s, 4 s, 8 s, ... */\nconst maxRetries = 6;\nconst firstRetryMs = 2_000;\n\n/** One object's alarm, kept across its instances for the run. */\ninterface AlarmEntry {\n time: number | null;\n /** Alarm changes for this object so far, for unique event ids. */\n seq: number;\n /**\n * The current alarm's generation: every setAlarm or deleteAlarm starts a\n * new one, and an event or retry of an older generation is superseded.\n */\n gen: number;\n /** Times the alarm fired this run (retries not counted). */\n firings: number;\n}\n\n/** What an alarm event carries. */\ninterface AlarmData {\n readonly binding: string;\n readonly gen: number;\n readonly id: string;\n readonly object: string;\n readonly time: number;\n readonly retryCount: number;\n}\n\n/** The alarms of one namespace's objects; the platform clears it before each run. */\nexport class AlarmBook {\n private readonly entries = new Map<string, AlarmEntry>();\n\n clear(): void {\n this.entries.clear();\n }\n\n entry(id: string): AlarmEntry {\n let e = this.entries.get(id);\n if (!e) {\n e = { time: null, seq: 0, gen: 0, firings: 0 };\n this.entries.set(id, e);\n }\n return e;\n }\n}\n\n/** The alarm of one object, as its taken-over methods see it. */\nexport interface AlarmControl {\n get(): number | null;\n set(time: number): void;\n delete(): void;\n /** Report something about the object's alarms that Eutaxy cannot model faithfully. */\n unsupported(reason: string): void;\n}\n\n/** One alarm control per object: setting schedules an event at the alarm's virtual time. */\nexport function alarmControl(\n book: AlarmBook,\n binding: string,\n id: string,\n object: string,\n hooks: () => RunHooks,\n): AlarmControl {\n const entry = book.entry(id);\n return {\n get: () => entry.time,\n set: (time) => {\n entry.time = time;\n entry.seq++;\n entry.gen = entry.seq;\n const data: AlarmData = { binding, gen: entry.gen, id, object, time, retryCount: 0 };\n const now = Date.now();\n hooks().enqueue({\n id: `alarm:${binding}:${object}:${entry.seq}`,\n attempt: 1,\n source: alarmSource,\n data: data as unknown as JsonValue,\n ...(time > now ? { at: time } : {}),\n });\n },\n delete: () => {\n entry.time = null;\n // Supersedes the pending event and any retry of it.\n entry.seq++;\n entry.gen = entry.seq;\n },\n unsupported: (reason) => hooks().unsupported(`Durable Object ${binding} ${object}: ${reason}`),\n };\n}\n\n/** Storage objects whose alarm methods Eutaxy has taken over (one per live instance). */\nexport const takenOver = new WeakSet<object>();\n\nconst timeOf = (time: number | Date) => (typeof time === \"number\" ? time : time.getTime());\n\n/** Storage objects whose alarm was read before Eutaxy took them over (in a constructor). */\nconst readBeforeTakeover = new WeakSet<object>();\n/** Storage prototypes whose getAlarm records such reads. */\nconst watched = new WeakSet<object>();\n\n/**\n * Record reads of the native alarm on storage not yet taken over: a rebuilt\n * object's constructor reads native storage, where Eutaxy's pending alarm is\n * not. The wrapper only records; it returns what the native method returns.\n */\nfunction watchReads(storage: DurableObjectStorage): void {\n const proto = Object.getPrototypeOf(storage) as { getAlarm?: (...a: unknown[]) => unknown };\n if (!proto || watched.has(proto) || typeof proto.getAlarm !== \"function\") return;\n watched.add(proto);\n const native = proto.getAlarm;\n proto.getAlarm = function (this: object, ...args: unknown[]) {\n if (!takenOver.has(this)) readBeforeTakeover.add(this);\n return native.apply(this, args);\n };\n}\n\n/**\n * Replace an object's alarm methods so no real alarm is ever scheduled. An\n * alarm the object set before the takeover (in its constructor) is moved\n * over: deleted from the runtime and set on the control, unless an alarm is\n * still pending, which the constructor could not see in native storage\n * (Eutaxy keeps it): then the pending one stays and the run is UNSUPPORTED.\n */\nexport async function takeOverAlarms(\n storage: DurableObjectStorage,\n alarm: AlarmControl,\n): Promise<void> {\n if (takenOver.has(storage)) return;\n // From the first takeover on, later instances' constructor reads are recorded.\n watchReads(storage);\n takenOver.add(storage);\n if (readBeforeTakeover.has(storage) && alarm.get() !== null) {\n alarm.unsupported(\n \"its constructor read the alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled\",\n );\n }\n const existing = await storage.getAlarm();\n if (existing !== null) {\n await storage.deleteAlarm();\n if (alarm.get() === null) alarm.set(existing);\n else\n alarm.unsupported(\n \"its constructor set an alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled\",\n );\n }\n const s = storage as unknown as Record<string, unknown>;\n // Inside transactionSync an alarm change would have to roll back with it: not modelled.\n let inSync = false;\n const outsideSync = (op: string) => {\n if (inSync) alarm.unsupported(`${op} inside transactionSync() is not modelled`);\n };\n Object.assign(s, {\n setAlarm: async (time: number | Date) => {\n outsideSync(\"setAlarm\");\n alarm.set(timeOf(time));\n },\n getAlarm: async () => alarm.get(),\n deleteAlarm: async () => {\n outsideSync(\"deleteAlarm\");\n alarm.delete();\n },\n });\n if (typeof s[\"transactionSync\"] === \"function\") {\n const transactionSync = (s[\"transactionSync\"] as (cb: () => unknown) => unknown).bind(storage);\n s[\"transactionSync\"] = (callback: () => unknown) => {\n inSync = true;\n try {\n return transactionSync(callback);\n } finally {\n inSync = false;\n }\n };\n }\n const transaction = (\n s[\"transaction\"] as (cb: (txn: unknown) => unknown) => Promise<unknown>\n ).bind(storage);\n // Inside a transaction an alarm change is held until the transaction commits.\n s[\"transaction\"] = async (callback: (txn: unknown) => unknown) => {\n // Per attempt: the runtime may run the callback again after a conflict, discarding the first.\n let pending: { time: number | null } | undefined;\n let rolledBack = false;\n const held = {\n setAlarm: async (time: number | Date) => {\n pending = { time: timeOf(time) };\n },\n getAlarm: async () => (pending ? pending.time : alarm.get()),\n deleteAlarm: async () => {\n pending = { time: null };\n },\n };\n const result = await transaction((txn) => {\n pending = undefined;\n rolledBack = false;\n return callback(\n new Proxy(txn as Record<string, unknown>, {\n get(target, prop) {\n if (typeof prop === \"string\" && prop in held) return held[prop as keyof typeof held];\n const value = target[prop as string];\n if (prop === \"rollback\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n rolledBack = true;\n return (value as (...a: unknown[]) => unknown).apply(target, args);\n };\n }\n // Native methods check their receiver: call them on the real transaction.\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n }),\n );\n });\n if (pending && !rolledBack) {\n if (pending.time === null) alarm.delete();\n else alarm.set(pending.time);\n }\n return result;\n };\n}\n\nexport interface AlarmDelivery {\n readonly binding: string;\n readonly book: AlarmBook;\n /** Alarm firings allowed per object per run; later ones are recorded and not fired. */\n readonly limit: number;\n /** Run the handler inside the object, after taking over its alarms. */\n readonly runAlarm: (\n id: string,\n object: string,\n info: { readonly retryCount: number; readonly isRetry: boolean },\n gen: number,\n ) => Promise<void>;\n /** Record a platform action (an alarm not fired, a handler given up on). */\n readonly bookkeep: (op: string, args: JsonValue) => void;\n /** Reset the object, when the alarm's invocation crashes inside its handler. */\n readonly abort: (id: string) => void;\n /** Whether an effect the handler makes may wait for a turn (not inside blockConcurrencyWhile). */\n readonly mayPark: (id: string) => boolean;\n /** Drop the object's instance, when its alarm invocation crashed around the handler. */\n readonly evict: (id: string) => Promise<void>;\n}\n\n/**\n * Fire an alarm event: skip it when the object's alarm has since moved or\n * been deleted, run `alarm()` as one effect otherwise, and schedule a retry\n * with backoff when the handler fails, crashes, or a fault says it did.\n */\nexport async function deliverAlarm(\n event: EventRef,\n hooks: RunHooks,\n maxRedeliveries: number,\n d: AlarmDelivery,\n): Promise<DeliveryResult> {\n const a = event.data as unknown as AlarmData;\n const entry = d.book.entry(a.id);\n // Superseded by a later setAlarm or deleteAlarm: dropped before anything, faults included.\n if (entry.gen !== a.gen) return { status: \"completed\", followUps: [] };\n if (a.retryCount === 0) {\n if (entry.time !== a.time) return { status: \"completed\", followUps: [] };\n // It stays set until the handler starts (runAlarm clears it after the takeover), as natively.\n if (entry.firings >= d.limit) {\n entry.time = null;\n d.bookkeep(\"alarm_not_fired\", { object: a.object, firings: entry.firings });\n return { status: \"completed\", followUps: [] };\n }\n entry.firings++;\n }\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const info = { retryCount: a.retryCount, isRetry: a.retryCount > 0 };\n const { status } = await runInvocation(hooks, inv, () =>\n hooks.effect(\n {\n invocation,\n target: `DO:${d.binding}`,\n op: \"alarm\",\n args: { object: a.object, retryCount: a.retryCount },\n // Crash before: the handler never ran. Crash after: it ran and committed, but counts as failed.\n allowed: readFaults,\n hostsEffects: true,\n },\n async () => {\n await d.runAlarm(a.id, a.object, info, a.gen);\n return null;\n },\n () => null,\n { onAbandon: () => d.abort(a.id), mayPark: () => d.mayPark(a.id) },\n ),\n );\n // A crash is the object's: its in-memory state goes with the instance, whatever the handler did.\n if (status === \"crashed\") await d.evict(a.id);\n if (status !== \"completed\") {\n // The retries so far are the attempt less one: retryCount counts them too.\n const next = redelivery(event, maxRetries, { maxRedeliveries });\n if (next) {\n const retryAt = Date.now() + firstRetryMs * 2 ** a.retryCount;\n const data: AlarmData = { ...a, retryCount: a.retryCount + 1 };\n // The alarm stays set, for its retry, until a later change supersedes it.\n if (entry.gen === a.gen) entry.time = retryAt;\n hooks.enqueue({ ...next, data: data as unknown as JsonValue, at: retryAt });\n } else {\n // Given up on: no longer pending, unless a newer alarm replaced it meanwhile.\n if (entry.gen === a.gen) entry.time = null;\n d.bookkeep(\"alarm_gave_up\", { object: a.object, retries: a.retryCount });\n }\n }\n return { status, followUps: [] };\n}\n","/**\n * The Durable Object namespace proxy. The objects are the real ones workerd\n * runs: storage, transactions and the input and output gates are the\n * runtime's own. Eutaxy proxies the boundary a Worker crosses to reach them:\n * every call on a stub is an effect point, so a call can fail before it\n * reaches the object (`crash_before`, `error`), or reach it, commit, and\n * lose its answer (`ambiguous`) or its caller (`crash_after`).\n *\n * Between runs every object is cleared, seeded from the scenario's setup\n * and evicted, so it starts from storage alone; after a run its storage is\n * snapshotted for state invariants. Both go through the Cloudflare Vitest\n * plugin's test helpers. Alarms are taken over on each object's storage and\n * fire in virtual time (see alarms.ts).\n */\n\nimport { type JsonValue, toJson, writeFaults } from \"@eutaxy/core\";\nimport { withoutNetwork } from \"@eutaxy/engine\";\nimport { AlarmBook, alarmControl, takenOver, takeOverAlarms } from \"./alarms.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\n\n/**\n * The Cloudflare Vitest plugin's test helpers, as exported by\n * `cloudflare:test` (pass the module namespace). Typed loosely on purpose:\n * the plugin's generic overloads are too deep to check against an interface.\n */\nexport interface DurableObjectTestHelpers {\n readonly runInDurableObject: unknown;\n readonly evictDurableObject: unknown;\n readonly listDurableObjectIds: unknown;\n}\n\n/** The helpers with the signatures this module calls them with. */\ninterface Helpers {\n runInDurableObject<R>(\n stub: DurableObjectStub,\n callback: (instance: unknown, state: DurableObjectState) => R | Promise<R>,\n ): Promise<R>;\n evictDurableObject(stub: DurableObjectStub): Promise<void>;\n listDurableObjectIds(namespace: DurableObjectNamespace): Promise<DurableObjectId[]>;\n}\n\nconst typed = (helpers: DurableObjectTestHelpers): Helpers => helpers as unknown as Helpers;\n\nexport function isDurableObjectNamespace(value: unknown): value is DurableObjectNamespace {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { idFromName?: unknown }).idFromName === \"function\" &&\n typeof (value as { get?: unknown }).get === \"function\"\n );\n}\n\n/** Object names by id, so snapshots and the log name objects as the Worker does. */\nexport type ObjectNames = Map<string, string>;\n\n/** How deep each object state is inside blockConcurrencyWhile, while it is. */\nconst gateDepth = new WeakMap<object, number>();\n/** Object-state prototypes whose blockConcurrencyWhile records that depth. */\nconst gateWatched = new WeakSet<object>();\n\n/**\n * Record when an object holds its input gate with blockConcurrencyWhile,\n * on the state prototype so constructors are covered too; the wrapper only\n * records and calls the native method.\n */\nfunction watchGate(state: DurableObjectState): void {\n const proto = Object.getPrototypeOf(state) as {\n blockConcurrencyWhile?: (cb: () => Promise<unknown>) => Promise<unknown>;\n };\n if (!proto || gateWatched.has(proto) || typeof proto.blockConcurrencyWhile !== \"function\") return;\n gateWatched.add(proto);\n const native = proto.blockConcurrencyWhile;\n proto.blockConcurrencyWhile = function (this: object, callback: () => Promise<unknown>) {\n return native.call(this, async () => {\n gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);\n try {\n return await callback();\n } finally {\n gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);\n }\n });\n };\n}\n\n/** Whether the object is inside blockConcurrencyWhile now. */\nfunction gateHeld(state: DurableObjectState | undefined): boolean {\n return state !== undefined && (gateDepth.get(state) ?? 0) > 0;\n}\n\n/** What Eutaxy keeps about one namespace during a run; the platform clears it before each run. */\nexport class BindingState {\n /** Names learned this run (seeded ones come back with the setup), so traces never depend on earlier runs. */\n readonly names: ObjectNames = new Map();\n /** Ids of the objects a call or an alarm reached this run. */\n readonly touched = new Set<string>();\n /** The objects' alarms in virtual time. */\n readonly alarms = new AlarmBook();\n /** Each reached object's live state, so an invocation that crashes inside it can reset it. */\n readonly states = new Map<string, DurableObjectState>();\n\n /** Whether the object's own effects may wait for a turn: not while it holds its input gate. */\n mayPark(id: string): boolean {\n return !gateHeld(this.states.get(id));\n }\n\n clear(): void {\n this.names.clear();\n this.touched.clear();\n this.alarms.clear();\n this.states.clear();\n }\n\n /**\n * Reset an object the way a crash does, with `ctx.abort()`, which\n * application code cannot catch: the runtime ends the requests inside it.\n * Called where an injected crash happens inside the object's own work,\n * which is the one place abort() works (from outside, workerd refuses).\n */\n abort(id: string): void {\n const state = this.states.get(id);\n this.states.delete(id);\n try {\n state?.abort(\"Eutaxy: the invocation crashed inside this object\");\n } catch {\n // abort() throws to unwind the object's code; the reset has happened.\n }\n }\n}\n\n/** The storage's own alarm deletion, even after Eutaxy replaced the method on it. */\nasync function deleteRealAlarm(storage: DurableObjectStorage): Promise<void> {\n const proto = Object.getPrototypeOf(storage) as { deleteAlarm?: () => Promise<void> };\n const own = Object.hasOwn(storage, \"deleteAlarm\");\n const deleteAlarm = own ? proto.deleteAlarm : storage.deleteAlarm;\n await deleteAlarm?.call(storage);\n}\n\n/** An RPC argument as effect-log data; a Request becomes its method and URL. */\nfunction argument(value: unknown): JsonValue {\n if (value instanceof Request) return { method: value.method, url: value.url };\n return toJson(value);\n}\n\n/**\n * Whether a result is data the caller holds by value. Anything else (an RPC\n * capability, an object with methods) would let later calls bypass the\n * proxy, so it makes the run UNSUPPORTED.\n */\nexport function isPlainData(value: unknown, depth = 0): boolean {\n if (value === null || value === undefined) return true;\n if (typeof value === \"function\") return false;\n if (typeof value !== \"object\") return true;\n // Too deep to inspect: not certified as data.\n if (depth > 8) return false;\n if (value instanceof Response || value instanceof Date) return true;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;\n const proto = Object.getPrototypeOf(value);\n if (Array.isArray(value)) return value.every((v) => isPlainData(v, depth + 1));\n if (proto !== Object.prototype && proto !== null) return false;\n return Object.values(value).every((v) => isPlainData(v, depth + 1));\n}\n\n/** An RPC result as effect-log data; a Response becomes its status. */\nfunction summarize(result: unknown): JsonValue {\n if (result instanceof Response) return { status: result.status, ok: result.ok };\n return toJson(result);\n}\n\nexport function proxyNamespace(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n state: BindingState,\n helpers: DurableObjectTestHelpers | undefined,\n /** Whether the running scenario resets this namespace (has a `durableObject` setup for it). */\n isReset: () => boolean,\n): DurableObjectNamespace {\n const target = `DO:${binding}`;\n const { names, touched, alarms: book } = state;\n const nameOf = (id: DurableObjectId) => names.get(id.toString()) ?? id.toString();\n\n function stubFor(stub: DurableObjectStub, id: string, object: string): DurableObjectStub {\n /** Make sure the call may reach the object, and take over its alarms first. */\n async function reach(real: DurableObjectStub): Promise<void> {\n if (!helpers) {\n ctx.hooks.unsupported(\n `Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`,\n );\n } else if (!isReset()) {\n ctx.hooks.unsupported(\n `Durable Object binding ${binding} has no durableObject setup, so its objects are not reset between runs; add durableObject(${JSON.stringify(binding)}) to the scenario's setup`,\n );\n } else {\n touched.add(id);\n await typed(helpers).runInDurableObject(real, (_instance, live) => {\n watchGate(live);\n state.states.set(id, live);\n return takeOverAlarms(\n live.storage,\n alarmControl(book, binding, id, object, () => ctx.hooks),\n );\n });\n }\n }\n\n /** A result passed back to the Worker; one that is not plain data cannot be followed. */\n function plain<T>(result: T): T {\n if (!isPlainData(result)) {\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object} returned something that is not plain data (an RPC capability or an object with methods); calls on it would bypass Eutaxy`,\n );\n }\n return result;\n }\n\n /**\n * The promise a call returns. On a real stub it is an RPC promise that\n * pipelines property reads (`stub.getData().value`); this one is not, so\n * a read on it makes the run UNSUPPORTED instead of yielding undefined.\n */\n function pipelineGuard<T>(promise: Promise<T>): Promise<T> {\n return new Proxy(promise, {\n get(target, prop) {\n if (\n typeof prop === \"symbol\" ||\n prop === \"then\" ||\n prop === \"catch\" ||\n prop === \"finally\"\n ) {\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop} on a call's promise) is not supported; await the call first`,\n );\n return undefined;\n },\n });\n }\n\n /** One effect on the object: a method call, or awaiting an RPC property. */\n function onObject(op: string, args: JsonValue, perform: () => Promise<unknown>) {\n return ctx.hooks.effect(\n // The object's own effects during the call (its fetch) belong to this call's turn.\n {\n invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed: writeFaults,\n hostsEffects: true,\n },\n perform,\n summarize,\n {\n // A crash inside the object's own work leaves its request pending: reset the object.\n onAbandon: () => state.abort(id),\n // Inside blockConcurrencyWhile nothing else enters the object: its effects run at once.\n mayPark: () => state.mayPark(id),\n },\n );\n }\n\n return new Proxy(stub, {\n get(real, prop, receiver) {\n // A stub is not a promise; `id` and `name` are not calls.\n if (prop === \"then\") return undefined;\n if (typeof prop !== \"string\" || prop === \"id\" || prop === \"name\")\n return Reflect.get(real, prop, receiver);\n // `stub.method(...)` calls it; `await stub.property` reads an RPC getter. Both are one effect.\n const call = (...args: unknown[]) =>\n pipelineGuard(\n onObject(prop, { object, args: args.map(argument) }, async () => {\n await reach(real);\n // Reflect.apply, not method.apply: an RPC stub's methods are proxies, `.apply` would be a call.\n const method = (real as unknown as Record<string, (...a: unknown[]) => unknown>)[\n prop\n ];\n if (typeof method !== \"function\")\n throw new TypeError(`${binding} stub has no ${prop}`);\n return plain(await Reflect.apply(method, real, args));\n }),\n );\n const read = () =>\n onObject(prop, { object, property: true }, async () => {\n await reach(real);\n return plain(await (real as unknown as Record<string, unknown>)[prop]);\n });\n const awaitable = (\n onFulfilled?: (v: unknown) => unknown,\n onRejected?: (e: unknown) => unknown,\n ) => read().then(onFulfilled, onRejected);\n // Callable and awaitable; any other property read is pipelining, which is not modelled.\n return new Proxy(call, {\n get(target, key) {\n if (key === \"then\") return awaitable;\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop}.${key}) is not supported; await .${prop} first`,\n );\n return undefined;\n },\n });\n },\n });\n }\n\n function idFromName(name: string): DurableObjectId {\n const id = real.idFromName(name);\n names.set(id.toString(), name);\n return id;\n }\n\n return new Proxy(real, {\n get(target, prop, receiver) {\n switch (prop) {\n case \"idFromName\":\n return idFromName;\n case \"idFromString\":\n return (hex: string) => target.idFromString(hex);\n case \"newUniqueId\":\n return (options?: DurableObjectNamespaceNewUniqueIdOptions) => {\n ctx.hooks.unsupported(\n `${binding}.newUniqueId() is random and differs on replay; use idFromName`,\n );\n return target.newUniqueId(options);\n };\n case \"get\":\n return (id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions) =>\n stubFor(target.get(id, options), id.toString(), nameOf(id));\n case \"getByName\":\n return (name: string) => {\n const id = idFromName(name);\n return stubFor(target.get(id), id.toString(), name);\n };\n case \"jurisdiction\":\n return (jurisdiction: DurableObjectJurisdiction) => {\n ctx.hooks.unsupported(\n `${binding}.jurisdiction() namespaces are not proxied or reset; use the namespace itself`,\n );\n return target.jurisdiction(jurisdiction);\n };\n default: {\n // Native methods check their receiver: call them on the real namespace.\n const value = Reflect.get(target, prop, receiver);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n }\n },\n });\n}\n\n/** Drop an object's instance from outside it; one that is not running has nothing to drop. */\nexport async function evictObject(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers | undefined,\n id: string,\n): Promise<void> {\n if (!helpers) return;\n await typed(helpers)\n .evictDurableObject(real.get(real.idFromString(id)))\n .catch(() => {});\n}\n\n/**\n * Run an object's `alarm()` handler inside it, after taking over its alarms\n * (the instance may be new since the alarm was set).\n */\nexport function alarmRunner(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n helpers: DurableObjectTestHelpers | undefined,\n state: BindingState,\n): (\n id: string,\n object: string,\n info: { readonly retryCount: number; readonly isRetry: boolean },\n gen: number,\n) => Promise<void> {\n return async (id, object, info, gen) => {\n if (!helpers) {\n ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);\n return;\n }\n state.touched.add(id);\n await typed(helpers).runInDurableObject(\n real.get(real.idFromString(id)),\n async (instance, live) => {\n watchGate(live);\n state.states.set(id, live);\n await takeOverAlarms(\n live.storage,\n alarmControl(state.alarms, binding, id, object, () => ctx.hooks),\n );\n // Superseded while the effect waited for its turn: the handler of a cancelled alarm never runs.\n const entry = state.alarms.entry(id);\n if (entry.gen !== gen) return;\n // The alarm is consumed as its handler starts: from here getAlarm() returns null.\n entry.time = null;\n const handler = (instance as { alarm?: (info: unknown) => unknown }).alarm;\n if (typeof handler !== \"function\") {\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object} set an alarm but has no alarm() handler`,\n );\n return;\n }\n await handler.call(instance, info);\n },\n );\n };\n}\n\n/** The objects to reset: every id the namespace has created, plus the setup's named ones. */\nasync function objectIds(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n seeded: readonly string[],\n): Promise<DurableObjectId[]> {\n const ids = new Map<string, DurableObjectId>();\n for (const id of await typed(helpers).listDurableObjectIds(real)) ids.set(id.toString(), id);\n for (const name of seeded) {\n const id = real.idFromName(name);\n names.set(id.toString(), name);\n ids.set(id.toString(), id);\n }\n return [...ids.values()].sort((a, b) => (a.toString() < b.toString() ? -1 : 1));\n}\n\n/**\n * Clear every object of the namespace, write the seeded entries, and evict\n * them all, so each run's first call constructs the object from storage.\n */\nexport async function resetNamespace(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } },\n): Promise<void> {\n // Clearing an object constructs it, outside the simulation: its constructor must not reach the network.\n const { requested } = await withoutNetwork(() => clearAndSeed(real, helpers, names, objects));\n if (requested) {\n throw new Error(\n \"a Durable Object constructor made a request during reset; constructors run outside the simulation there, so objects whose constructor does I/O are not supported\",\n );\n }\n}\n\nasync function clearAndSeed(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } },\n): Promise<void> {\n const ids = await objectIds(real, helpers, names, Object.keys(objects));\n for (const id of ids) {\n const stub = real.get(id);\n const name = names.get(id.toString());\n // Own entries only, and only for a known name: an object may be named \"\" or \"__proto__\".\n const entries = name !== undefined && Object.hasOwn(objects, name) ? objects[name] : undefined;\n await typed(helpers).runInDurableObject(stub, async (_instance, state) => {\n // Before any constructor of this run: so its blockConcurrencyWhile is seen too.\n watchGate(state);\n await state.storage.deleteAll();\n await deleteRealAlarm(state.storage);\n if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);\n });\n // The object just ran, so eviction can only fail for a real reason: let it fail the reset.\n await typed(helpers).evictDurableObject(stub);\n }\n}\n\n/**\n * Each object's storage as rows `{ key, value }`, sorted by key, one table\n * per object name. An object no call reached this run still holds exactly\n * its seed (reset left it evicted), so its rows come from the seed and it is\n * not constructed: its constructor would run outside the simulation. Such an\n * object that is running anyway was reached some other way (through another\n * object's own binding): `onIndirect` is told, and the seed is not its state.\n * The tables are the seeded objects and those a call reached, never objects\n * only earlier runs created, so a snapshot depends on this run alone.\n */\nexport async function snapshotNamespace(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n touched: ReadonlySet<string>,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } },\n onIndirect: (object: string) => void,\n onUnsupported: (reason: string) => void,\n): Promise<{ readonly [object: string]: readonly JsonValue[] }> {\n // Reading an object that is no longer running reconstructs it, outside the simulation.\n const { value, requested } = await withoutNetwork(() =>\n readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported),\n );\n if (requested)\n onUnsupported(\"a Durable Object made a request while its storage was being snapshotted\");\n return value;\n}\n\nasync function readTables(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n touched: ReadonlySet<string>,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } },\n onIndirect: (object: string) => void,\n onUnsupported: (reason: string) => void,\n): Promise<{ readonly [object: string]: readonly JsonValue[] }> {\n const out: Record<string, JsonValue[]> = {};\n for (const id of await objectIds(real, helpers, names, Object.keys(objects))) {\n const name = names.get(id.toString()) ?? id.toString();\n if (!touched.has(id.toString())) {\n // Eviction only succeeds on a running object, and reset left every object evicted.\n const running = await typed(helpers)\n .evictDurableObject(real.get(id))\n .then(\n () => true,\n () => false,\n );\n if (running) onIndirect(name);\n // Objects earlier runs created stay in the namespace's list: only the seed and this run count.\n if (!Object.hasOwn(objects, name)) continue;\n }\n const entries = touched.has(id.toString())\n ? [\n ...(await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {\n // Storage Eutaxy never took over belongs to an instance built after the run's calls.\n if (!takenOver.has(state.storage))\n onUnsupported(\n `Durable Object ${name} was reset during the run and reconstructed for the snapshot; its constructor ran outside the simulation`,\n );\n return state.storage.list();\n })),\n ]\n : Object.entries(Object.hasOwn(objects, name) ? (objects[name] ?? {}) : {});\n // Defined, not assigned: an object may be named \"__proto__\".\n Object.defineProperty(out, name, {\n value: entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, value]) => ({ key, value: toJson(value) })),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return out;\n}\n","/**\n * The R2 binding proxy. Every `put`, `delete`, `get`, `head` and `list` is\n * an effect point against the real Miniflare-backed bucket. A body is read\n * inside its `get`'s effect and handed back in an object with the same\n * fields and body methods: reading it later would be I/O the run cannot\n * see. An object's random `version` and wall-clock `uploaded` are replaced\n * by stand-ins (see `VersionBook`), so traces stay byte-identical.\n */\n\nimport {\n type EffectPoint,\n type FaultKind,\n type JsonValue,\n readFaults,\n toJson,\n writeFaults,\n} from \"@eutaxy/core\";\nimport type { ProxyContext } from \"./d1.ts\";\n\n/** Whether a binding is an R2 bucket (Miniflare's `R2Bucket`). */\nexport function isR2(value: unknown): value is R2Bucket {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return [\"head\", \"get\", \"put\", \"delete\", \"list\", \"createMultipartUpload\"].every(\n (m) => typeof v[m] === \"function\",\n );\n}\n\n/**\n * Stand-ins for the version and upload time of each object version the run\n * sees, in the order it first sees them: versions count up, and the time is\n * the virtual time it was first seen.\n */\nexport class VersionBook {\n private readonly seen = new Map<string, { version: string; uploaded: Date }>();\n\n clear(): void {\n this.seen.clear();\n }\n\n standIn(realVersion: string, at: number): { version: string; uploaded: Date } {\n let s = this.seen.get(realVersion);\n if (!s) {\n s = { version: (this.seen.size + 1).toString(16).padStart(32, \"0\"), uploaded: new Date(at) };\n this.seen.set(realVersion, s);\n }\n return { version: s.version, uploaded: new Date(s.uploaded.getTime()) };\n }\n}\n\n/** An object's metadata, with stand-ins for its version and upload time. */\nfunction metadata(real: R2Object, book: VersionBook, at: number): R2Object {\n const { version, uploaded } = book.standIn(real.version, at);\n return {\n key: real.key,\n version,\n size: real.size,\n etag: real.etag,\n httpEtag: real.httpEtag,\n uploaded,\n httpMetadata: real.httpMetadata,\n customMetadata: real.customMetadata,\n range: real.range,\n checksums: real.checksums,\n storageClass: real.storageClass,\n ssecKeyMd5: real.ssecKeyMd5,\n writeHttpMetadata: (headers: Headers) => real.writeHttpMetadata(headers),\n } as R2Object;\n}\n\n/**\n * The bytes behind each body stream the proxy hands out. The stream itself\n * has no known length, which the runtime's put requires, so a put given one\n * (copying an object) is given its bytes instead.\n */\nconst buffered = new WeakMap<ReadableStream, () => Uint8Array>();\n\n/**\n * An object with its body, already read: the stream and the body methods\n * share one consumption, as a real body's do. A method fails once the\n * stream is read, cancelled or locked by a reader; the stream ends empty\n * once a method has read the body.\n */\nfunction withBody(meta: R2Object, bytes: Uint8Array): R2ObjectBody {\n let used = false;\n let stream: ReadableStream | undefined;\n const take = (): Uint8Array => {\n if (used || stream?.locked) throw new TypeError(\"Body has already been used\");\n used = true;\n return bytes.slice();\n };\n // Defined, not assigned: Object.assign would call the getters and use the body up.\n return Object.defineProperties(meta, {\n body: {\n enumerable: true,\n get: () => {\n // Pulled only when read, so looking at the body does not use it.\n stream ??= new ReadableStream(\n {\n pull(controller) {\n if (!used) controller.enqueue(bytes.slice());\n used = true;\n controller.close();\n },\n cancel() {\n used = true;\n },\n },\n { highWaterMark: 0 },\n );\n buffered.set(stream, take);\n return stream;\n },\n },\n bodyUsed: { enumerable: true, get: () => used },\n arrayBuffer: { value: async () => take().buffer as ArrayBuffer },\n bytes: { value: async () => take() },\n text: { value: async () => new TextDecoder().decode(take()) },\n json: { value: async () => JSON.parse(new TextDecoder().decode(take())) as unknown },\n blob: { value: async () => new Blob([take()]) },\n }) as unknown as R2ObjectBody;\n}\n\n/** Conditions as the trace keeps them: a `Headers` object by its entries. */\nfunction conditions(onlyIf: unknown): { onlyIf?: unknown } {\n if (onlyIf === undefined) return {};\n return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };\n}\n\n/** What the trace keeps of a get's options: the conditions and range, never an encryption key. */\nfunction getArgs(key: string, options: R2GetOptions | undefined): JsonValue {\n return toJson({\n key,\n ...conditions(options?.onlyIf),\n ...(options?.range === undefined ? {} : { range: options.range }),\n });\n}\n\n/** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */\nfunction putArgs(options: R2PutOptions | undefined): JsonValue {\n if (!options) return {};\n return toJson({\n ...conditions(options.onlyIf),\n ...(options.customMetadata === undefined ? {} : { customMetadata: options.customMetadata }),\n ...(options.httpMetadata === undefined ? {} : { httpMetadata: options.httpMetadata }),\n });\n}\n\nexport function proxyR2(\n real: R2Bucket,\n binding: string,\n ctx: ProxyContext,\n book: VersionBook,\n): R2Bucket {\n const target = `R2:${binding}`;\n const point = (op: string, args: JsonValue, allowed: readonly FaultKind[]): EffectPoint => ({\n invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed,\n });\n const notModelled = (what: string): never => {\n const reason = `R2 ${binding}: ${what} is not modelled`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */\n const checkConditions = (onlyIf: unknown): void => {\n const datedHeaders = [\"if-modified-since\", \"if-unmodified-since\"];\n const dated =\n onlyIf instanceof Headers\n ? datedHeaders.some((h) => onlyIf.has(h))\n : typeof onlyIf === \"object\" &&\n onlyIf !== null &&\n (\"uploadedBefore\" in onlyIf || \"uploadedAfter\" in onlyIf);\n if (dated)\n ctx.hooks.unsupported(`R2 ${binding}: conditions on the upload time are not modelled`);\n };\n const described = (o: R2Object | null) =>\n o === null ? { found: false } : { found: true, key: o.key, size: o.size, etag: o.etag };\n return {\n put: (key: string, value: unknown, options?: R2PutOptions) =>\n ctx.hooks.effect(\n point(\"put\", { key, ...(putArgs(options) as object) }, writeFaults),\n async () => {\n checkConditions(options?.onlyIf);\n const read = value instanceof ReadableStream ? buffered.get(value) : undefined;\n const stored = await real.put(key, (read ? read() : value) as never, options);\n return stored === null ? null : metadata(stored, book, Date.now());\n },\n (o) => (o === null ? { stored: false } : { stored: true, size: o.size, etag: o.etag }),\n ),\n delete: (keys: string | string[]) =>\n ctx.hooks.effect(\n point(\"delete\", { keys: typeof keys === \"string\" ? [keys] : [...keys] }, writeFaults),\n () => real.delete(keys),\n () => null,\n ),\n get: (key: string, options?: R2GetOptions) =>\n ctx.hooks.effect(\n point(\"get\", getArgs(key, options), readFaults),\n async () => {\n checkConditions(options?.onlyIf);\n const o = await real.get(key, options);\n if (o === null) return null;\n const meta = metadata(o, book, Date.now());\n // A failed precondition answers the metadata without a body.\n if (!(\"body\" in o)) return meta;\n return withBody(meta, new Uint8Array(await (o as R2ObjectBody).arrayBuffer()));\n },\n (o) => ({ ...described(o), ...(o !== null ? { body: \"body\" in o } : {}) }),\n ),\n head: (key: string) =>\n ctx.hooks.effect(\n point(\"head\", { key }, readFaults),\n async () => {\n const o = await real.head(key);\n return o === null ? null : metadata(o, book, Date.now());\n },\n described,\n ),\n list: (options?: R2ListOptions) =>\n ctx.hooks.effect(\n point(\"list\", toJson(options ?? {}), readFaults),\n async () => {\n const listed = await real.list(options);\n const at = Date.now();\n return { ...listed, objects: listed.objects.map((o) => metadata(o, book, at)) };\n },\n (l) => ({\n keys: l.objects.map((o) => o.key),\n truncated: l.truncated,\n delimitedPrefixes: l.delimitedPrefixes,\n }),\n ),\n createMultipartUpload: () => notModelled(\"createMultipartUpload()\"),\n resumeMultipartUpload: () => notModelled(\"resumeMultipartUpload()\"),\n } as unknown as R2Bucket;\n}\n\n/** An object a setup seeds: its text, or its text with metadata. */\nexport type R2Seed =\n | string\n | {\n readonly value: string;\n readonly customMetadata?: Readonly<Record<string, string>>;\n readonly httpMetadata?: Readonly<Record<string, string>>;\n };\n\n/** Every object of the bucket, through all pages of a listing. */\nasync function allObjects(real: R2Bucket): Promise<R2Object[]> {\n const out: R2Object[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page: R2Objects = await real.list({\n include: [\"customMetadata\", \"httpMetadata\"],\n ...(cursor === undefined ? {} : { cursor }),\n });\n out.push(...page.objects);\n if (!page.truncated) return out;\n cursor = page.cursor;\n }\n}\n\n/** Empty the bucket and put its seeds, before a run. */\nexport async function resetR2(\n real: R2Bucket,\n seeds: Readonly<Record<string, R2Seed>>,\n): Promise<void> {\n const keys = (await allObjects(real)).map((o) => o.key);\n for (let i = 0; i < keys.length; i += 1000) await real.delete(keys.slice(i, i + 1000));\n for (const [key, seed] of Object.entries(seeds)) {\n if (typeof seed === \"string\") await real.put(key, seed);\n else\n await real.put(key, seed.value, {\n ...(seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {}),\n ...(seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}),\n });\n }\n}\n\n/** Largest object whose text the snapshot keeps. */\nconst snapshotTextLimit = 4096;\n\n/**\n * The bucket's objects as rows `{ key, size, etag, customMetadata,\n * httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is\n * valid UTF-8. Versions and upload times are left out: they are the store's,\n * not the Worker's.\n */\nexport async function snapshotR2(real: R2Bucket): Promise<JsonValue[]> {\n const rows: JsonValue[] = [];\n const objects = (await allObjects(real)).sort((a, b) =>\n a.key < b.key ? -1 : a.key > b.key ? 1 : 0,\n );\n for (const o of objects) {\n let text: string | undefined;\n if (o.size <= snapshotTextLimit) {\n const body = await real.get(o.key);\n if (body && \"body\" in body) {\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false }).decode(\n await body.arrayBuffer(),\n );\n } catch {\n // not text: the size and etag stand for it\n }\n }\n }\n rows.push(\n toJson({\n key: o.key,\n size: o.size,\n etag: o.etag,\n customMetadata: o.customMetadata ?? {},\n httpMetadata: o.httpMetadata ?? {},\n ...(text === undefined ? {} : { text }),\n }),\n );\n }\n return rows;\n}\n","/**\n * Cloudflare's cron expressions (Workers, Cron Triggers): five fields,\n * minute, hour, day of month, month and weekday, in UTC, with `*`, lists,\n * ranges, steps and names; weekdays run 1 = Sunday to 7 = Saturday. The\n * tick times a scenario drives are the expression's matches from the\n * virtual epoch on, so `scheduledTime` is what the trigger would have set.\n * `L`, `W` and `#` are not modelled: a scenario using them is refused.\n */\n\nconst monthNames = [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\",\n];\nconst dayNames = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"];\n\ninterface Field {\n readonly name: string;\n readonly min: number;\n readonly max: number;\n readonly names?: readonly string[];\n /** The number the first name stands for (months start at 1, Cloudflare's weekdays at 1 = Sunday). */\n readonly firstName?: number;\n}\n\nconst fields: readonly Field[] = [\n { name: \"minute\", min: 0, max: 59 },\n { name: \"hour\", min: 0, max: 23 },\n { name: \"day of month\", min: 1, max: 31 },\n { name: \"month\", min: 1, max: 12, names: monthNames, firstName: 1 },\n { name: \"weekday\", min: 1, max: 7, names: dayNames, firstName: 1 },\n];\n\n/** A parsed expression: the values each field admits. */\nexport interface CronSchedule {\n readonly minutes: ReadonlySet<number>;\n readonly hours: ReadonlySet<number>;\n readonly daysOfMonth: ReadonlySet<number>;\n readonly months: ReadonlySet<number>;\n /** 1 = Sunday to 7 = Saturday, as Cloudflare numbers them. */\n readonly weekdays: ReadonlySet<number>;\n /** Whether the day fields were both given: then a day matches either, as cron has it. */\n readonly anyDayOfMonth: boolean;\n readonly anyWeekday: boolean;\n}\n\nfunction value(token: string, field: Field): number {\n const lower = token.toLowerCase();\n if (field.names) {\n const i = field.names.indexOf(lower);\n if (i >= 0) return (field.firstName ?? 0) + i;\n }\n if (!/^\\d+$/.test(token))\n throw new Error(`${field.name}: ${JSON.stringify(token)} is not a value`);\n const n = Number(token);\n if (n < field.min || n > field.max)\n throw new Error(`${field.name}: ${n} is outside ${field.min}-${field.max}`);\n return n;\n}\n\nfunction parseField(text: string, field: Field): Set<number> {\n if (/[LW#]/i.test(text) && !field.names?.some((n) => text.toLowerCase().includes(n)))\n throw new Error(`${field.name}: L, W and # are not modelled`);\n const out = new Set<number>();\n for (const part of text.split(\",\")) {\n const pieces = part.split(\"/\");\n if (pieces.length > 2 || part === \"\")\n throw new Error(`${field.name}: ${JSON.stringify(part)} is not a value, range or step`);\n const [rangeText, stepText] = pieces as [string, string?];\n let step = 1;\n if (stepText !== undefined) {\n if (!/^\\d+$/.test(stepText) || Number(stepText) < 1)\n throw new Error(`${field.name}: step ${JSON.stringify(stepText)} is not a positive number`);\n step = Number(stepText);\n }\n let from: number;\n let to: number;\n if (rangeText === \"*\") {\n from = field.min;\n to = field.max;\n } else if (rangeText.includes(\"-\")) {\n const ends = rangeText.split(\"-\");\n if (ends.length !== 2)\n throw new Error(`${field.name}: ${JSON.stringify(rangeText)} is not a range`);\n const [a, b] = ends as [string, string];\n from = value(a, field);\n to = value(b, field);\n if (from > to) throw new Error(`${field.name}: range ${rangeText} runs backwards`);\n } else {\n from = value(rangeText, field);\n to = stepText === undefined ? from : field.max;\n }\n for (let v = from; v <= to; v += step) out.add(v);\n }\n return out;\n}\n\n/** Parse an expression; throws with the field and the problem when it is not one Cloudflare accepts. */\nexport function parseCron(expression: string): CronSchedule {\n const parts = expression.trim().split(/\\s+/);\n if (parts.length !== 5)\n throw new Error(\n `a cron expression has five fields, got ${parts.length}: ${JSON.stringify(expression)}`,\n );\n const [minute, hour, dom, month, weekday] = parts as [string, string, string, string, string];\n return {\n minutes: parseField(minute, fields[0] as Field),\n hours: parseField(hour, fields[1] as Field),\n daysOfMonth: parseField(dom, fields[2] as Field),\n months: parseField(month, fields[3] as Field),\n weekdays: parseField(weekday, fields[4] as Field),\n anyDayOfMonth: dom === \"*\",\n anyWeekday: weekday === \"*\",\n };\n}\n\n/** Whether the minute starting at `time` (ms since the epoch, UTC) matches. */\nexport function cronMatches(schedule: CronSchedule, time: number): boolean {\n const d = new Date(time);\n if (!schedule.minutes.has(d.getUTCMinutes()) || !schedule.hours.has(d.getUTCHours()))\n return false;\n if (!schedule.months.has(d.getUTCMonth() + 1)) return false;\n const dayOk = schedule.daysOfMonth.has(d.getUTCDate());\n const weekdayOk = schedule.weekdays.has(d.getUTCDay() + 1);\n // Both day fields restricted: either may match (standard cron); one restricted: it must.\n if (!schedule.anyDayOfMonth && !schedule.anyWeekday) return dayOk || weekdayOk;\n return dayOk && weekdayOk;\n}\n\nconst minuteMs = 60_000;\n/**\n * Between two matches of any expression Cloudflare accepts lie at most eight\n * years (the 29th of February across a century's missing leap year); an\n * expression with no match in that span never fires.\n */\nconst longestGapMs = 9 * 366 * 24 * 60 * minuteMs;\n\n/** The first `count` tick times at or after `from`, each the start of a matching minute. */\nexport function cronTicks(expression: string, from: number, count: number): number[] {\n const schedule = parseCron(expression);\n const out: number[] = [];\n let t = Math.ceil(from / minuteMs) * minuteMs;\n let horizon = t + longestGapMs;\n while (out.length < count) {\n if (t > horizon) throw new Error(`${JSON.stringify(expression)} never fires`);\n if (cronMatches(schedule, t)) {\n out.push(t);\n horizon = t + longestGapMs;\n }\n t += minuteMs;\n }\n return out;\n}\n","/**\n * Typed construction of scenario specs for Cloudflare Workers. Everything here\n * produces the plain-data `ScenarioSpec` from core; this module only knows the\n * Cloudflare shapes (queues, D1 bindings) and the effect conventions the\n * proxies follow.\n */\n\nimport {\n type AtLeastOnce,\n type Bounds,\n atLeastOncePerMessage as coreAtLeastOncePerMessage,\n defaultBounds,\n type EffectSelector,\n type EventRef,\n type EveryRow,\n type ExternalDecl,\n type Implies,\n type Invariant,\n type JsonValue,\n type PlatformData,\n type References,\n type Refines,\n type RowCondition,\n type ScenarioSpec,\n type ScriptedResponse,\n type StateQuery,\n type Unique,\n validateScenario,\n type WorkerRef,\n} from \"@eutaxy/core\";\nimport { virtualEpoch } from \"@eutaxy/engine\";\nimport { cronTicks, parseCron } from \"./cron.ts\";\nimport type { R2Seed } from \"./r2.ts\";\n\n/** One queue message to deliver; `id` defaults to its position. */\nexport interface QueueMessage {\n readonly id?: string;\n readonly body: JsonValue;\n}\n\n/** Drive the Worker's `queue()` handler with these messages. */\nexport interface QueueDrive extends PlatformData {\n readonly kind: \"queue\";\n readonly queue: string;\n readonly messages: readonly { readonly id: string; readonly body: JsonValue }[];\n}\n\n/** One inbound request; `id` defaults to its position, `method` to POST with a body and GET without. */\nexport interface HttpRequestInput {\n readonly id?: string;\n readonly method?: string;\n readonly path: string;\n readonly headers?: { readonly [name: string]: string };\n /** JSON body (sent as application/json) or a string body. */\n readonly body?: JsonValue;\n}\n\n/** A type alias, not an interface, so it is assignable to the JSON shape of `PlatformData`. */\nexport type HttpRequestSpec = {\n readonly id: string;\n readonly method: string;\n readonly path: string;\n readonly headers: { readonly [name: string]: string };\n /** Absent: no body at all. `null` is a JSON body, sent as `null`. */\n readonly body?: JsonValue;\n};\n\n/**\n * Drive the Worker's `fetch()` handler with these requests. The caller's\n * retry policy decides redelivery: a webhook provider resends a request it\n * got no 2xx for (`retryOn: \"non-2xx\"`, the default) or only on 5xx and\n * failures (`\"5xx\"`), up to `retries` times; a browser-like caller has\n * `retries: 0`. `delaysMs[i]` is the virtual time the caller waits before\n * its resend number i + 1 (the last entry repeats; none means at once).\n * `deadlineMs` is how long the caller waits for an answer: one that comes\n * later counts as failed and is resent while the handler may still run.\n */\nexport interface HttpDrive extends PlatformData {\n readonly kind: \"http\";\n readonly requests: readonly HttpRequestSpec[];\n readonly retries: number;\n readonly retryOn: \"non-2xx\" | \"5xx\";\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\nexport interface HttpCallerOptions {\n readonly retries?: number;\n readonly retryOn?: \"non-2xx\" | \"5xx\";\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\nexport function http(\n requests: readonly HttpRequestInput[],\n options: HttpCallerOptions = {},\n): HttpDrive {\n return {\n kind: \"http\",\n requests: requests.map((r, i) => ({\n id: r.id ?? `req-${i + 1}`,\n method: (r.method ?? (r.body === undefined ? \"GET\" : \"POST\")).toUpperCase(),\n path: r.path,\n headers: r.headers ?? {},\n ...(r.body === undefined ? {} : { body: r.body }),\n })),\n retries: options.retries ?? 3,\n retryOn: options.retryOn ?? \"non-2xx\",\n ...(options.delaysMs === undefined ? {} : { delaysMs: [...options.delaysMs] }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n };\n}\n\n/** One RPC call; `id` defaults to its position, `args` to none. */\nexport interface RpcCallInput {\n readonly id?: string;\n readonly method: string;\n readonly args?: readonly JsonValue[];\n}\n\n/** A type alias, not an interface, so it is assignable to the JSON shape of `PlatformData`. */\nexport type RpcCallSpec = {\n readonly id: string;\n readonly method: string;\n readonly args: readonly JsonValue[];\n};\n\n/**\n * Drive a `WorkerEntrypoint` of the Worker with these method calls, one\n * invocation per attempt, the entrypoint constructed anew for each. The\n * entrypoint is the Worker's default export, or the named export\n * `entrypoint`. Cloudflare does not retry an RPC call; the caller resends\n * a call that threw or got no answer up to `retries` times (default 0: a\n * calling Worker resends only when written to), after `delaysMs` of\n * virtual time, and gives up waiting at `deadlineMs`, as the HTTP drive's\n * caller does.\n */\nexport interface RpcDrive extends PlatformData {\n readonly kind: \"rpc\";\n readonly entrypoint?: string;\n readonly calls: readonly RpcCallSpec[];\n readonly retries: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\nexport interface RpcCallerOptions {\n readonly entrypoint?: string;\n readonly retries?: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\nexport function rpc(calls: readonly RpcCallInput[], options: RpcCallerOptions = {}): RpcDrive {\n return {\n kind: \"rpc\",\n ...(options.entrypoint === undefined ? {} : { entrypoint: options.entrypoint }),\n calls: calls.map((c, i) => ({\n id: c.id ?? `call-${i + 1}`,\n method: c.method,\n args: [...(c.args ?? [])],\n })),\n retries: options.retries ?? 0,\n ...(options.delaysMs === undefined ? {} : { delaysMs: [...options.delaysMs] }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n };\n}\n\n/** The target of a call's effects: the method, under the entrypoint's name when the drive names one. */\nexport function rpcTarget(drive: Pick<RpcDrive, \"entrypoint\">, method: string): string {\n return `Rpc:${drive.entrypoint === undefined ? method : `${drive.entrypoint}.${method}`}`;\n}\n\n/** One tick of a Cron Trigger: its id and the virtual time it fires, which the handler sees as `scheduledTime`. */\nexport type CronTickSpec = { readonly id: string; readonly at: number };\n\n/**\n * Drive the Worker's `scheduled()` handler with the ticks of a Cron Trigger:\n * the expression's first `ticks` matches from the virtual epoch on, in UTC,\n * each an event delivered at its virtual time. Cloudflare documents\n * `noRetry()` but no retry count, so the drive declares how many times a\n * tick whose handler failed is re-run (`retries`, default 0); a handler that\n * called `noRetry()` is not re-run.\n */\nexport interface CronDrive extends PlatformData {\n readonly kind: \"cron\";\n readonly cron: string;\n readonly ticks: readonly CronTickSpec[];\n readonly retries: number;\n}\n\nexport interface CronOptions {\n /** How many ticks to drive, from the first match on (default 1). */\n readonly ticks?: number;\n readonly retries?: number;\n}\n\nexport function cron(expression: string, options: CronOptions = {}): CronDrive {\n const count = options.ticks ?? 1;\n const times =\n Number.isInteger(count) && count >= 1 ? cronTicks(expression, virtualEpoch, count) : [];\n return {\n kind: \"cron\",\n cron: expression,\n ticks: times.map((at, i) => ({ id: `tick-${i + 1}`, at })),\n retries: options.retries ?? 0,\n };\n}\n\n/** The drives a Cloudflare scenario can have. */\nexport type Drive = QueueDrive | HttpDrive | RpcDrive | CronDrive;\n\n/** The drive's events as they are first delivered: one per message, request or call, attempt 1. */\nexport function driveEvents(drive: Drive): readonly EventRef[] {\n switch (drive.kind) {\n case \"queue\":\n return drive.messages.map((m) => ({ id: m.id, attempt: 1, data: m.body }));\n case \"http\":\n return drive.requests.map((r) => ({ id: r.id, attempt: 1, data: r as unknown as JsonValue }));\n case \"rpc\":\n return drive.calls.map((c) => ({ id: c.id, attempt: 1, data: c as unknown as JsonValue }));\n case \"cron\":\n // Delivered at its virtual time: the clock moves there once nothing else can.\n return drive.ticks.map((t) => ({\n id: t.id,\n attempt: 1,\n data: { cron: drive.cron, scheduledTime: t.at },\n at: t.at,\n }));\n }\n}\n\n/** The drive with only the named events kept, for shrinking. */\nexport function restrictDrive(drive: Drive, keepIds: readonly string[]): Drive {\n const keep = (id: string): boolean => keepIds.includes(id);\n switch (drive.kind) {\n case \"queue\":\n return { ...drive, messages: drive.messages.filter((m) => keep(m.id)) };\n case \"http\":\n return { ...drive, requests: drive.requests.filter((r) => keep(r.id)) };\n case \"rpc\":\n return { ...drive, calls: drive.calls.filter((c) => keep(c.id)) };\n case \"cron\":\n return { ...drive, ticks: drive.ticks.filter((t) => keep(t.id)) };\n }\n}\n\n/** Apply a SQL file to a D1 binding before each run. */\nexport interface D1Setup extends PlatformData {\n readonly kind: \"d1\";\n readonly binding: string;\n readonly schemaFile: string;\n}\n\n/**\n * Clear a Durable Object namespace before each run and seed the named\n * objects' storage with these entries; its storage is snapshotted after the\n * run for state invariants (see `durableObjectRows`).\n */\nexport interface DurableObjectSetup extends PlatformData {\n readonly kind: \"durable_object\";\n readonly binding: string;\n readonly objects: { readonly [name: string]: { readonly [key: string]: JsonValue } };\n /**\n * How many times each object's alarm may fire in one run (retries not\n * counted); an object that keeps re-arming stops there. Default 3.\n */\n readonly alarmsPerObject?: number;\n}\n\nexport function durableObject(\n binding: string,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } } = {},\n options: { readonly alarmsPerObject?: number } = {},\n): DurableObjectSetup {\n return {\n kind: \"durable_object\",\n binding,\n objects,\n ...(options.alarmsPerObject === undefined ? {} : { alarmsPerObject: options.alarmsPerObject }),\n };\n}\n\n/** An R2 bucket the scenario uses: emptied, then seeded with these objects, before each run. */\nexport interface R2Setup extends PlatformData {\n readonly kind: \"r2\";\n readonly binding: string;\n readonly objects: Readonly<Record<string, R2Seed>>;\n}\n\nexport function r2Bucket(binding: string, objects: Readonly<Record<string, R2Seed>> = {}): R2Setup {\n return { kind: \"r2\", binding, objects };\n}\n\n/**\n * Selects an R2 bucket's operations that completed, a `put` by default; a\n * put whose `onlyIf` failed stored nothing and is not selected, as a D1\n * write that changed no row is not.\n */\nexport function r2Op(\n binding: string,\n op: \"put\" | \"delete\" | \"get\" | \"head\" | \"list\" = \"put\",\n): EffectSelector {\n const target = `R2:${binding}`;\n return op === \"put\"\n ? { target, op, kind: \"result\", where: { \"result.stored\": true } }\n : { target, op, kind: \"result\" };\n}\n\n/** A bucket's objects at the end of the run as rows `{ key, size, etag, customMetadata, httpMetadata, text? }`. */\nexport function r2Rows(binding: string, where?: readonly RowCondition[]): StateQuery {\n const target = `R2:${binding}`;\n return where ? { target, table: \"objects\", where } : { target, table: \"objects\" };\n}\n\n/**\n * Every row the query returns is named by some row of `in` (its `column`\n * equals the row's value at `path`), as with a foreign key.\n */\nexport function references(\n name: string,\n query: StateQuery,\n path: string,\n inQuery: StateQuery,\n column: string,\n): References {\n return { kind: \"references\", name, query, path, in: inQuery, column };\n}\n\n/** A Workflow binding, and the class (an export of the Worker module) its instances run. */\nexport interface WorkflowSetup extends PlatformData {\n readonly kind: \"workflow\";\n readonly binding: string;\n readonly className: string;\n /** The Workflow's `name` in the wrangler config, which instances see as `event.workflowName`. */\n readonly name?: string;\n}\n\nexport function workflow(\n binding: string,\n className: string,\n options: { readonly name?: string } = {},\n): WorkflowSetup {\n return {\n kind: \"workflow\",\n binding,\n className,\n ...(options.name === undefined ? {} : { name: options.name }),\n };\n}\n\n/** A scripted method's reply: a value returned to the caller, or an error (`\"<Name>: <message>\"`) thrown to it. */\nexport type ScriptedReply = { readonly returns: JsonValue } | { readonly throws: string };\n\n/** A reply to `fetch()` through a service binding; a type alias of core's `ScriptedResponse`, for the JSON shape. */\nexport type ServiceResponse = {\n readonly method?: string;\n readonly path?: string;\n readonly status: number;\n readonly headers?: { readonly [name: string]: string };\n readonly body?: JsonValue;\n};\n\n/**\n * Script the Worker another Worker reaches through a service binding: its\n * RPC methods answer from `methods` (every method returns `null` when\n * omitted; a method missing from a present `methods` makes the run\n * UNSUPPORTED) and its `fetch()` from `fetch`, matched by method and path\n * as an external's responses are (200 with an empty body when omitted).\n * The real binding is never called. Each call is one effect,\n * `Service:<binding>`, with the faults of a Durable Object stub call.\n */\nexport interface ServiceSetup extends PlatformData {\n readonly kind: \"service\";\n readonly binding: string;\n readonly methods?: { readonly [method: string]: ScriptedReply };\n readonly fetch?: readonly ServiceResponse[];\n}\n\nexport function service(\n binding: string,\n options: {\n readonly methods?: { readonly [method: string]: ScriptedReply };\n readonly fetch?: readonly ServiceResponse[];\n } = {},\n): ServiceSetup {\n return {\n kind: \"service\",\n binding,\n ...(options.methods === undefined ? {} : { methods: options.methods }),\n ...(options.fetch === undefined ? {} : { fetch: [...options.fetch] }),\n };\n}\n\n/** Selects the calls through a service binding that completed, one method's or all. */\nexport function serviceCall(binding: string, method?: string): EffectSelector {\n return {\n target: `Service:${binding}`,\n ...(method === undefined ? {} : { op: method }),\n kind: \"result\",\n };\n}\n\n/** Selects a Workflow's step attempts, optionally of one step; a failed attempt's result carries its error. */\nexport function workflowStep(binding: string, step?: string): EffectSelector {\n return {\n target: `Workflow:${binding}`,\n op: \"step_result\",\n kind: \"result\",\n ...(step === undefined ? {} : { where: { \"args.step\": step } }),\n };\n}\n\n/** A Workflow's instances at the end of the run as rows `{ id, status, params, output?, error? }`. */\nexport function workflowRows(binding: string, where?: readonly RowCondition[]): StateQuery {\n const target = `Workflow:${binding}`;\n return where ? { target, table: \"instances\", where } : { target, table: \"instances\" };\n}\n\n/** Alarm firings per object per run when the setup does not say. */\nexport const defaultAlarmsPerObject = 3;\n\n/**\n * The storage of one object (by the name its id was made from) as rows\n * `{ key, value }`, for state invariants.\n */\nexport function durableObjectRows(\n binding: string,\n object: string,\n where?: readonly RowCondition[],\n): StateQuery {\n const target = `DO:${binding}`;\n return where ? { target, table: object, where } : { target, table: object };\n}\n\nexport interface CloudflareScenarioInput {\n readonly name: string;\n readonly worker: WorkerRef;\n readonly drive:\n | QueueDrive\n | HttpDrive\n | RpcDrive\n | CronDrive\n | {\n readonly kind: \"queue\";\n readonly queue: string;\n readonly messages: readonly QueueMessage[];\n };\n readonly setup?: readonly (\n | D1Setup\n | DurableObjectSetup\n | R2Setup\n | WorkflowSetup\n | ServiceSetup\n )[];\n readonly externals?: readonly ExternalDecl[];\n readonly invariants: readonly Invariant[];\n readonly bounds?: Partial<Bounds>;\n /** Modules of pure core functions with spec files beside them, relative to the scenario (see ScenarioSpec.specs). */\n readonly specs?: readonly string[];\n}\n\nexport function queue(name: string, messages: readonly QueueMessage[]): QueueDrive {\n return {\n kind: \"queue\",\n queue: name,\n messages: messages.map((m, i) => ({ id: m.id ?? `msg-${i + 1}`, body: m.body })),\n };\n}\n\nexport function d1Schema(binding: string, schemaFile: string): D1Setup {\n return { kind: \"d1\", binding, schemaFile };\n}\n\n/**\n * Effect conventions for D1 (what the proxies record):\n * call payload { args: { sql, params } }\n * result payload { args: { sql, params }, result: { changes, lastRowId } }\n * A committed write is a `result` whose `result.changes` is at least 1.\n */\nexport function d1Write(binding: string, op: \"run\" | \"batch\" = \"run\"): EffectSelector {\n return { target: `D1:${binding}`, op, kind: \"result\", atLeast: { \"result.changes\": 1 } };\n}\n\n/** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */\nexport function d1Read(binding: string, op: \"first\" | \"all\" | \"raw\" = \"first\"): EffectSelector {\n return { target: `D1:${binding}`, op, kind: \"result\" };\n}\n\n/** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */\nexport function d1Param(index: number): string {\n return `args.params.${index}`;\n}\n\n/**\n * The shell follows the core function `decision` (see the `refines`\n * invariant): every selected effect carries out the latest decision of its\n * invocation, agrees with it on `follows`, and, with `state`, was not made\n * stale by another invocation's write between the read it rests on and the\n * effect. The core function's module must be listed in the scenario's\n * `specs`, which is what records its calls.\n */\nexport function refines(\n name: string,\n decision: string,\n effect: EffectSelector,\n options: Pick<Refines, \"follows\" | \"state\"> = {},\n): Refines {\n return { kind: \"refines\", name, decision, effect, ...options };\n}\n\n/**\n * Every message's (or request's, or call's) `bodyKey` value must appear at\n * least once as `key` in a selected effect: nothing the drive delivered may\n * be lost. For an RPC drive `bodyKey` is a path into the call's arguments\n * (`\"0.orderId\"`).\n */\nexport function atLeastOncePerMessage(\n name: string,\n drive: Drive,\n effect: EffectSelector,\n key: string,\n bodyKey: string,\n): AtLeastOnce {\n if (drive.kind === \"queue\")\n return coreAtLeastOncePerMessage(name, drive.messages, effect, key, bodyKey);\n if (drive.kind === \"cron\") {\n const ticks = drive.ticks.map((t) => ({\n id: t.id,\n body: { cron: drive.cron, scheduledTime: t.at },\n }));\n return coreAtLeastOncePerMessage(name, ticks, effect, key, bodyKey);\n }\n if (drive.kind === \"rpc\") {\n const calls = drive.calls.map((c) => ({ id: c.id, body: c.args }));\n const inv = coreAtLeastOncePerMessage(name, calls, effect, key, bodyKey);\n // An RPC event's data is the whole call, so the path to re-derive from starts at its arguments.\n return { ...inv, perMessage: { bodyKey: bodyKey === \"\" ? \"args\" : `args.${bodyKey}` } };\n }\n const requests = drive.requests.map((r) => ({ id: r.id, body: r.body ?? null }));\n const inv = coreAtLeastOncePerMessage(name, requests, effect, key, bodyKey);\n // An HTTP event's data is the whole request, so the path to re-derive from starts at its body.\n return { ...inv, perMessage: { bodyKey: bodyKey === \"\" ? \"body\" : `body.${bodyKey}` } };\n}\n\n/**\n * Selects the responses the Worker returned for a path (`ok` narrows to 2xx\n * or to everything else). One `result` per attempt: a crash before the\n * response leaves none, a thrown error records status 500.\n */\nexport function httpResponse(\n path: string,\n options: { readonly ok?: boolean } = {},\n): EffectSelector {\n return {\n target: `Http:${path}`,\n op: \"response\",\n kind: \"result\",\n ...(options.ok === undefined ? {} : { where: { \"result.ok\": options.ok } }),\n };\n}\n\n/**\n * Selects the answers an RPC method gave (`ok` narrows to values returned\n * or to errors thrown). One `result` per attempt: a crash before the\n * response leaves none.\n */\nexport function rpcResponse(\n method: string,\n options: { readonly ok?: boolean; readonly entrypoint?: string } = {},\n): EffectSelector {\n return {\n target: rpcTarget(options, method),\n op: \"response\",\n kind: \"result\",\n ...(options.ok === undefined ? {} : { where: { \"result.ok\": options.ok } }),\n };\n}\n\n/** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */\nexport function d1Rows(\n binding: string,\n table: string,\n where?: readonly RowCondition[],\n): StateQuery {\n return where ? { target: `D1:${binding}`, table, where } : { target: `D1:${binding}`, table };\n}\n\n/** Every row the query selects satisfies all conditions. */\nexport function everyRow(\n name: string,\n query: StateQuery,\n holds: readonly RowCondition[],\n): EveryRow {\n return { kind: \"everyRow\", name, query, holds };\n}\n\n/** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */\nexport function unique(name: string, query: StateQuery, path: string): Unique {\n return { kind: \"unique\", name, query, path };\n}\n\n/** Every selected effect has a row whose column equals the effect's key. */\nexport function implies(\n name: string,\n when: EffectSelector,\n key: string,\n state: StateQuery,\n column: string,\n): Implies {\n return { kind: \"implies\", name, when, key, state, column };\n}\n\n/** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */\nexport function queueAck(queueName: string): EffectSelector {\n return {\n target: `Queue:${queueName}`,\n op: \"ack\",\n kind: \"result\",\n where: { \"result.effective\": true },\n };\n}\n\n/**\n * Declare an external service: requests to `host` are answered from\n * `responses` (every request gets 200 and an empty body when omitted), and\n * `dedupeBy` names the header whose value makes repeated requests\n * idempotent at that service.\n */\nexport function external(\n name: string,\n host: string,\n options: { readonly dedupeBy?: string; readonly responses?: readonly ScriptedResponse[] } = {},\n): ExternalDecl {\n return {\n name,\n host,\n guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},\n ...(options.responses ? { responses: options.responses } : {}),\n };\n}\n\n/**\n * Selects the requests to an external that took effect: a request replayed\n * under a dedupe key the external had already seen is not counted.\n */\nexport function fetchCall(externalName: string, method?: string): EffectSelector {\n return {\n target: `Fetch:${externalName}`,\n ...(method ? { op: method.toUpperCase() } : {}),\n kind: \"result\",\n where: { \"result.effective\": true },\n };\n}\n\nfunction validateHttpDrive(drive: HttpDrive): readonly string[] {\n const errors: string[] = [];\n if (drive.requests.length === 0) errors.push(\"http drive needs at least one request\");\n const ids = new Set<string>();\n drive.requests.forEach((r, i) => {\n if (!r.path.startsWith(\"/\")) errors.push(`requests[${i}].path must start with \"/\"`);\n if (!r.method) errors.push(`requests[${i}].method must not be empty`);\n if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);\n ids.add(r.id);\n if ((r.method === \"GET\" || r.method === \"HEAD\") && r.body !== undefined)\n errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);\n });\n errors.push(...validateCaller(\"http\", drive));\n return errors;\n}\n\n/** The caller's policy, as both drives a caller resends declare it. */\nfunction validateCaller(\n kind: string,\n drive: {\n readonly retries: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n },\n): readonly string[] {\n const errors: string[] = [];\n if (!(Number.isInteger(drive.retries) && drive.retries >= 0))\n errors.push(`${kind} drive retries must be a non-negative integer`);\n (drive.delaysMs ?? []).forEach((d, i) => {\n if (!(Number.isInteger(d) && d >= 0))\n errors.push(`${kind} drive delaysMs[${i}] must be a non-negative integer`);\n });\n if (\n drive.deadlineMs !== undefined &&\n !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)\n )\n errors.push(`${kind} drive deadlineMs must be a positive integer`);\n return errors;\n}\n\nfunction validateCronDrive(drive: CronDrive): readonly string[] {\n const errors: string[] = [];\n try {\n parseCron(drive.cron);\n } catch (err) {\n errors.push(`cron drive: ${(err as Error).message}`);\n }\n if (drive.ticks.length === 0) errors.push(\"cron drive ticks must be a positive integer\");\n const ids = new Set<string>();\n drive.ticks.forEach((t, i) => {\n if (ids.has(t.id)) errors.push(`duplicate tick id ${JSON.stringify(t.id)}`);\n ids.add(t.id);\n const previous = drive.ticks[i - 1];\n if (previous && !(t.at > previous.at))\n errors.push(`ticks[${i}] does not come after ticks[${i - 1}]`);\n });\n if (!(Number.isInteger(drive.retries) && drive.retries >= 0))\n errors.push(\"cron drive retries must be a non-negative integer\");\n return errors;\n}\n\n/** A method name the entrypoint can have: an identifier that is not the constructor. */\nconst methodName = /^[A-Za-z_$][\\w$]*$/;\n\nfunction validateRpcDrive(drive: RpcDrive): readonly string[] {\n const errors: string[] = [];\n if (drive.entrypoint !== undefined && !methodName.test(drive.entrypoint))\n errors.push(\"rpc drive entrypoint must be an exported class name\");\n const ids = new Set<string>();\n drive.calls.forEach((c, i) => {\n if (!methodName.test(c.method) || c.method === \"constructor\")\n errors.push(`calls[${i}].method must be a method name`);\n if (!Array.isArray(c.args)) errors.push(`calls[${i}].args must be an array`);\n if (ids.has(c.id)) errors.push(`duplicate call id ${JSON.stringify(c.id)}`);\n ids.add(c.id);\n });\n errors.push(...validateCaller(\"rpc\", drive));\n return errors;\n}\n\n/** Build and validate a scenario spec; throws with every problem listed. */\nexport function defineScenario(input: CloudflareScenarioInput): ScenarioSpec {\n // queue() keeps the ids a QueueDrive already has, so it serves both forms.\n const drive: Drive =\n input.drive.kind === \"queue\" ? queue(input.drive.queue, input.drive.messages) : input.drive;\n const spec: ScenarioSpec = {\n version: 1,\n name: input.name,\n platform: \"cloudflare\",\n worker: input.worker,\n drive,\n setup: input.setup ?? [],\n externals: input.externals ?? [],\n invariants: input.invariants,\n bounds: { ...defaultBounds, ...input.bounds },\n ...(input.specs ? { specs: input.specs } : {}),\n };\n const errors = [\n ...validateScenario(spec),\n ...(drive.kind === \"http\" ? validateHttpDrive(drive) : []),\n ...(drive.kind === \"rpc\" ? validateRpcDrive(drive) : []),\n ...(drive.kind === \"cron\" ? validateCronDrive(drive) : []),\n ];\n if (errors.length > 0) {\n throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\\n- ${errors.join(\"\\n- \")}`);\n }\n return spec;\n}\n","/**\n * Service bindings with the callee scripted. A Worker reaches a peer through\n * `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on\n * the same thread and retries nothing (Workers, service bindings). The real\n * binding is never called here: the scenario's `service()` setup scripts the\n * replies, and each call is one effect with the faults of a Durable Object\n * stub call, where `crash_before` and `error` mean the call never reached\n * the callee, `ambiguous` that it acted and the answer was lost, and\n * `crash_after` that the caller died after it.\n */\n\nimport { type EffectPoint, type JsonValue, toJson, writeFaults } from \"@eutaxy/core\";\nimport { findResponse, isRedirect, parseBody, replyOf, toResponse } from \"@eutaxy/engine\";\nimport type { ProxyContext } from \"./d1.ts\";\nimport type { ScriptedReply, ServiceSetup } from \"./scenario.ts\";\n\n/** Marks of the other kinds of binding, which a service binding's duck type must not carry. */\nconst otherKinds = [\"prepare\", \"idFromName\", \"head\", \"createBatch\"];\n\n/**\n * Whether an env value is a service binding (the runtime's `Fetcher`). In\n * workerd it is an RPC stub whose every property read yields a callable, so\n * duck typing alone would take it for any other kind: the runtime's class is\n * checked first, and the duck type (fetch and connect, none of the other\n * kinds' marks) serves test doubles.\n */\nexport function isServiceBinding(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n const fetcher = (globalThis as { Fetcher?: unknown }).Fetcher;\n if (typeof fetcher === \"function\" && value instanceof fetcher) return true;\n const ctor = Object.getPrototypeOf(value)?.constructor as { name?: string } | undefined;\n if (ctor?.name === \"Fetcher\") return true;\n const v = value as Record<string, unknown>;\n return (\n typeof v[\"fetch\"] === \"function\" &&\n typeof v[\"connect\"] === \"function\" &&\n otherKinds.every((k) => typeof v[k] !== \"function\")\n );\n}\n\n/** The built-in error classes RPC carries across as themselves (workerd keeps the type). */\nconst builtInErrors: { readonly [name: string]: new (message: string) => Error } = {\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n};\n\n/**\n * The error the caller sees for a `throws` reply, `\"<Name>: <message>\"`: a\n * built-in error class is that class, so `instanceof` holds as it does over\n * RPC; any other name is an `Error` carrying the name.\n */\nexport function scriptedError(spec: string): Error {\n const at = spec.indexOf(\": \");\n if (at < 0) return new Error(spec);\n const name = spec.slice(0, at);\n const message = spec.slice(at + 2);\n const builtIn = builtInErrors[name];\n if (builtIn) return new builtIn(message);\n const error = new Error(message);\n error.name = name;\n return error;\n}\n\n/** The scripted stub a Worker sees under a service binding's name. */\nexport function proxyService(binding: string, ctx: ProxyContext, script: ServiceSetup): object {\n const target = `Service:${binding}`;\n const point = (op: string, args: JsonValue): EffectPoint => ({\n invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed: writeFaults,\n });\n const unsupported = (what: string): never => {\n const reason = `service binding ${binding}: ${what}`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */\n const replyTo = (method: string): ScriptedReply => {\n if (script.methods === undefined) return { returns: null };\n if (!Object.hasOwn(script.methods, method))\n return unsupported(\n `no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`,\n );\n return script.methods[method] as ScriptedReply;\n };\n const answer = (method: string): unknown => {\n const reply = replyTo(method);\n if (\"throws\" in reply) throw scriptedError(reply.throws);\n // Copied, as RPC copies values: the Worker cannot change the script.\n return structuredClone(reply.returns);\n };\n\n const fetchThrough = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const request = new Request(input, init);\n const url = new URL(request.url);\n const method = request.method.toUpperCase();\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const body = parseBody(await request.text());\n const reply = await ctx.hooks.effect(\n point(method, { url: request.url, method, headers, body }),\n async () => {\n // The matcher is the externals'; a service binding takes any host, so none is matched.\n const found = findResponse(\n {\n name: binding,\n host: url.host,\n guarantees: {},\n ...(script.fetch === undefined ? {} : { responses: script.fetch }),\n },\n method,\n url.pathname,\n );\n if (found === undefined)\n return unsupported(\n `no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`,\n );\n const reply = replyOf(found);\n // workerd follows a redirect from the callee as fetch does; the script holds only the first reply.\n if (isRedirect(reply.status) && request.redirect !== \"manual\")\n return unsupported(\n `the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: \"manual\"`,\n );\n return reply;\n },\n (r) => ({ status: r.status }),\n );\n return toResponse(reply);\n };\n\n /**\n * The promise a call returns. On the real stub it is an RPC promise that\n * pipelines property reads (`stub.charge().id`); this one is not, so a read\n * on it makes the run UNSUPPORTED instead of yielding undefined.\n */\n const pipelineGuard = <T>(promise: Promise<T>, method: string): Promise<T> =>\n new Proxy(promise, {\n get(target, prop) {\n if (typeof prop === \"symbol\" || prop === \"then\" || prop === \"catch\" || prop === \"finally\") {\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n ctx.hooks.unsupported(\n `service binding ${binding}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`,\n );\n return undefined;\n },\n });\n\n /** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */\n const call = (method: string) => {\n const invoke = (...args: unknown[]) =>\n pipelineGuard(\n ctx.hooks.effect(\n point(method, { args: args.map((a) => toJson(a)) }),\n async () => answer(method),\n (value) => ({ value: toJson(value) }),\n ),\n method,\n );\n const read = () =>\n ctx.hooks.effect(\n point(method, { property: true }),\n async () => answer(method),\n (value) => ({ value: toJson(value) }),\n );\n const awaitable = (\n onFulfilled?: (v: unknown) => unknown,\n onRejected?: (e: unknown) => unknown,\n ) => read().then(onFulfilled, onRejected);\n // Callable and awaitable; any other property read is pipelining, which is not modelled.\n return new Proxy(invoke, {\n get(fn, key) {\n if (key === \"then\") return awaitable;\n if (typeof key === \"symbol\") return Reflect.get(fn, key);\n ctx.hooks.unsupported(\n `service binding ${binding}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`,\n );\n return undefined;\n },\n });\n };\n\n return new Proxy(\n {},\n {\n get(_stub, prop) {\n // The stub is not a promise.\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n if (prop === \"fetch\") return fetchThrough;\n if (prop === \"connect\")\n return () => unsupported(\"connect() (a raw TCP socket) is not modelled\");\n return call(prop);\n },\n },\n );\n}\n","/**\n * Constructing an entrypoint class (`WorkerEntrypoint`, `WorkflowEntrypoint`)\n * outside the runtime, for the one `new` per call or instance run that the\n * models make themselves.\n */\n\n/** Sets `ctx` and `env` as the runtime's base classes do, for the one `new` workerd would refuse. */\nclass StandInEntrypoint {\n readonly ctx: unknown;\n readonly env: unknown;\n constructor(ctx: unknown, env: unknown) {\n this.ctx = ctx;\n this.env = env;\n }\n}\n\n/**\n * Construct a subclass of the entrypoint base class named `base`. workerd's\n * base constructors accept only a native ExecutionContext, so for this one\n * synchronous `new` the class that extends the base directly extends a\n * stand-in instead; its own constructor and field initialisers run as\n * written, and the base is put back before anything else can run.\n */\nexport function constructEntrypoint(\n cls: unknown,\n base: \"WorkerEntrypoint\" | \"WorkflowEntrypoint\",\n ctx: unknown,\n env: unknown,\n): object {\n if (typeof cls !== \"function\") throw new TypeError(\"not a class\");\n let direct = cls as object;\n for (;;) {\n const parent = Object.getPrototypeOf(direct) as unknown;\n if (typeof parent !== \"function\" || parent === Function.prototype)\n throw new TypeError(`${(cls as { name: string }).name} does not extend ${base}`);\n if ((parent as { name: string }).name === base) break;\n direct = parent;\n }\n const original = Object.getPrototypeOf(direct) as object;\n Object.setPrototypeOf(direct, StandInEntrypoint);\n try {\n return Reflect.construct(cls as new (...a: unknown[]) => object, [ctx, env]);\n } finally {\n Object.setPrototypeOf(direct, original);\n }\n}\n","/**\n * Workflows, modelled: the binding's `create`/`get`, and each instance run\n * as invocations of its class's `run(event, step)` against a model of the\n * engine (persisted step results, retries in virtual time, restarts that\n * re-run `run` from the start). The real local engine is never called: it\n * runs on its own real-time clock and retry loop, which Eutaxy can neither\n * fault nor schedule. See docs/design.md, \"Workflows\".\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n type FaultKind,\n invocationOf,\n type JsonValue,\n type RunHooks,\n toJson,\n writeFaults,\n} from \"@eutaxy/core\";\nimport {\n CrashSignal,\n InjectedEffectError,\n type Outcome as RunOutcome,\n runInvocation,\n} from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\nimport { constructEntrypoint } from \"./entrypoint.ts\";\n\n/** The `EventRef.source` of a Workflow instance's run. */\nexport const workflowSource = \"workflow\";\n\n/** Before a step's callback: the engine restarts before the step runs. */\nconst STEP_START: readonly FaultKind[] = [\"crash_before\"];\n/**\n * After it: the engine restarts after the step ran but before its result\n * was persisted (`crash_after`), or the attempt ran and counted as failed,\n * as a timeout does (`ambiguous`).\n */\nconst STEP_RESULT: readonly FaultKind[] = [\"crash_after\", \"ambiguous\"];\n\n/**\n * Cloudflare's defaults for a step without a config (Workflows, Sleeping\n * and retrying). A partial config is merged with them field by field, as\n * the engine does. Miniflare's local engine waits 1 s by default; the\n * model keeps the documented 10 s.\n */\nconst defaultRetries = { limit: 5, delay: 10_000, backoff: \"exponential\" } as const;\n\n/**\n * A persisted step result; a failure is kept as the engine keeps it, serialised\n * (built-in types survive; a custom error name does not survive the clone, so\n * it is kept beside and put back on replay).\n */\ntype Outcome =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown; readonly errorName?: string };\n\n/** Keep a thrown value as the engine keeps it, with an Error's name, which the clone would lose. */\nfunction failure(thrown: unknown): Outcome {\n let kept: unknown;\n try {\n kept = structuredClone(thrown);\n } catch {\n kept = new Error(String(thrown));\n }\n return thrown instanceof Error\n ? { ok: false, error: kept, errorName: thrown.name }\n : { ok: false, error: kept };\n}\n\n/** An event sent to an instance, as `waitForEvent` returns it. */\nexport interface InstanceEvent {\n readonly type: string;\n readonly payload: unknown;\n readonly timestamp: Date;\n}\n\nexport interface Instance {\n readonly id: string;\n readonly params: unknown;\n readonly createdAt: number;\n /** The engine's statuses the model reaches; `waiting` while a wait for an event is pending. */\n status: \"queued\" | \"running\" | \"waiting\" | \"complete\" | \"errored\";\n /** Events sent and not yet consumed by a wait, in order, per type (the engine's buffer). */\n readonly events: Map<string, InstanceEvent[]>;\n /**\n * The pending wait, while the instance is `waiting`: its type, its generation, which a wake\n * must match, and whether an event already woke it (a second event is buffered, not a second wake).\n */\n waiting: { readonly type: string; readonly gen: number; woken: boolean } | undefined;\n /** Generations of waits so far, so a stale wake (the timeout of a wait an event ended) is told apart. */\n waitGen: number;\n /** What `run` returned, as the engine keeps it; summarised only where it is recorded. */\n output?: unknown;\n error?: { readonly name: string; readonly message: string };\n /** Persisted step and sleep results, by name and count: what a restart replays. */\n readonly persisted: Map<string, Outcome>;\n /** Attempts started per step, persisted as the engine does, so a restart goes on counting. */\n readonly attempts: Map<string, number>;\n /** Each step's config as its first attempt resolved it; a restart reuses it, as the engine does. */\n readonly configs: Map<\n string,\n { readonly retries: ResolvedRetries; readonly timeout: unknown; readonly sensitive?: string }\n >;\n /** Each pending sleep's or retry's deadline, persisted before it waits, so a restart waits only the rest. */\n readonly deadlines: Map<string, number>;\n}\n\n/** One binding's instances in the current run. */\nexport class WorkflowRegistry {\n readonly instances = new Map<string, Instance>();\n\n clear(): void {\n this.instances.clear();\n }\n\n /** The instances as rows for the end-of-run snapshot, by id. */\n rows(): JsonValue[] {\n return [...this.instances.values()]\n .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n .map((i) => ({\n id: i.id,\n status: i.status,\n params: toJson(i.params),\n ...(i.output === undefined ? {} : { output: toJson(i.output) }),\n ...(i.error === undefined ? {} : { error: `${i.error.name}: ${i.error.message}` }),\n }));\n }\n}\n\n/** A Workflow binding as the env shows it (Miniflare's `WorkflowImpl`). */\nexport function isWorkflowBinding(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v[\"create\"] === \"function\" &&\n typeof v[\"createBatch\"] === \"function\" &&\n typeof v[\"get\"] === \"function\"\n );\n}\n\ninterface CreateOptions {\n readonly id?: string;\n readonly params?: unknown;\n}\n\n/** The binding's proxy: instances live in the registry and run as events, never in the real engine. */\nexport function proxyWorkflow(\n binding: string,\n ctx: ProxyContext,\n registry: WorkflowRegistry,\n): object {\n const target = `Workflow:${binding}`;\n const unsupported = (what: string): never => {\n const reason = `Workflow ${binding}: ${what} is not modelled`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n const handle = (id: string): object => ({\n id,\n status: () =>\n ctx.hooks.effect(\n { invocation: ctx.currentInvocation(), target, op: \"status\", args: { id }, allowed: [] },\n async () => {\n const i = registry.instances.get(id);\n if (!i) throw new Error(\"instance.not_found\");\n return {\n status: i.status,\n // A copy, as the binding's serialised answer is: the caller cannot change the instance.\n // The binding answers null when there is no output yet, or run() returned nothing.\n output: i.output === undefined ? null : structuredClone(i.output),\n ...(i.error === undefined ? {} : { error: { ...i.error } }),\n };\n },\n (s) => toJson(s),\n ),\n pause: () => unsupported(\"pause()\"),\n resume: () => unsupported(\"resume()\"),\n terminate: () => unsupported(\"terminate()\"),\n restart: () => unsupported(\"restart()\"),\n sendEvent: (args: { readonly type?: unknown; readonly payload?: unknown } = {}) =>\n ctx.hooks.effect(\n {\n invocation: ctx.currentInvocation(),\n target,\n op: \"send_event\",\n args: { id, type: toJson(args.type), payload: toJson(args.payload) },\n // A call to the engine: it may never arrive, or arrive with its answer lost.\n allowed: writeFaults,\n },\n async () => {\n const type = validEventType(args.type);\n const i = registry.instances.get(id);\n if (!i) throw new Error(\"instance.not_found\");\n if (i.status === \"complete\" || i.status === \"errored\")\n throw new Error(\n `(instance.not_running) Workflow instance with id \"${id}\" is ${i.status} and takes no events`,\n );\n const event: InstanceEvent = {\n type,\n payload: structuredClone(args.payload),\n timestamp: new Date(),\n };\n const queue = i.events.get(type) ?? [];\n queue.push(event);\n i.events.set(type, queue);\n // A wait for this type is pending: wake the instance once; its timeout wake becomes stale.\n if (i.status === \"waiting\" && i.waiting?.type === type && !i.waiting.woken) {\n i.waiting.woken = true;\n ctx.hooks.enqueue({\n id: `workflow:${binding}:${id}:event-${i.waiting.gen}`,\n attempt: 1,\n source: workflowSource,\n data: { binding, id, wake: i.waiting.gen },\n });\n }\n return null;\n },\n () => null,\n ),\n delete: () => unsupported(\"delete()\"),\n subscribe: () => unsupported(\"subscribe()\"),\n });\n return {\n async create(options: CreateOptions = {}) {\n // Generated with the run's virtual randomness, before the call, as the binding does locally.\n const id = options.id ?? crypto.randomUUID();\n // The binding's own default (Miniflare): no params is an empty object; null stays null.\n const params = structuredClone(options.params === undefined ? {} : options.params);\n return ctx.hooks.effect(\n {\n invocation: ctx.currentInvocation(),\n target,\n op: \"create\",\n args: { id, params: toJson(params) },\n // A call to the engine: it may never arrive, or arrive with its answer lost.\n allowed: writeFaults,\n },\n async () => {\n if (!validInstanceId(id)) throw new Error(\"Workflow instance has invalid id\");\n if (registry.instances.has(id))\n throw new Error(\n `(instance.already_exists) Workflow instance with id \"${id}\" already exists`,\n );\n registry.instances.set(id, {\n id,\n params,\n createdAt: Date.now(),\n status: \"queued\",\n events: new Map(),\n waiting: undefined,\n waitGen: 0,\n persisted: new Map(),\n attempts: new Map(),\n configs: new Map(),\n deadlines: new Map(),\n });\n ctx.hooks.enqueue({\n id: `workflow:${binding}:${id}`,\n attempt: 1,\n source: workflowSource,\n data: { binding, id },\n });\n return handle(id);\n },\n () => ({ id }),\n );\n },\n async get(id: string) {\n return ctx.hooks.effect(\n { invocation: ctx.currentInvocation(), target, op: \"get\", args: { id }, allowed: [] },\n async () => {\n if (!registry.instances.has(id)) throw new Error(\"instance.not_found\");\n return handle(id);\n },\n () => ({ id }),\n );\n },\n createBatch: () => unsupported(\"createBatch()\"),\n deleteBatch: () => unsupported(\"deleteBatch()\"),\n };\n}\n\n/** The binding's rule for an instance id (Miniflare): up to 100 of these characters. */\nfunction validInstanceId(id: unknown): boolean {\n return typeof id === \"string\" && id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(id);\n}\n\n/** An event type as Workflows accept it (Events and parameters): up to 100 of these characters, else `workflow.invalid_event_type`. */\nfunction validEventType(type: unknown): string {\n if (typeof type === \"string\" && type.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(type))\n return type;\n throw new Error(\n `(workflow.invalid_event_type) event type must be up to 100 letters, digits, - or _, got ${JSON.stringify(type)}`,\n );\n}\n\n/** Thrown through `run()` to suspend an instance waiting for an event; never meant to be caught. */\nclass Suspension {\n readonly gen: number;\n constructor(gen: number) {\n this.gen = gen;\n }\n}\n\n/** A wake event's data: which wait's generation it ends. */\ninterface WakeData {\n readonly binding: string;\n readonly id: string;\n readonly wake?: number;\n}\n\n/**\n * Whether a run event wakes the instance: not a wake at all, the restart of a\n * run a wake began (its first delivery resumed the instance), or the wake of\n * the wait still pending.\n */\nexport function wakes(instance: Instance, event: EventRef): boolean {\n const wake = (event.data as unknown as WakeData).wake;\n if (wake === undefined || event.attempt > 1) return true;\n return instance.status === \"waiting\" && instance.waiting?.gen === wake;\n}\n\n/** Construct a `WorkflowEntrypoint` subclass outside the runtime, for the one `new` per instance run. */\nexport function constructWorkflow(cls: unknown, ctx: unknown, env: unknown): object {\n return constructEntrypoint(cls, \"WorkflowEntrypoint\", ctx, env);\n}\n\n/** The engine's conversion (itty-time): a year is 365.25 days, a month 30; an unknown unit counts 1. */\nconst units: { readonly [unit: string]: number } = {\n year: 31_557_600_000,\n month: 2_592_000_000,\n week: 604_800_000,\n day: 86_400_000,\n hour: 3_600_000,\n minute: 60_000,\n second: 1000,\n m: 1,\n};\n\n/** The engine's reading of a duration, NaN where it reads none. */\nfunction engineDuration(d: unknown): number {\n if (!Number.isNaN(Number(d)) && typeof d !== \"object\") return Number(d);\n if (typeof d !== \"string\") return Number.NaN;\n const m = /^([^ ]+) +(\\w\\w*?)s?$/.exec(d);\n if (!m) return Number.NaN;\n return Number(m[1]) * (units[m[2] as string] ?? 1);\n}\n\n/** A Workflows duration in milliseconds, read as the engine reads it. */\nexport function durationMs(d: unknown): number {\n const ms = engineDuration(d);\n if (Number.isNaN(ms) || ms < 0) throw new TypeError(`not a Workflows duration: ${String(d)}`);\n return ms;\n}\n\n/** Miniflare's `isValidStepConfig`, exactly: its schema is strict, and a timeout `== 0` is refused. */\nexport function validStepConfig(config: unknown): boolean {\n const only = (o: object, keys: readonly string[]) =>\n Object.keys(o).every((k) => keys.includes(k));\n const durationOk = (v: unknown) => !Number.isNaN(engineDuration(v));\n if (\n typeof config !== \"object\" ||\n config === null ||\n !only(config, [\"retries\", \"timeout\", \"sensitive\"])\n )\n return false;\n const c = config as Record<string, unknown>;\n const r = c[\"retries\"] as Record<string, unknown> | undefined;\n if (r !== undefined) {\n if (typeof r !== \"object\" || r === null || !only(r, [\"delay\", \"limit\", \"backoff\"]))\n return false;\n const delay = r[\"delay\"];\n if (\n !(\n typeof delay === \"function\" ||\n typeof delay === \"string\" ||\n (typeof delay === \"number\" && delay >= 0)\n )\n )\n return false;\n if (typeof r[\"limit\"] !== \"number\" || r[\"limit\"] < 0) return false;\n if (\n r[\"backoff\"] !== undefined &&\n ![\"constant\", \"linear\", \"exponential\"].includes(r[\"backoff\"] as string)\n )\n return false;\n if (typeof delay !== \"function\" && !durationOk(delay)) return false;\n }\n const t = c[\"timeout\"];\n if (t !== undefined) {\n if (!(typeof t === \"string\" || (typeof t === \"number\" && t >= 0))) return false;\n // biome-ignore lint/suspicious/noDoubleEquals: the engine's own loose test (\"0\" and \"\" are zero)\n if (t == 0 || !durationOk(t)) return false;\n }\n if (c[\"sensitive\"] !== undefined && c[\"sensitive\"] !== \"output\") return false;\n return true;\n}\n\nconst utf8 = new TextEncoder();\n\n/** About how many bytes a value takes stored, walking it as structured cloning does. */\nfunction approximateBytes(value: unknown, seen = new Set<object>()): number {\n if (value === null || value === undefined) return 1;\n switch (typeof value) {\n case \"string\":\n return utf8.encode(value).length;\n case \"number\":\n case \"bigint\":\n return 8;\n case \"boolean\":\n return 1;\n case \"object\":\n break;\n default:\n return 0;\n }\n const o = value as object;\n if (seen.has(o)) return 0;\n seen.add(o);\n if (o instanceof ArrayBuffer || ArrayBuffer.isView(o)) return o.byteLength;\n if (o instanceof Date) return 8;\n let total = 0;\n if (o instanceof Map)\n for (const [k, v] of o) total += approximateBytes(k, seen) + approximateBytes(v, seen);\n else if (o instanceof Set) for (const v of o) total += approximateBytes(v, seen);\n else\n for (const [k, v] of Object.entries(o))\n total += utf8.encode(k).length + approximateBytes(v, seen);\n return total;\n}\n\nfunction sleep(ms: number): Promise<void> {\n // The virtual setTimeout: the run fires it when the invocation is idle.\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\ninterface ResolvedRetries {\n readonly limit: number;\n readonly delay: unknown;\n readonly backoff?: string;\n}\n\ninterface StepConfig {\n readonly retries?: { readonly limit: number; readonly delay: unknown; readonly backoff?: string };\n readonly timeout?: unknown;\n /** \"output\": the step's output is redacted in the engine's logs, here in the trace. */\n readonly sensitive?: string;\n}\n\ninterface RunDelivery {\n readonly binding: string;\n /** The Workflow's configured name, for `event.workflowName`. */\n readonly name?: string;\n readonly instance: Instance;\n readonly cls: unknown;\n /** The env the instance sees: the proxied bindings. */\n readonly env: object;\n readonly maxFaultsPerRun: number;\n readonly maxRedeliveries: number;\n}\n\n/**\n * One engine attempt of an instance: construct its class and call `run`.\n * Steps whose results were persisted return them without running; a crash\n * restarts the instance (a new attempt, from the start of `run`).\n */\nexport async function deliverWorkflow(\n event: EventRef,\n hooks: RunHooks,\n d: RunDelivery,\n): Promise<DeliveryResult> {\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const target = `Workflow:${d.binding}`;\n const instance = d.instance;\n // A wake of a wait that already ended (an event came before the timeout, or the reverse): nothing to do.\n if (!wakes(instance, event)) return { status: \"completed\", followUps: [] };\n instance.status = \"running\";\n instance.waiting = undefined;\n const background: Promise<unknown>[] = [];\n const counts = new Map<string, number>();\n const key = (kind: string, name: string): string => {\n const count = (counts.get(`${kind}:${name}`) ?? 0) + 1;\n counts.set(`${kind}:${name}`, count);\n return `${kind}:${name}#${count}`;\n };\n const replay = (o: Outcome): unknown => {\n if (o.ok) return structuredClone(o.value);\n const error: unknown = structuredClone(o.error);\n if (o.errorName !== undefined && error instanceof Error) error.name = o.errorName;\n throw error;\n };\n\n const step = {\n do: async (name: string, a: unknown, b?: unknown, c?: unknown): Promise<unknown> => {\n const [config, fn, options] = (typeof a === \"function\" ? [{}, a, b] : [a ?? {}, b, c]) as [\n StepConfig,\n (ctx: unknown) => unknown,\n { rollback?: unknown } | undefined,\n ];\n if (suspending !== undefined) continuedAfterSuspension(\"step.do\");\n if (options?.rollback !== undefined) {\n hooks.unsupported(`Workflow ${d.binding}: rollback handlers are not modelled`);\n throw new Error(\"eutaxy: rollback handlers are not modelled\");\n }\n // The engine's checks, before anything runs: fatal errors there, whose catching is not documented.\n const fatal = (message: string): never => {\n hooks.unsupported(`Workflow ${d.binding}: ${message}`);\n const err = new Error(message);\n err.name = \"WorkflowFatalError\";\n throw err;\n };\n if (name.length > 256 || [...name].some((c) => c.charCodeAt(0) < 0x20))\n fatal(`Step name \"${name}\" exceeds max length (256 chars) or invalid characters found`);\n if (!validStepConfig(config))\n fatal(\n `Step config for \"${name}\" is in a invalid format. See https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/`,\n );\n const k = key(\"do\", name);\n const count = counts.get(`do:${name}`) as number;\n const done = instance.persisted.get(k);\n if (done) return replay(done);\n const live = { ...defaultRetries, ...config.retries };\n const first = instance.configs.get(k);\n if (!first)\n instance.configs.set(k, {\n retries: live,\n timeout: config.timeout ?? \"10 minutes\",\n ...(config.sensitive === undefined ? {} : { sensitive: config.sensitive }),\n });\n const sensitive = first ? first.sensitive : config.sensitive;\n const stored = first?.retries;\n // A delay function is not persisted: the engine calls the one the current run passes, or\n // falls back to the default delay; the crashed run's function is never called again.\n const retries =\n stored && typeof stored.delay === \"function\"\n ? {\n ...stored,\n delay: typeof live.delay === \"function\" ? live.delay : defaultRetries.delay,\n }\n : (stored ?? live);\n const limit = Math.min(retries.limit, d.maxRedeliveries);\n // What the callback sees: a delay function is not exposed (Workflows, Step context).\n const { delay, ...shown } = retries;\n const resolved = {\n retries: typeof delay === \"function\" ? shown : retries,\n timeout: first ? first.timeout : (config.timeout ?? \"10 minutes\"),\n ...(sensitive === undefined ? {} : { sensitive }),\n };\n for (let attempt = (instance.attempts.get(k) ?? 0) + 1; ; attempt++) {\n // A retry the engine was waiting for when it restarted: only the rest of its delay.\n const due = instance.deadlines.get(`retry:${k}`);\n if (due !== undefined) {\n await sleep(Math.max(0, due - Date.now()));\n instance.deadlines.delete(`retry:${k}`);\n }\n // A fresh copy per attempt: what the callback does to it does not reach the engine's own.\n const stepContext = {\n step: { name, count },\n attempt,\n config: { ...resolved, retries: { ...resolved.retries } },\n };\n const args = { instance: instance.id, step: name, count, attempt };\n // The callback runs as the instance's own code, between two points: its effects are ordinary\n // effects of the invocation, and its timers are virtual. The points are asynchronous, as the\n // engine's reading and persisting are: other events may run between steps.\n await hooks.effect(\n { invocation, target, op: \"step\", args, allowed: STEP_START },\n async () => null,\n () => null,\n );\n instance.attempts.set(k, attempt);\n // What the attempt threw, kept as thrown (a plain value too), as the engine rethrows it.\n let failed = false;\n let thrown: unknown;\n let value: unknown;\n let returned: { readonly value: unknown } | undefined;\n try {\n returned = { value: await fn(stepContext) };\n } catch (err) {\n // A crash ends the attempt and the instance; it is not a failure to retry.\n if (err instanceof CrashSignal || inv.isCrashed()) throw err;\n failed = true;\n thrown = err;\n try {\n hooks.effectSync(\n { invocation, target, op: \"step_result\", args, allowed: [] },\n () => {\n throw err;\n },\n () => null,\n );\n } catch {\n // Recorded as the attempt's error; handled below.\n }\n }\n if (returned !== undefined) {\n const notModelled = (reason: string): never => {\n hooks.unsupported(`Workflow ${d.binding}: step \"${name}\" ${reason}`);\n throw new Error(`eutaxy: step \"${name}\" ${reason}`);\n };\n try {\n value = structuredClone(returned.value);\n } catch {\n // A stream, or anything else the engine persists in its own way: not a failure to retry.\n notModelled(\n \"returned a value that is not structured-cloneable (a ReadableStream is not modelled)\",\n );\n }\n if (approximateBytes(value) > 1_048_576)\n notModelled(\n 'returned more than about 1 MiB, which the engine refuses (\"output is too large\"); Eutaxy cannot measure the stored size exactly',\n );\n }\n if (!failed) {\n try {\n await hooks.effect(\n { invocation, target, op: \"step_result\", args, allowed: STEP_RESULT },\n async () => value,\n (v) => ({ output: sensitive === \"output\" ? \"[REDACTED]\" : toJson(v) }),\n );\n instance.persisted.set(k, { ok: true, value });\n return structuredClone(value);\n } catch (err) {\n if (err instanceof CrashSignal || !(err instanceof InjectedEffectError)) throw err;\n // The attempt ran but counted as failed: a timeout, as the engine reports one.\n thrown = Object.assign(\n new Error(`Execution timed out after ${durationMs(resolved.timeout)}ms`),\n { name: \"WorkflowTimeoutError\" },\n );\n }\n }\n // The engine's predicate (an Error so named, or whose message starts so). It rethrows the\n // value as thrown and does not persist it, so after a restart the callback runs again.\n if (\n thrown instanceof Error &&\n (thrown.name === \"NonRetryableError\" || thrown.message.startsWith(\"NonRetryableError\"))\n )\n throw thrown;\n if (attempt > limit) {\n instance.persisted.set(k, failure(thrown));\n throw thrown;\n }\n let wait: number;\n try {\n // A fresh context from the engine's own values: the callback may have changed its copy.\n const delayContext = {\n step: { name, count },\n attempt,\n config: { ...resolved, retries: { ...resolved.retries } },\n };\n wait = await retryDelayMs(retries, attempt, delayContext, thrown);\n } catch (err) {\n hooks.unsupported(\n `Workflow ${d.binding}: step \"${name}\"'s retry delay function threw (${String(err)})`,\n );\n throw err;\n }\n instance.deadlines.set(`retry:${k}`, Date.now() + wait);\n await sleep(wait);\n instance.deadlines.delete(`retry:${k}`);\n }\n },\n sleep: async (name: string, duration: unknown): Promise<void> => {\n const ms = durationMs(duration);\n // Keyed by name and duration, as the engine keys sleeps: another duration is another sleep.\n await sleepStep(key(\"sleep\", `${name}\\u0000${ms}`), name, ms);\n },\n sleepUntil: async (name: string, timestamp: unknown): Promise<void> => {\n const at = timestamp instanceof Date ? timestamp.getTime() : Number(timestamp);\n const k = key(\"sleepUntil\", `${name}\\u0000${at}`);\n if (instance.persisted.has(k)) {\n // Miniflare's engine checks the time before its cache and throws here; production is undocumented.\n if (at < Date.now())\n hooks.unsupported(\n `Workflow ${d.binding}: step.sleepUntil \"${name}\" replayed after its time, where Miniflare's engine throws`,\n );\n return;\n }\n // Miniflare's engine refuses a time in the past, with this message.\n if (at < Date.now() && !instance.deadlines.has(k))\n throw new Error(\"You can't sleep until a time in the past, time-traveler\");\n await sleepStep(k, name, Math.max(0, at - Date.now()), at);\n },\n waitForEvent: async (\n name: string,\n options: { readonly type?: unknown; readonly timeout?: unknown } = {},\n ): Promise<unknown> => {\n if (suspending !== undefined) continuedAfterSuspension(\"step.waitForEvent\");\n const type = validEventType(options.type);\n const timeoutMs = durationMs(options.timeout ?? \"24 hours\");\n if (!(timeoutMs >= 1000 && timeoutMs <= 365 * 24 * 3_600_000)) {\n hooks.unsupported(\n `Workflow ${d.binding}: waitForEvent \"${name}\" timeout must be between 1 second and 365 days`,\n );\n const err = new Error(`Invalid timeout for waitForEvent \"${name}\"`);\n err.name = \"WorkflowFatalError\";\n throw err;\n }\n // Keyed by name and count, as the engine keys waits.\n const k = key(\"waitForEvent\", name);\n const done = instance.persisted.get(k);\n if (done) return replay(done);\n const args = { instance: instance.id, step: name, type };\n const existing = instance.deadlines.get(k);\n // An event already sent: the first of its type, as the engine's queue gives it, if it came\n // before the wait's deadline; one sent after it finds the wait timed out and stays buffered.\n const queue = instance.events.get(type) ?? [];\n const inTime = queue.findIndex(\n (e) => existing === undefined || e.timestamp.getTime() < existing,\n );\n const received = inTime < 0 ? undefined : queue.splice(inTime, 1)[0];\n if (received) {\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"event\",\n args: { ...args, timestamp: received.timestamp.getTime() },\n allowed: [],\n },\n () => received,\n (e) => ({ payload: toJson(e.payload) }),\n );\n instance.persisted.set(k, { ok: true, value: received });\n return structuredClone(received);\n }\n if (existing !== undefined && Date.now() >= existing) {\n // The wait's time is up: the error is the step's, persisted, and the instance fails unless the code catches it.\n const error = Object.assign(new Error(`Execution timed out after ${timeoutMs}ms`), {\n name: \"WorkflowTimeoutError\",\n });\n hooks.effectSync(\n { invocation, target, op: \"wait_timeout\", args, allowed: [] },\n () => null,\n () => null,\n );\n instance.persisted.set(k, failure(error));\n throw error;\n }\n const deadline = existing ?? Date.now() + timeoutMs;\n if (existing === undefined) {\n instance.deadlines.set(k, deadline);\n hooks.effectSync(\n { invocation, target, op: \"wait\", args: { ...args, timeoutMs }, allowed: [] },\n () => null,\n () => null,\n );\n }\n // Nothing to wait on yet: the instance hibernates until the event or the deadline wakes it.\n const gen = ++instance.waitGen;\n instance.waiting = { type, gen, woken: false };\n suspending = { gen, deadline };\n throw new Suspension(gen);\n },\n };\n /** Set once a wait suspended this run: anything the code does after it caught the suspension is not modelled. */\n let suspending: { readonly gen: number; readonly deadline: number } | undefined;\n const continuedAfterSuspension = (what: string): never => {\n const reason = `Workflow ${d.binding}: ${what} after step.waitForEvent suspended the instance; the code caught the suspension (catch only the wait's WorkflowTimeoutError)`;\n hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n async function sleepStep(k: string, name: string, ms: number, until?: number): Promise<void> {\n if (suspending !== undefined) continuedAfterSuspension(\"step.sleep\");\n if (instance.persisted.has(k)) return;\n const pending = instance.deadlines.get(k);\n if (pending !== undefined) {\n await sleep(Math.max(0, pending - Date.now()));\n instance.persisted.set(k, { ok: true, value: null });\n return;\n }\n instance.deadlines.set(k, Date.now() + ms);\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"sleep\",\n args: { instance: instance.id, step: name, ms, ...(until === undefined ? {} : { until }) },\n allowed: [],\n },\n () => null,\n () => null,\n );\n await sleep(ms);\n instance.persisted.set(k, { ok: true, value: null });\n }\n\n const ran = await runInvocation(hooks, inv, () => {\n const flow = constructWorkflow(d.cls, executionContext(background), d.env) as {\n run(event: unknown, step: unknown): unknown;\n };\n const workflowEvent: Record<string, unknown> = {\n payload: structuredClone(instance.params),\n timestamp: new Date(instance.createdAt),\n instanceId: instance.id,\n };\n if (d.name !== undefined) workflowEvent[\"workflowName\"] = d.name;\n else\n Object.defineProperty(workflowEvent, \"workflowName\", {\n enumerable: true,\n get: () => {\n hooks.unsupported(\n `Workflow ${d.binding}: event.workflowName needs the Workflow's name, workflow(binding, className, { name })`,\n );\n return undefined;\n },\n });\n return flow.run(workflowEvent, step);\n });\n // The engine keeps the result serialised: one it cannot keep fails the instance.\n const serialised = (value: unknown): RunOutcome<unknown> => {\n try {\n return { status: \"completed\", value: structuredClone(value) };\n } catch {\n hooks.unsupported(\n `Workflow ${d.binding}: run() returned a value that is not structured-cloneable`,\n );\n return {\n status: \"errored\",\n error: new Error(\"run() returned a value that is not structured-cloneable\"),\n };\n }\n };\n let result: RunOutcome<unknown> = ran.status === \"completed\" ? serialised(ran.value) : ran;\n if (suspending !== undefined) {\n // The run ended by suspending: its outcome is the wait, whatever the code made of the sentinel.\n if (!(ran.status === \"errored\" && ran.error instanceof Suspension) && ran.status !== \"crashed\")\n hooks.unsupported(\n `Workflow ${d.binding}: run() ${ran.status === \"completed\" ? \"returned\" : \"threw\"} after step.waitForEvent suspended the instance; the code caught the suspension (catch only the wait's WorkflowTimeoutError)`,\n );\n if (ran.status !== \"crashed\") result = { status: \"completed\", value: undefined };\n }\n let status = result.status;\n if (suspending !== undefined && result.status === \"completed\") {\n instance.status = \"waiting\";\n const suspended = suspending;\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n if (status === \"crashed\") {\n // The crash ends the run; the restart below suspends again with a new generation.\n instance.status = \"running\";\n instance.waiting = undefined;\n }\n const followUps: EventRef[] =\n status === \"crashed\"\n ? instance.status === \"running\" && event.attempt <= d.maxFaultsPerRun\n ? [{ ...event, attempt: event.attempt + 1 }]\n : []\n : [\n // The timeout wake, due at the deadline; an event sent earlier wakes the instance first.\n {\n id: `workflow:${d.binding}:${instance.id}:timeout-${suspended.gen}`,\n attempt: 1,\n source: workflowSource,\n data: { binding: d.binding, id: instance.id, wake: suspended.gen },\n at: suspended.deadline,\n },\n ];\n return { status, followUps };\n }\n if (result.status === \"completed\") {\n instance.status = \"complete\";\n instance.output = result.value;\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"complete\",\n args: { instance: instance.id, output: toJson(instance.output) },\n allowed: [],\n },\n () => null,\n () => null,\n );\n } else if (result.status === \"errored\") {\n instance.status = \"errored\";\n const e = result.error;\n instance.error =\n e instanceof Error\n ? { name: e.name, message: e.message }\n : { name: \"Error\", message: String(e) };\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"errored\",\n args: { instance: instance.id, error: `${instance.error.name}: ${instance.error.message}` },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n // The engine restarts a crashed instance from the start of `run`; crashes come from faults, so few.\n const followUps =\n status === \"crashed\" && instance.status === \"running\" && event.attempt <= d.maxFaultsPerRun\n ? [{ ...event, attempt: event.attempt + 1 }]\n : [];\n return { status, followUps };\n}\n\n/** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */\nasync function retryDelayMs(\n retries: NonNullable<StepConfig[\"retries\"]>,\n attempt: number,\n ctx: unknown,\n error: unknown,\n): Promise<number> {\n const delay =\n typeof retries.delay === \"function\"\n ? await (retries.delay as (i: unknown) => unknown)({ ctx, error })\n : retries.delay;\n // The backoff applies to a delay function's value too, as in Miniflare's engine.\n const base = durationMs(delay);\n switch (retries.backoff) {\n case \"linear\":\n return base * attempt;\n case \"exponential\":\n return base * 2 ** (attempt - 1);\n default:\n return base;\n }\n}\n","/**\n * Each kind of binding the platform models, as one record: how an env value\n * is recognised, what the Worker sees in its place, what is forgotten before\n * a run, the reset its setup step asks for, the snapshot the run ends with,\n * and, for the kinds with events of their own (alarms, Workflow runs), their\n * delivery. The platform and the differential runner iterate these records;\n * neither knows a kind by name.\n */\n\nimport type {\n DeliveryResult,\n EventRef,\n JsonValue,\n PlatformData,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { alarmSource, deliverAlarm } from \"./alarms.ts\";\nimport { isD1, type ProxyContext, proxyD1, resetD1, snapshotD1 } from \"./d1.ts\";\nimport {\n alarmRunner,\n BindingState,\n type DurableObjectTestHelpers,\n evictObject,\n isDurableObjectNamespace,\n proxyNamespace,\n resetNamespace,\n snapshotNamespace,\n} from \"./durable-objects.ts\";\nimport { isR2, proxyR2, resetR2, snapshotR2, VersionBook } from \"./r2.ts\";\nimport {\n type D1Setup,\n type DurableObjectSetup,\n defaultAlarmsPerObject,\n type R2Setup,\n type ServiceSetup,\n type WorkflowSetup,\n} from \"./scenario.ts\";\nimport { isServiceBinding, proxyService } from \"./services.ts\";\nimport {\n deliverWorkflow,\n isWorkflowBinding,\n proxyWorkflow,\n WorkflowRegistry,\n workflowSource,\n} from \"./workflows.ts\";\n\n/** A setup step that names a binding; every kind modelled here has one. */\nexport interface BindingSetup extends PlatformData {\n readonly binding: string;\n}\n\n/** The tables of one binding's end-of-run snapshot. */\nexport type Tables = { readonly [table: string]: readonly JsonValue[] };\n\n/**\n * One kind of binding. `Real` is the env value's type once `is` accepted it;\n * `Setup` the setup step that names a binding of this kind.\n */\nexport interface Binding<Real = unknown, Setup extends BindingSetup = BindingSetup> {\n /** The `kind` of the setup step naming a binding of this type. */\n readonly kind: Setup[\"kind\"];\n /** The prefix of its snapshot targets: `D1`, `DO`, `R2`, `Workflow`. */\n readonly target: string;\n /** Whether an env value is a binding of this kind. */\n is(value: unknown): value is Real;\n /**\n * What the Worker sees in place of the real binding, asked on every access\n * of `env.<name>`: the record keeps one proxy per name where it may, and\n * reports a binding the scenario did not set up each time it is touched.\n */\n proxy(name: string, real: Real, ctx: ProxyContext): unknown;\n /** Forget what the last run learned, before the next run's setup. */\n clear(): void;\n /** Bring the real binding, or the model, to the state the setup step asks for. */\n reset(step: Setup, real: unknown): Promise<void>;\n /**\n * The snapshot the run ends with, read through the real binding, or null\n * when the env value is not this binding. `unsupported` reports what the\n * snapshot found that the run could not control.\n */\n snapshot(\n step: Setup,\n real: unknown,\n unsupported: (reason: string) => void,\n ): Promise<Tables | null>;\n /** `EventRef.source` of the events this binding emits, when it has any. */\n readonly source?: string;\n /** Deliver one of its events. */\n deliver?(event: EventRef, hooks: RunHooks, spec: ScenarioSpec): Promise<DeliveryResult>;\n}\n\n/** A D1 database: Miniflare's SQLite, reset to the scenario's schema and read back whole. */\nexport function d1Binding(schemas: Readonly<Record<string, string>>): Binding<D1Database, D1Setup> {\n const proxies = new Map<string, D1Database>();\n return {\n kind: \"d1\",\n target: \"D1\",\n is: isD1,\n proxy(name, real, ctx) {\n let p = proxies.get(name);\n if (!p) {\n p = proxyD1(real, name, ctx);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {},\n async reset(step, real) {\n const schema = schemas[step.binding];\n if (schema === undefined)\n throw new Error(`no schema provided for D1 binding ${step.binding}`);\n if (!isD1(real)) throw new Error(`env.${step.binding} is not a D1 binding`);\n await resetD1(real, schema);\n },\n async snapshot(_step, real) {\n return isD1(real) ? snapshotD1(real) : null;\n },\n };\n}\n\n/** An R2 bucket: Miniflare's real one, emptied and seeded before each run. */\nexport function r2Binding(): Binding<R2Bucket, R2Setup> {\n /** The buckets the current scenario sets up. */\n let setUp = new Set<string>();\n const proxies = new Map<string, R2Bucket>();\n /** One book for every bucket: the stand-ins count up across them. */\n const versions = new VersionBook();\n return {\n kind: \"r2\",\n target: \"R2\",\n is: isR2,\n proxy(name, real, ctx) {\n if (!setUp.has(name))\n ctx.hooks.unsupported(\n `R2 binding ${name} needs an r2Bucket() setup step, which empties it before each run`,\n );\n let p = proxies.get(name);\n if (!p) {\n p = proxyR2(real, name, ctx, versions);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n setUp = new Set();\n versions.clear();\n },\n async reset(step, real) {\n if (!isR2(real)) throw new Error(`env.${step.binding} is not an R2 bucket`);\n setUp.add(step.binding);\n await resetR2(real, step.objects);\n },\n async snapshot(_step, real) {\n return isR2(real) ? { objects: await snapshotR2(real) } : null;\n },\n };\n}\n\nexport interface DurableObjectDeps {\n readonly ctx: ProxyContext;\n /** The Cloudflare test helpers, without which objects cannot be reset, seeded or snapshotted. */\n readonly helpers: DurableObjectTestHelpers | undefined;\n /** The env value under a binding name: alarm events name their binding, not an object. */\n readonly real: (name: string) => unknown;\n}\n\n/**\n * A Durable Object namespace: the real objects workerd runs, cleared, seeded\n * and evicted before each run, their storage snapshotted after it, and their\n * alarms taken over and fired as events of the run.\n */\nexport function durableObjectBinding(\n deps: DurableObjectDeps,\n): Binding<DurableObjectNamespace, DurableObjectSetup> {\n const { ctx, helpers } = deps;\n const proxies = new Map<string, DurableObjectNamespace>();\n /** The bindings the current scenario's setup resets before each run. */\n let setUp = new Set<string>();\n /** Per binding, alarm firings allowed per object in the current run. */\n let alarmLimits = new Map<string, number>();\n /** Per binding, what the current run knows about its objects. */\n const states = new Map<string, BindingState>();\n const stateFor = (binding: string): BindingState => {\n let state = states.get(binding);\n if (!state) {\n state = new BindingState();\n states.set(binding, state);\n }\n return state;\n };\n const namespace = (name: string, real: unknown = deps.real(name)): DurableObjectNamespace => {\n if (!isDurableObjectNamespace(real))\n throw new Error(`env.${name} is not a Durable Object namespace`);\n return real;\n };\n const required = (): DurableObjectTestHelpers => {\n if (!helpers)\n throw new Error(\n 'Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })',\n );\n return helpers;\n };\n return {\n kind: \"durable_object\",\n target: \"DO\",\n is: isDurableObjectNamespace,\n proxy(name, real, ctx) {\n let p = proxies.get(name);\n if (!p) {\n p = proxyNamespace(real, name, ctx, stateFor(name), helpers, () => setUp.has(name));\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n setUp = new Set();\n alarmLimits = new Map();\n for (const state of states.values()) state.clear();\n },\n async reset(step, real) {\n setUp.add(step.binding);\n alarmLimits.set(step.binding, step.alarmsPerObject ?? defaultAlarmsPerObject);\n await resetNamespace(\n namespace(step.binding, real),\n required(),\n stateFor(step.binding).names,\n step.objects,\n );\n },\n async snapshot(step, real, unsupported) {\n const binding = step.binding;\n return snapshotNamespace(\n namespace(binding, real),\n required(),\n stateFor(binding).names,\n stateFor(binding).touched,\n step.objects,\n (object) =>\n unsupported(\n `Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`,\n ),\n unsupported,\n );\n },\n source: alarmSource,\n async deliver(event, hooks, spec) {\n const binding = String((event.data as { binding?: unknown }).binding ?? \"\");\n return deliverAlarm(event, hooks, spec.bounds.maxRedeliveries, {\n binding,\n book: stateFor(binding).alarms,\n limit: alarmLimits.get(binding) ?? defaultAlarmsPerObject,\n runAlarm: alarmRunner(namespace(binding), binding, ctx, helpers, stateFor(binding)),\n abort: (id) => stateFor(binding).abort(id),\n mayPark: (id) => stateFor(binding).mayPark(id),\n evict: (id) => evictObject(namespace(binding), helpers, id),\n bookkeep: (op, args) =>\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target: `DO:${binding}`,\n op,\n args,\n allowed: [],\n },\n () => null,\n () => null,\n ),\n });\n },\n };\n}\n\nexport interface WorkflowDeps {\n /** The Worker module's exports, where the classes `workflow` setup steps name are found. */\n readonly exports: Readonly<Record<string, unknown>> | undefined;\n /** The env the instances run with: the Worker's proxied one. */\n readonly env: () => object;\n}\n\n/**\n * A Workflow binding: a model of the engine running the scenario's own\n * class, never the real binding; instances live in a registry and run as\n * events of the run.\n */\nexport function workflowBinding(deps: WorkflowDeps): Binding<object, WorkflowSetup> {\n /** The bindings the current scenario sets up, with the class each runs. */\n let classes = new Map<string, WorkflowSetup>();\n const registries = new Map<string, WorkflowRegistry>();\n const registryFor = (binding: string): WorkflowRegistry => {\n let r = registries.get(binding);\n if (!r) {\n r = new WorkflowRegistry();\n registries.set(binding, r);\n }\n return r;\n };\n const proxies = new Map<string, object>();\n return {\n kind: \"workflow\",\n target: \"Workflow\",\n is: isWorkflowBinding,\n proxy(name, _real, ctx) {\n if (!classes.has(name)) {\n ctx.hooks.unsupported(\n `Workflow binding ${name} needs a workflow() setup step naming its class`,\n );\n // Never the real binding: its engine would run the class on the real clock.\n return proxyWorkflow(name, ctx, new WorkflowRegistry());\n }\n let p = proxies.get(name);\n if (!p) {\n p = proxyWorkflow(name, ctx, registryFor(name));\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n classes = new Map();\n for (const registry of registries.values()) registry.clear();\n },\n async reset(step) {\n classes.set(step.binding, step);\n },\n async snapshot(step) {\n return { instances: registryFor(step.binding).rows() };\n },\n source: workflowSource,\n async deliver(event, hooks, spec) {\n const { binding, id } = event.data as { binding: string; id: string };\n const setup = classes.get(binding);\n // A binding with no setup step was already reported when the Worker touched it.\n if (!setup) return { status: \"errored\", followUps: [] };\n const className = setup.className;\n const cls = deps.exports?.[className];\n const instance = registryFor(binding).instances.get(id);\n if (typeof cls !== \"function\" || !instance) {\n hooks.unsupported(\n `Workflow ${binding}: class ${className} is not among the Worker module's exports; pass them as createCloudflarePlatform({ ..., exports })`,\n );\n return { status: \"errored\", followUps: [] };\n }\n return deliverWorkflow(event, hooks, {\n binding,\n ...(setup.name === undefined ? {} : { name: setup.name }),\n instance,\n cls,\n env: deps.env(),\n maxFaultsPerRun: spec.bounds.maxFaultsPerRun,\n maxRedeliveries: spec.bounds.maxRedeliveries,\n });\n },\n };\n}\n\n/**\n * A service binding: never the real binding, a stub answering from the\n * scenario's `service` setup; each call one effect. Nothing to reset or\n * snapshot, the callee is scripted.\n */\nexport function serviceBinding(): Binding<object, ServiceSetup> {\n /** The bindings the current scenario scripts. */\n let scripts = new Map<string, ServiceSetup>();\n /** Per binding, the stub for the current run's script. */\n const proxies = new Map<string, object>();\n return {\n kind: \"service\",\n target: \"Service\",\n is: isServiceBinding,\n proxy(name, _real, ctx) {\n const script = scripts.get(name);\n if (!script) {\n ctx.hooks.unsupported(\n `service binding ${name} needs a service() setup step scripting the Worker it reaches`,\n );\n // Never the real binding: it would call the real peer.\n return proxyService(name, ctx, { kind: \"service\", binding: name, methods: {} });\n }\n let p = proxies.get(name);\n if (!p) {\n p = proxyService(name, ctx, script);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n scripts = new Map();\n proxies.clear();\n },\n async reset(step) {\n scripts.set(step.binding, step);\n },\n async snapshot() {\n return null;\n },\n };\n}\n\n/**\n * The setup steps these records own, each with its record, in setup order:\n * what the platform resets and snapshots, and the differential runner\n * compares. A step no record owns is left to the scenario's validation.\n */\nexport function ownedSetups(\n setup: ScenarioSpec[\"setup\"],\n bindings: readonly Binding[],\n): readonly (readonly [Binding, BindingSetup])[] {\n const out: (readonly [Binding, BindingSetup])[] = [];\n for (const step of setup) {\n const binding = bindings.find((b) => b.kind === step.kind);\n if (binding) out.push([binding, step as BindingSetup]);\n }\n return out;\n}\n","/**\n * The caller of an inbound request or RPC call. Cloudflare retries neither,\n * so resends follow the policy the drive declares for the caller: how many\n * times it resends, the virtual delay before each resend, and how long it\n * waits for an answer. The decision is the caller's and is made once per\n * attempt: at the response point, or at its deadline if the handler has\n * not answered by then.\n */\n\nimport {\n type EventRef,\n type FaultKind,\n type JsonValue,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\n\n/** The response point: a crash before it is a response the caller never saw. */\nconst RESPOND: readonly FaultKind[] = [\"crash_before\"];\n/**\n * With a caller deadline the answer can also arrive too late: `ambiguous`\n * here means it was sent, the caller counted it as failed, and the handler\n * carried on.\n */\nconst RESPOND_WITH_DEADLINE: readonly FaultKind[] = [\"crash_before\", \"ambiguous\"];\n\n/** What a drive declares about its caller. */\nexport interface CallerPolicy {\n /** Resends after the first attempt. */\n readonly retries: number;\n /** Virtual time the caller waits before resend number i + 1; the last entry repeats, none means at once. */\n readonly delaysMs?: readonly number[];\n /** How long the caller waits for an answer; one that comes later counts as failed. */\n readonly deadlineMs?: number;\n}\n\n/** The virtual delay before resend number `resend` (1 for the first), per the policy. */\nexport function retryDelayMs(policy: Pick<CallerPolicy, \"delaysMs\">, resend: number): number {\n const delays = policy.delaysMs ?? [];\n return delays[Math.min(resend, delays.length) - 1] ?? 0;\n}\n\n/** One attempt's caller, waiting for its answer. */\nexport interface Caller {\n /** The faults the response point admits: with a deadline, also the answer that comes too late. */\n readonly responseFaults: readonly FaultKind[];\n /** Whether the virtual clock is past the caller's deadline now. */\n isLate(): boolean;\n /**\n * The caller's decision once the attempt has an answer or none: it accepts\n * the answer, or gives up, now or at its deadline when the answer was\n * late, and resends or stops.\n */\n settle(accepted: boolean, late: boolean): void;\n}\n\n/**\n * Start waiting for the attempt's answer. With a deadline, a virtual timer\n * makes the caller give up at it whatever the handler is doing, so a resend\n * can start while the first attempt still runs. `gaveUp` is what the\n * `gave_up` effect records when the retries are spent.\n */\nexport function startCaller(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n policy: CallerPolicy,\n target: string,\n gaveUp: JsonValue,\n): Caller {\n // Virtual time: when the caller sent this attempt, for its deadline.\n const started = Date.now();\n const deadline = policy.deadlineMs;\n // The caller gives up at its deadline even when the answer comes later still.\n const lateAt = deadline === undefined ? undefined : started + deadline;\n\n /** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */\n let decided = false;\n const giveUp = (at: number): void => {\n if (decided) return;\n decided = true;\n const next = redelivery(event, policy.retries, spec.bounds);\n if (next) {\n const resendAt = Math.max(at + retryDelayMs(policy, event.attempt), Date.now());\n hooks.enqueue({ ...next, ...(resendAt > Date.now() ? { at: resendAt } : {}) });\n } else {\n hooks.effectSync(\n { invocation: hooks.bookkeeping(), target, op: \"gave_up\", args: gaveUp, allowed: [] },\n () => null,\n () => null,\n );\n }\n };\n // A virtual timer: at the deadline the caller gives up, whatever the handler is doing.\n const deadlineTimer =\n lateAt === undefined ? undefined : setTimeout(() => giveUp(lateAt), deadline);\n\n return {\n responseFaults: deadline === undefined ? RESPOND : RESPOND_WITH_DEADLINE,\n isLate: () => lateAt !== undefined && Date.now() > lateAt,\n settle(accepted, late) {\n // The caller decides as soon as it has an answer or gives up, before background work ends.\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n if (accepted) decided = true;\n else giveUp(late && lateAt !== undefined ? lateAt : Date.now());\n },\n };\n}\n","/** Inbound HTTP delivery: one invocation per attempt of a request the drive's caller sends. */\n\nimport type { DeliveryResult, EventRef, JsonValue, RunHooks, ScenarioSpec } from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport { startCaller } from \"./caller.ts\";\nimport type { HttpDrive, HttpRequestSpec } from \"./scenario.ts\";\n\n/** The URL inbound requests are addressed to; handlers read only the path. */\nexport const requestOrigin = \"https://worker.test\";\n\n/** Build the `Request` a drive entry describes. */\nexport function requestFor(r: HttpRequestSpec): Request {\n const headers = new Headers(r.headers);\n let body: string | null = null;\n if (r.body !== undefined) {\n if (typeof r.body === \"string\") body = r.body;\n else {\n // Any JSON value, `null` included, travels as application/json.\n body = JSON.stringify(r.body);\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n }\n }\n return new Request(`${requestOrigin}${r.path}`, { method: r.method, headers, body });\n}\n\n/** A compact record of a response for the effect log: status, ok, and a bounded body. */\nexport async function summarizeResponse(response: Response): Promise<JsonValue> {\n const text = await response.clone().text();\n let body: JsonValue = text.length > 1000 ? `${text.slice(0, 1000)}…` : text;\n if (text && (response.headers.get(\"content-type\") ?? \"\").includes(\"json\")) {\n try {\n body = JSON.parse(text) as JsonValue;\n } catch {\n // keep the text\n }\n }\n return { status: response.status, ok: response.ok, body };\n}\n\n/** One attempt of an inbound request, under the caller's retry policy and deadline. */\nexport async function deliverRequest(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: HttpDrive,\n invocation: string,\n worker: RunningWorker,\n): Promise<DeliveryResult> {\n const req = event.data as unknown as HttpRequestSpec;\n const target = `Http:${req.path}`;\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n const handler = worker.handler.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n const args: JsonValue = { requestId: event.id, method: req.method, path: req.path };\n const caller = startCaller(event, hooks, spec, drive, target, {\n requestId: event.id,\n attempts: event.attempt,\n });\n\n const handled = await runInvocation(hooks, inv, () =>\n handler.call(worker.handler, requestFor(req), worker.env, executionContext(background)),\n );\n const response = handled.status === \"completed\" ? handled.value : undefined;\n let status: DeliveryResult[\"status\"] = handled.status;\n\n let summary: { status: number; ok: boolean } | null = null;\n let read: { status: number; ok: boolean; body: JsonValue } | \"crashed\" | \"errored\" = \"errored\";\n if (status === \"completed\" && response) {\n // The body is read before the point so the record is complete; the point itself is the send.\n // Streaming bodies run handler code: a crash inside it abandons the read, an error fails the delivery.\n const body = await runInvocation(hooks, inv, () => summarizeResponse(response));\n read =\n body.status === \"completed\"\n ? (body.value as { status: number; ok: boolean; body: JsonValue })\n : body.status;\n if (read === \"crashed\" || read === \"errored\") status = read;\n }\n let late = caller.isLate();\n const allowed = caller.responseFaults;\n if (status === \"completed\" && typeof read === \"object\") {\n const s = read;\n try {\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed },\n () => s,\n (v) => v,\n );\n summary = s;\n } catch (err) {\n if (err instanceof CrashSignal) status = \"crashed\";\n else if (err instanceof InjectedEffectError) {\n // Sent, but after the caller's deadline: the handler carries on, the caller resends.\n summary = s;\n late = true;\n } else throw err;\n }\n } else if (status === \"errored\") {\n // Cloudflare answers an uncaught exception with a 500 (workers runtime behaviour); the caller sees that.\n const s = { status: 500, ok: false, body: \"\" };\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed: [] },\n () => s,\n (v) => v,\n );\n summary = s;\n }\n\n const accepted =\n summary !== null && !late && (drive.retryOn === \"5xx\" ? summary.status < 500 : summary.ok);\n caller.settle(accepted, late);\n\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\n}\n","/** Queue delivery: one invocation per delivery of a message, redelivered until acked or dead-lettered. */\n\nimport {\n type DeliveryResult,\n decisionFaults,\n type EventRef,\n type JsonValue,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { CrashSignal, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport type { QueueDrive } from \"./scenario.ts\";\n\n/** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */\nfunction cloneJson(value: JsonValue): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n\n/** One delivery of a queue message, with Queues' at-least-once semantics. */\nexport async function deliverMessage(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: QueueDrive,\n invocation: string,\n worker: RunningWorker,\n maxRetries: number,\n): Promise<DeliveryResult> {\n const queueTarget = `Queue:${drive.queue}`;\n const inv = hooks.startInvocation(invocation);\n /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */\n const state: { decision: \"ack\" | \"retry\" | null } = { decision: null };\n const background: Promise<unknown>[] = [];\n\n /** Records the call; the result says whether it took effect (the first decision wins). */\n const decide = (op: \"ack\" | \"retry\", args: JsonValue): void => {\n hooks.effectSync(\n { invocation, target: queueTarget, op, args, allowed: decisionFaults },\n () => {\n if (state.decision !== null) return false;\n state.decision = op;\n return true;\n },\n (effective) => ({ effective }),\n );\n };\n const message: Message<unknown> = {\n id: event.id,\n timestamp: new Date(),\n body: cloneJson(event.data),\n attempts: event.attempt,\n ack: () => decide(\"ack\", { messageId: event.id, implicit: false, body: event.data }),\n retry: () => decide(\"retry\", { messageId: event.id, body: event.data }),\n };\n const batch: MessageBatch<unknown> = {\n queue: drive.queue,\n messages: [message],\n metadata: { metrics: { backlogCount: 0, backlogBytes: 0 } },\n ackAll: () => message.ack(),\n retryAll: () => message.retry(),\n };\n const execution = executionContext(background);\n\n const handler = worker.handler.queue;\n if (!handler) throw new Error(\"the Worker has no queue() handler\");\n let status: DeliveryResult[\"status\"] = (\n await runInvocation(hooks, inv, () =>\n handler.call(worker.handler, batch, worker.env, execution),\n )\n ).status;\n\n if (status === \"completed\" && state.decision === null) {\n try {\n decide(\"ack\", { messageId: event.id, implicit: true, body: event.data });\n } catch (err) {\n if (err instanceof CrashSignal) status = \"crashed\";\n else throw err;\n }\n }\n\n if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = \"crashed\";\n\n const followUps: EventRef[] = [];\n if (state.decision !== \"ack\") {\n const next = redelivery(event, maxRetries, spec.bounds);\n if (next) {\n followUps.push(next);\n } else {\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target: queueTarget,\n op: \"dead_letter\",\n args: { messageId: event.id, attempts: event.attempt },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n }\n return { status, followUps };\n}\n","/**\n * Inbound RPC delivery: one invocation per attempt of a `WorkerEntrypoint`\n * method call the drive's caller makes. The entrypoint is constructed anew\n * for each call, as the runtime does (Cloudflare, Workers RPC: a new\n * instance of the class for every call), and its return value or the error\n * it threw is the response the caller sees.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n type JsonValue,\n type RunHooks,\n type ScenarioSpec,\n toJson,\n} from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport { startCaller } from \"./caller.ts\";\nimport { isPlainData } from \"./durable-objects.ts\";\nimport { constructEntrypoint } from \"./entrypoint.ts\";\nimport { type RpcCallSpec, type RpcDrive, rpcTarget } from \"./scenario.ts\";\n\n/**\n * An error as the caller sees it over RPC: a new error object with the\n * name and message (Cloudflare, RPC error handling), nothing of its class.\n */\nexport function describeError(error: unknown): string {\n if (error instanceof Error) return `${error.name}: ${error.message}`;\n return typeof error === \"string\" ? error : JSON.stringify(toJson(error));\n}\n\n/** One attempt of a call, under the caller's retry policy and deadline. */\nexport async function deliverCall(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: RpcDrive,\n invocation: string,\n cls: unknown,\n env: object,\n): Promise<DeliveryResult> {\n const call = event.data as unknown as RpcCallSpec;\n const target = rpcTarget(drive, call.method);\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n const args: JsonValue = { callId: event.id, method: call.method, args: call.args };\n const caller = startCaller(event, hooks, spec, drive, target, {\n callId: event.id,\n attempts: event.attempt,\n });\n\n const ran = await runInvocation(hooks, inv, () =>\n callMethod(cls, call, executionContext(background), env),\n );\n let status: DeliveryResult[\"status\"] = ran.status;\n let late = caller.isLate();\n let answer: { readonly ok: boolean } | null = null;\n if (ran.status === \"completed\") {\n // Data travels by copy; a stub, a function or a stream would let later calls bypass the run.\n if (!isPlainData(ran.value))\n hooks.unsupported(\n `Rpc ${call.method}: the result is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`,\n );\n const s = { ok: true, value: toJson(ran.value) };\n try {\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed: caller.responseFaults },\n () => s,\n (v) => v,\n );\n answer = s;\n } catch (err) {\n if (err instanceof CrashSignal) status = \"crashed\";\n else if (err instanceof InjectedEffectError) {\n // Answered, but after the caller's deadline: the handler carries on, the caller resends.\n answer = s;\n late = true;\n } else throw err;\n }\n } else if (ran.status === \"errored\") {\n // The exception reaches the caller as a new error with its name and message; the caller saw an answer.\n const s = { ok: false, error: describeError(ran.error) };\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed: [] },\n () => s,\n (v) => v,\n );\n answer = s;\n }\n\n caller.settle(answer !== null && !late && answer.ok, late);\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\n}\n\n/**\n * The class an RPC drive calls: the named export, or the Worker's default\n * export (the class passed as the handler, or `exports.default`). Not\n * necessarily a class: the platform reports what it found instead.\n */\nexport function entrypointClass(\n handler: unknown,\n exports: Readonly<Record<string, unknown>> | undefined,\n entrypoint: string | undefined,\n): unknown {\n if (entrypoint !== undefined) return exports?.[entrypoint];\n return typeof handler === \"function\" ? handler : exports?.[\"default\"];\n}\n\n/**\n * The method RPC exposes under a name: one the class or a superclass defines\n * on its prototype. An instance property, even a function, and Object's own\n * methods are not callable (workerd: \"The RPC receiver does not implement the\n * method\").\n */\nfunction rpcMethod(instance: object, name: string): ((...a: unknown[]) => unknown) | undefined {\n for (\n let proto = Object.getPrototypeOf(instance) as object | null;\n proto !== null && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto) as object | null\n ) {\n const own = Object.getOwnPropertyDescriptor(proto, name);\n if (!own) continue;\n return typeof own.value === \"function\" && name !== \"constructor\"\n ? (own.value as (...a: unknown[]) => unknown)\n : undefined;\n }\n return undefined;\n}\n\n/**\n * Construct the entrypoint for one call and invoke the method, as the\n * runtime does per call. The arguments are copied, as RPC copies them: a\n * method that mutates one changes neither the scenario nor a later attempt.\n */\nexport function callMethod(cls: unknown, call: RpcCallSpec, ctx: unknown, env: object): unknown {\n const instance = constructEntrypoint(cls, \"WorkerEntrypoint\", ctx, env);\n const method = rpcMethod(instance, call.method);\n if (!method)\n throw new TypeError(`The RPC receiver does not implement the method \"${call.method}\".`);\n return method.apply(instance, structuredClone(call.args) as unknown[]);\n}\n","/**\n * Cron Trigger delivery: one invocation of the Worker's `scheduled()` handler\n * per tick attempt, with `scheduledTime` the tick's virtual time and `cron`\n * the expression (Workers, Scheduled handler). Cloudflare documents\n * `noRetry()` but no retry count, so the drive declares how many times a\n * tick whose handler failed is re-run; `noRetry()` stops them.\n */\n\nimport {\n type DeliveryResult,\n decisionFaults,\n type EventRef,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport type { CronDrive } from \"./scenario.ts\";\n\n/** What a tick event carries: what the controller shows the handler. */\nexport interface TickData {\n readonly cron: string;\n readonly scheduledTime: number;\n}\n\n/** One attempt of a tick: the handler runs, and a failure is re-run as the drive declares unless it said noRetry(). */\nexport async function deliverTick(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: CronDrive,\n invocation: string,\n worker: RunningWorker,\n): Promise<DeliveryResult> {\n const tick = event.data as unknown as TickData;\n const target = `Cron:${drive.cron}`;\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n /** Rejections of waitUntil work: the first one is the invocation's status (Cloudflare, Scheduled handler). */\n const failures: unknown[] = [];\n const handler = worker.handler.scheduled;\n if (!handler) throw new Error(\"the Worker has no scheduled() handler\");\n let noRetry = false;\n const controller: ScheduledController = {\n scheduledTime: tick.scheduledTime,\n cron: tick.cron,\n // A decision the runtime honours, like a queue ack: a crash around it may lose or keep it.\n noRetry: () => {\n hooks.effectSync(\n { invocation, target, op: \"no_retry\", args: { tick: event.id }, allowed: decisionFaults },\n () => {\n noRetry = true;\n return null;\n },\n () => null,\n );\n },\n };\n let status: DeliveryResult[\"status\"] = (\n await runInvocation(hooks, inv, () =>\n handler.call(worker.handler, controller, worker.env, executionContext(background, failures)),\n )\n ).status;\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n if (status === \"completed\" && failures.length > 0) status = \"errored\";\n\n const followUps: EventRef[] = [];\n if (status !== \"completed\" && !noRetry) {\n // The re-run is the same tick: same scheduledTime, next attempt.\n const next = redelivery(event, drive.retries, spec.bounds);\n if (next) followUps.push(next);\n else\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target,\n op: \"gave_up\",\n args: { tick: event.id, attempts: event.attempt },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n return { status, followUps };\n}\n","/**\n * The Cloudflare platform: delivers queue messages to the Worker's `queue()`\n * handler and inbound requests to its `fetch()` handler, with proxied\n * bindings, and applies Queues' at-least-once semantics (explicit and\n * implicit ack, retry, redelivery up to max_retries, dead-lettering) as\n * documented by Cloudflare, and for requests the caller's retry policy\n * declared in the drive.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n invocationOf,\n type Platform,\n type RunHooks,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport type { RunningWorker } from \"./background.ts\";\nimport {\n type Binding,\n d1Binding,\n durableObjectBinding,\n ownedSetups,\n r2Binding,\n serviceBinding,\n workflowBinding,\n} from \"./bindings.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\nimport type { DurableObjectTestHelpers } from \"./durable-objects.ts\";\nimport { deliverRequest } from \"./http.ts\";\nimport { deliverMessage } from \"./queues.ts\";\nimport { deliverCall, entrypointClass } from \"./rpc.ts\";\nimport { type Drive, driveEvents, restrictDrive } from \"./scenario.ts\";\nimport { deliverTick } from \"./scheduled.ts\";\n\n/** The Worker's default export, as far as the platform drives it. */\nexport interface WorkerHandler {\n queue?(batch: MessageBatch<unknown>, env: unknown, ctx: ExecutionContext): void | Promise<void>;\n fetch?(request: Request, env: unknown, ctx: ExecutionContext): Response | Promise<Response>;\n scheduled?(\n controller: ScheduledController,\n env: unknown,\n ctx: ExecutionContext,\n ): void | Promise<void>;\n}\n\n/** A `WorkerEntrypoint` subclass: the Worker's default export when it exposes RPC methods. Its env is its own. */\nexport type WorkerEntrypointClass = abstract new (ctx: ExecutionContext, env: never) => object;\n\nexport interface CloudflarePlatformOptions {\n /** The bindings from `cloudflare:workers`. */\n readonly env: object;\n /**\n * The Worker's default export: the handler object, or the\n * `WorkerEntrypoint` class the `rpc` drive calls (its own `fetch()`\n * method is not driven by `http()` yet).\n */\n readonly handler: WorkerHandler | WorkerEntrypointClass;\n /** Schema SQL per D1 binding named in the scenario's setup. */\n readonly schemas: Readonly<Record<string, string>>;\n /** Cloudflare's default when the consumer does not set max_retries. */\n readonly maxRetries?: number;\n /**\n * The Cloudflare Vitest plugin's test helpers (`import * as helpers from\n * \"cloudflare:test\"`), needed for Durable Object bindings: Eutaxy resets,\n * seeds and snapshots the real objects through them.\n */\n readonly durableObjects?: DurableObjectTestHelpers;\n /**\n * The Worker module's exports (`import * as worker from \"./worker.ts\"`),\n * where the classes `workflow` setup steps name are found.\n */\n readonly exports?: Readonly<Record<string, unknown>>;\n}\n\nfunction isBindingLike(value: unknown): boolean {\n if (typeof value === \"function\") return true;\n if (typeof value !== \"object\" || value === null) return false;\n const proto = Object.getPrototypeOf(value) as object | null;\n const names = [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})];\n return names.some(\n (k) => k !== \"constructor\" && typeof (value as Record<string, unknown>)[k] === \"function\",\n );\n}\n\nconst assumptions: readonly string[] = [\n \"platform model: Cloudflare Queues at-least-once delivery; the first ack or retry decision per message wins; unacked messages are redelivered up to max_retries then dead-lettered\",\n \"D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect\",\n \"message.timestamp is the virtual clock's time at delivery\",\n \"only D1, Durable Object, R2, Workflow and scripted service bindings are proxied; touching any other binding makes the run UNSUPPORTED\",\n \"service bindings are scripted callees: the Worker behind a binding is never called; each RPC method call or fetch() through it is one effect answered from the scenario's service() setup, where crash_before and error mean the call never reached the callee, ambiguous that it acted and the answer was lost, and crash_after that the caller died after it (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/); Cloudflare does not retry such a call\",\n \"R2 buckets are Miniflare's real ones, emptied and seeded before each run and snapshotted after it; R2 is strongly consistent and the last writer wins (developers.cloudflare.com/r2/reference/consistency/); each put, delete, get, head and list is one effect, a body is read inside its get, and an object's version and upload time are stand-ins so traces repeat; multipart uploads and conditions on the upload time are not modelled\",\n \"Durable Objects are the real objects workerd runs (storage, transactions, input and output gates are the runtime's own); each stub call is one effect: crash_before or error means it never reached the object, ambiguous means the object committed and the caller lost the answer, crash_after means the caller died after it; in a concurrent run an object's own outbound I/O during a call is a turn, so another event may enter the object meanwhile (its input gate is open then), except while it holds the gate with blockConcurrencyWhile, when its effects run at once; storage operations are not turns (the input gate holds other events during them); the object's own binding calls are not recorded; objects are cleared, seeded and evicted before each run and their storage is snapshotted after it (developers.cloudflare.com/durable-objects/api/storage-api/)\",\n \"Durable Object alarms are taken over so none is scheduled on the real clock and fire in virtual time: one alarm per object, a later setAlarm replaces it, setAlarm in a transaction applies on commit, the alarm survives eviction, alarm() is one effect (crash_before: it never ran; crash_after: it ran and counts as failed; error: it threw), and a failed alarm is retried after 2 s, 4 s, 8 s ... up to six retries and maxRedeliveries, with retryCount and isRetry (developers.cloudflare.com/durable-objects/api/base/#alarm); each object's alarm fires at most alarmsPerObject times per run (default 3)\",\n \"Workflows are a model of the engine, never the local one, running the scenario's own class: create is one effect that queues the instance; each step.do attempt is two effect points around its callback, which runs as the instance's own code (step, crash_before: the engine restarts before it; step_result, crash_after: it ran and committed but its result was not persisted, so it runs again; ambiguous: the attempt ran but counted as failed, as a timeout does); a failed attempt is retried after its delay in virtual time (defaults 5 retries, 10 s, exponential, merged field by field with a step's config), up to its limit and maxRedeliveries, except a NonRetryableError; a restart re-runs run() from the start with the persisted step and sleep results, so code outside steps repeats; step timeouts are not measured (developers.cloudflare.com/workflows/build/rules-of-workflows/, /workflows/build/sleeping-and-retrying/)\",\n \"state invariants read a snapshot of every D1 binding named in setup, taken after the last event\",\n \"work passed to ctx.waitUntil runs after the handler returns and never affects acknowledgement or the response; a cut_off fault at that point loses work not yet started, and an effect in flight commits without its continuation\",\n \"concurrent invocations (maxConcurrentInvocations above 1) share one isolate's module state and bindings, and another may run while one awaits I/O (developers.cloudflare.com/workers/reference/how-workers-works/); queue consumers run concurrently up to max_concurrency (developers.cloudflare.com/queues/configuration/consumer-concurrency/)\",\n \"inbound requests: one invocation per attempt; an uncaught exception is a 500 response; the drive's caller resends a request it got no acceptable response for (crash before the response, an answer after its deadlineMs, or a status its retryOn policy rejects) up to its retries, each resend after its delaysMs entry of virtual time; the handler's own time is virtual, so a late answer is the ambiguous fault at the response point or an answer later than deadlineMs in virtual time\",\n \"cron triggers: each tick of the drive's expression is one invocation of scheduled(), with scheduledTime the tick's virtual time (UTC, the expression's matches from the virtual epoch on, in Cloudflare's dialect where weekdays run 1 = Sunday to 7 = Saturday; L, W and # are not modelled) and cron the expression (developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/, /workers/configuration/cron-triggers/); Cloudflare documents noRetry() but no retry count, so the drive declares how many times a tick whose handler failed is re-run, and none after noRetry()\",\n \"inbound RPC: one invocation per call attempt, the entrypoint constructed anew for each with a fresh ExecutionContext (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/); the return value is the response effect, and an exception reaches the caller as a new error with its name and message (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); Cloudflare does not retry a call, so the drive's caller resends a call that threw or got no answer as the http drive's caller does; a result that is not plain data (a stub, a function, a stream) makes the run UNSUPPORTED\",\n];\n\nexport function createCloudflarePlatform(options: CloudflarePlatformOptions): Platform {\n const env = options.env as Record<string, unknown>;\n const maxRetries = options.maxRetries ?? 3;\n let hooksRef: RunHooks | null = null;\n\n const ctx: ProxyContext = {\n get hooks() {\n if (!hooksRef) throw new Error(\"no run in progress\");\n return hooksRef;\n },\n // Bindings are shared by every invocation in flight; the engine knows which one is running.\n currentInvocation: () => ctx.hooks.running(),\n };\n\n /**\n * The kinds of binding modelled, in the order an env value is tried against\n * them: a service binding first, since in workerd it answers every duck\n * type (its property reads are RPC stubs).\n */\n const bindings: readonly Binding[] = [\n serviceBinding(),\n d1Binding(options.schemas),\n durableObjectBinding({ ctx, helpers: options.durableObjects, real: (name) => env[name] }),\n r2Binding(),\n workflowBinding({ exports: options.exports, env: () => proxiedEnv }),\n ];\n const proxiedEnv = new Proxy(env, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown;\n if (typeof prop !== \"string\") return value;\n for (const binding of bindings) if (binding.is(value)) return binding.proxy(prop, value, ctx);\n if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);\n return value;\n },\n });\n // An entrypoint class exposes RPC methods; the queue and http drives need the handler object.\n const handler: WorkerHandler = typeof options.handler === \"function\" ? {} : options.handler;\n const worker: RunningWorker = { handler, env: proxiedEnv };\n\n return {\n name: \"cloudflare\",\n assumptions,\n concurrent: true,\n\n async reset(spec: ScenarioSpec): Promise<void> {\n for (const binding of bindings) binding.clear();\n for (const [binding, setup] of ownedSetups(spec.setup, bindings))\n await binding.reset(setup, env[setup.binding]);\n },\n\n restrictEvents(spec: ScenarioSpec, keepIds: readonly string[]): ScenarioSpec {\n return { ...spec, drive: restrictDrive(spec.drive as Drive, keepIds) };\n },\n\n async finish(spec: ScenarioSpec, hooks: RunHooks): Promise<void> {\n for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {\n const tables = await binding.snapshot(setup, env[setup.binding], (reason) =>\n hooks.unsupported(reason),\n );\n if (tables)\n hooks.snapshot(hooks.bookkeeping(), `${binding.target}:${setup.binding}`, { tables });\n }\n },\n\n initialEvents(spec: ScenarioSpec): readonly EventRef[] {\n return driveEvents(spec.drive as Drive);\n },\n\n async deliver(event: EventRef, hooks: RunHooks, spec: ScenarioSpec): Promise<DeliveryResult> {\n const drive = spec.drive as Drive;\n const invocation = invocationOf(event);\n hooksRef = hooks;\n // An event of a binding's own (an alarm, a Workflow run) is the binding's to deliver.\n const owner =\n event.source === undefined ? undefined : bindings.find((b) => b.source === event.source);\n if (owner?.deliver) return owner.deliver(event, hooks, spec);\n switch (drive.kind) {\n case \"http\":\n return deliverRequest(event, hooks, spec, drive, invocation, worker);\n case \"cron\":\n return deliverTick(event, hooks, spec, drive, invocation, worker);\n case \"rpc\": {\n const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);\n if (typeof cls !== \"function\") {\n hooks.unsupported(\n `Rpc: ${drive.entrypoint === undefined ? \"the Worker's default export\" : `export ${drive.entrypoint}`} is not a WorkerEntrypoint class; pass the Worker module's exports as createCloudflarePlatform({ ..., exports })`,\n );\n return { status: \"errored\", followUps: [] };\n }\n return deliverCall(event, hooks, spec, drive, invocation, cls, proxiedEnv);\n }\n default:\n return deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries);\n }\n },\n };\n}\n","/**\n * Differential check: the same fault-free scenario run once through Eutaxy's\n * proxies and once against the raw bindings, with the queue model (or the\n * HTTP caller's retry policy) applied on the raw side itself. Any difference in the per-attempt decisions or in\n * the final D1 and R2 state is a bug in the proxies or the platform model, not in\n * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue\n * semantics (core's redelivery rule among it); what it does not share is any proxy code.\n */\n\nimport {\n type EventRef,\n getPath,\n invocationOf,\n type JsonValue,\n redelivery,\n type ScenarioSpec,\n toJson,\n} from \"@eutaxy/core\";\nimport {\n CrashSignal,\n compareSides,\n DifferentialStuck,\n effectLatencyMs,\n installScriptedFetch,\n patchGlobals,\n proxiedSide,\n settleOn,\n type VirtualClock,\n} from \"@eutaxy/engine\";\nimport { executionContext } from \"./background.ts\";\nimport { type Binding, d1Binding, ownedSetups, r2Binding } from \"./bindings.ts\";\nimport { isD1 } from \"./d1.ts\";\nimport { requestFor } from \"./http.ts\";\nimport { type CloudflarePlatformOptions, createCloudflarePlatform } from \"./platform.ts\";\nimport { isR2 } from \"./r2.ts\";\nimport { callMethod, describeError, entrypointClass } from \"./rpc.ts\";\nimport { type Drive, driveEvents, type HttpRequestSpec, type RpcCallSpec } from \"./scenario.ts\";\nimport type { TickData } from \"./scheduled.ts\";\n\n/** A type, not an interface, so it is JSON data the comparison takes as it is. */\nexport type AttemptRecord = {\n readonly event: string;\n readonly attempt: number;\n readonly status: \"completed\" | \"errored\";\n /** Queue drive: the acknowledgement that took effect. Cron drive: `no_retry` when the handler asked for none. */\n readonly decision: \"ack\" | \"retry\" | \"no_retry\" | null;\n /** HTTP drive: the response status the caller saw (500 for an uncaught exception). */\n readonly response?: number;\n /** RPC drive: the answer the caller saw, `{ ok: true, value }` or `{ ok: false, error }`. */\n readonly result?: JsonValue;\n};\n\nexport interface Side {\n readonly attempts: readonly AttemptRecord[];\n readonly state: {\n readonly [binding: string]: { readonly [table: string]: readonly JsonValue[] };\n };\n}\n\nexport interface DifferentialResult {\n /** True only when both sides agree and the proxied run touched nothing unmodelled. */\n readonly equal: boolean;\n readonly eutaxy: Side;\n readonly raw: Side;\n readonly differences: readonly string[];\n /** What the proxied run could not control; non-empty means the comparison proves nothing. */\n readonly unsupported: readonly string[];\n}\n\n/**\n * The raw side's only wrapper: counts D1 calls in flight (so the settle loop\n * knows real I/O is pending) and advances the clock as the proxies do. It\n * records nothing and injects nothing.\n */\nfunction countingD1(real: D1Database, io: { n: number }, clock: VirtualClock): D1Database {\n const realOf = new WeakMap<object, D1PreparedStatement>();\n const track = async <T>(p: Promise<T>): Promise<T> => {\n io.n++;\n try {\n return await p;\n } finally {\n io.n--;\n clock.advance(effectLatencyMs);\n }\n };\n const wrapStatement = (s: D1PreparedStatement): D1PreparedStatement => {\n const proxy = new Proxy(s, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (prop === \"bind\") return (...a: unknown[]) => wrapStatement(t.bind(...a));\n if (prop === \"run\" || prop === \"all\" || prop === \"first\" || prop === \"raw\") {\n return (...a: unknown[]) =>\n track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a));\n }\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n realOf.set(proxy, s);\n return proxy;\n };\n return new Proxy(real, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (prop === \"prepare\") return (sql: string) => wrapStatement(t.prepare(sql));\n if (prop === \"batch\") {\n return (stmts: D1PreparedStatement[]) =>\n track(t.batch(stmts.map((s) => realOf.get(s) ?? s)));\n }\n if (prop === \"exec\") return (sql: string) => track(t.exec(sql));\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n}\n\n/**\n * The same for an R2 bucket: each call advances the clock as its proxied\n * effect does, and reading a body it gave counts as I/O in flight but does\n * not advance the clock (the proxy reads it inside the get). Reads through\n * the body's own stream are not counted: wrapping it would lose the known\n * length a copy's put needs, and Miniflare answers them within the settle\n * loop's real tick (checked with an 8 MB body).\n */\nfunction countingR2(real: R2Bucket, io: { n: number }, clock: VirtualClock): R2Bucket {\n const track = async <T>(p: Promise<T>, advance: boolean): Promise<T> => {\n io.n++;\n try {\n return await p;\n } finally {\n io.n--;\n if (advance) clock.advance(effectLatencyMs);\n }\n };\n const reads = [\"arrayBuffer\", \"bytes\", \"text\", \"json\", \"blob\"];\n const counted = (o: unknown): unknown => {\n if (o === null || typeof o !== \"object\" || !(\"body\" in o)) return o;\n return new Proxy(o, {\n get(t, prop) {\n // The object's own getters (body, etag) need the object itself as receiver.\n const v = Reflect.get(t, prop) as unknown;\n if (typeof prop === \"string\" && reads.includes(prop) && typeof v === \"function\")\n return (...a: unknown[]) =>\n track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a), false);\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n };\n return new Proxy(real, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (\n prop === \"put\" ||\n prop === \"delete\" ||\n prop === \"get\" ||\n prop === \"head\" ||\n prop === \"list\"\n )\n return async (...a: unknown[]) =>\n counted(await track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a), true));\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n}\n\n/**\n * The bindings whose state the two sides compare: those a store holds and\n * the real binding resets and reads back (D1, R2). Durable Objects and\n * Workflows have no raw side.\n */\nfunction storedBindings(options: CloudflarePlatformOptions): readonly Binding[] {\n return [d1Binding(options.schemas), r2Binding()];\n}\n\nasync function snapshotAll(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n): Promise<Side[\"state\"]> {\n const env = options.env as Record<string, unknown>;\n const out: Record<string, { readonly [table: string]: readonly JsonValue[] }> = {};\n for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) {\n // A D1 or R2 snapshot reports nothing; if one ever did, the comparison could not stand.\n const tables = await binding.snapshot(setup, env[setup.binding], (reason) => {\n throw new Error(`snapshot of ${setup.binding}: ${reason}`);\n });\n if (tables) out[setup.binding] = tables;\n }\n return out;\n}\n\n/** The Eutaxy side, keeping each delivery's status and the decision it made. */\nasync function eutaxySide(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n): Promise<Side & { readonly unsupported: readonly string[] }> {\n const { attempts, unsupported } = await proxiedSide(\n spec,\n createCloudflarePlatform(options),\n (event, result, entries): AttemptRecord => {\n const invocation = invocationOf(event);\n const mine = entries.filter((e) => e.invocation === invocation);\n const decision = mine.some((e) => e.kind === \"result\" && e.op === \"no_retry\")\n ? \"no_retry\"\n : (mine.find(\n (e) =>\n e.kind === \"result\" &&\n (e.op === \"ack\" || e.op === \"retry\") &&\n getPath(e.payload, \"result.effective\") === true,\n )?.op as \"ack\" | \"retry\" | undefined);\n const response = mine.find((e) => e.kind === \"result\" && e.op === \"response\");\n const answer = (): Partial<AttemptRecord> => {\n if (!response) return {};\n if (spec.drive.kind === \"rpc\")\n return { result: getPath(response.payload, \"result\") ?? null };\n return { response: getPath(response.payload, \"result.status\") as number };\n };\n return {\n event: event.id,\n attempt: event.attempt,\n status: result.status === \"completed\" ? \"completed\" : \"errored\",\n decision: decision ?? null,\n ...answer(),\n };\n },\n );\n return { attempts, state: await snapshotAll(spec, options), unsupported };\n}\n\n/** Each binding's tables under `<binding>.<table>`, as the comparison names them. */\nfunction flatten(state: Side[\"state\"]): { readonly [name: string]: readonly JsonValue[] } {\n const out: Record<string, readonly JsonValue[]> = {};\n for (const [binding, tables] of Object.entries(state))\n for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;\n return out;\n}\n\n/** The next event as the engine picks it: the earliest due, the first inserted among equals. */\nfunction takeEarliest(pending: EventRef[]): EventRef {\n let best = 0;\n for (let i = 1; i < pending.length; i++)\n if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;\n return pending.splice(best, 1)[0] as EventRef;\n}\n\n/** The raw side: the handler called directly with the real bindings and plain message or Request objects. */\nasync function rawSide(spec: ScenarioSpec, options: CloudflarePlatformOptions): Promise<Side> {\n const env = options.env as Record<string, unknown>;\n const drive = spec.drive as Drive;\n const maxRetries = options.maxRetries ?? 3;\n // The same resets as the proxied side's, which ran first on the same env and so already holds.\n for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options)))\n await binding.reset(setup, env[setup.binding]);\n const attempts: AttemptRecord[] = [];\n const pending: EventRef[] = [...driveEvents(drive)];\n // The same virtual globals as the proxied side, from the same seed, so Date.now and randomness agree,\n // and the same scripted externals, without recording.\n const patched = patchGlobals(0);\n const unsupported: string[] = [];\n const restoreFetch = installScriptedFetch(\n spec.externals,\n null,\n (r) => unsupported.push(r),\n () => patched.clock.advance(effectLatencyMs), // the proxied side advances per effect; match it\n );\n const io = { n: 0 };\n const counting = new Map<string, D1Database | R2Bucket>();\n const countedEnv = new Proxy(env, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown;\n if (typeof prop !== \"string\" || !(isD1(value) || isR2(value))) return value;\n let c = counting.get(prop);\n if (!c) {\n c = isD1(value)\n ? countingD1(value, io, patched.clock)\n : countingR2(value, io, patched.clock);\n counting.set(prop, c);\n }\n return c;\n },\n });\n const settle = <T>(p: Promise<T>): Promise<T> =>\n settleOn(p, {\n clock: patched.clock,\n inFlight: () => io.n,\n crashed: () => false,\n stuck: () => {\n throw new DifferentialStuck();\n },\n });\n try {\n // The queue and http drives need the handler object; an entrypoint class has neither handler.\n const handlers = typeof options.handler === \"function\" ? {} : options.handler;\n if (drive.kind === \"rpc\") {\n const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);\n if (typeof cls !== \"function\") throw new Error(\"the Worker has no WorkerEntrypoint class\");\n while (pending.length > 0) {\n const event = takeEarliest(pending);\n const call = event.data as unknown as RpcCallSpec;\n const background: Promise<unknown>[] = [];\n let status: \"completed\" | \"errored\";\n let result: JsonValue;\n try {\n const value = await settle(\n Promise.resolve().then(() =>\n callMethod(cls, call, executionContext(background), countedEnv),\n ),\n );\n result = { ok: true, value: toJson(value) };\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n result = { ok: false, error: describeError(err) };\n status = \"errored\";\n }\n await settle(Promise.all(background));\n attempts.push({ event: event.id, attempt: event.attempt, status, decision: null, result });\n const next = status === \"completed\" ? null : redelivery(event, drive.retries, spec.bounds);\n if (next) pending.push(next);\n }\n } else if (drive.kind === \"cron\") {\n const handler = handlers.scheduled;\n if (!handler) throw new Error(\"the Worker has no scheduled() handler\");\n while (pending.length > 0) {\n const event = takeEarliest(pending);\n const tick = event.data as unknown as TickData;\n // The proxied side's clock moved to the tick; so does this one.\n if (event.at !== undefined && event.at > patched.clock.now())\n patched.clock.advance(event.at - patched.clock.now());\n const background: Promise<unknown>[] = [];\n const failures: unknown[] = [];\n let noRetry = false;\n const controller: ScheduledController = {\n scheduledTime: tick.scheduledTime,\n cron: tick.cron,\n noRetry: () => {\n noRetry = true;\n },\n };\n let status: \"completed\" | \"errored\";\n try {\n await settle(\n Promise.resolve().then(() =>\n handler.call(\n handlers,\n controller,\n countedEnv,\n executionContext(background, failures),\n ),\n ),\n );\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n status = \"errored\";\n }\n await settle(Promise.all(background));\n // A failed waitUntil is the invocation's status, as for the proxied side.\n if (status === \"completed\" && failures.length > 0) status = \"errored\";\n attempts.push({\n event: event.id,\n attempt: event.attempt,\n status,\n decision: noRetry ? \"no_retry\" : null,\n });\n const next =\n status === \"completed\" || noRetry ? null : redelivery(event, drive.retries, spec.bounds);\n if (next) pending.push(next);\n }\n } else if (drive.kind === \"http\") {\n const handler = handlers.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n while (pending.length > 0) {\n const event = takeEarliest(pending);\n const req = event.data as unknown as HttpRequestSpec;\n const background: Promise<unknown>[] = [];\n let status: \"completed\" | \"errored\";\n let response = 500;\n try {\n const r = await settle(\n Promise.resolve().then(() =>\n handler.call(handlers, requestFor(req), countedEnv, executionContext(background)),\n ),\n );\n await settle(r.clone().text());\n response = r.status;\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n status = \"errored\";\n }\n await settle(Promise.all(background));\n attempts.push({\n event: event.id,\n attempt: event.attempt,\n status,\n decision: null,\n response,\n });\n const accepted =\n drive.retryOn === \"5xx\" ? response < 500 : response >= 200 && response < 300;\n const next = accepted ? null : redelivery(event, drive.retries, spec.bounds);\n if (next) pending.push(next);\n }\n } else {\n const handler = handlers.queue;\n if (!handler) throw new Error(\"the Worker has no queue() handler\");\n while (pending.length > 0) {\n const event = takeEarliest(pending);\n let decision: \"ack\" | \"retry\" | null = null;\n const background: Promise<unknown>[] = [];\n const message: Message<unknown> = {\n id: event.id,\n timestamp: new Date(),\n body: JSON.parse(JSON.stringify(event.data)) as JsonValue,\n attempts: event.attempt,\n ack: () => {\n decision ??= \"ack\";\n },\n retry: () => {\n decision ??= \"retry\";\n },\n };\n const batch: MessageBatch<unknown> = {\n queue: drive.queue,\n messages: [message],\n metadata: { metrics: { backlogCount: 0, backlogBytes: 0 } },\n ackAll: () => message.ack(),\n retryAll: () => message.retry(),\n };\n const ctx = executionContext(background);\n let status: \"completed\" | \"errored\";\n try {\n await settle(\n Promise.resolve().then(() => handler.call(handlers, batch, countedEnv, ctx)),\n );\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n status = \"errored\";\n }\n if (status === \"completed\") decision ??= \"ack\";\n await settle(Promise.all(background));\n attempts.push({ event: event.id, attempt: event.attempt, status, decision });\n const next = decision === \"ack\" ? null : redelivery(event, maxRetries, spec.bounds);\n if (next) pending.push(next);\n }\n }\n } finally {\n restoreFetch();\n patched.restore();\n }\n if (unsupported.length > 0) throw new DifferentialStuck(`raw side: ${unsupported.join(\"; \")}`);\n return { attempts, state: await snapshotAll(spec, options) };\n}\n\n/** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */\nexport async function runDifferential(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n): Promise<DifferentialResult> {\n if (\n (spec.drive.kind === \"http\" || spec.drive.kind === \"rpc\") &&\n (\"delaysMs\" in spec.drive || \"deadlineMs\" in spec.drive)\n ) {\n throw new Error(\"runDifferential does not model the caller's delaysMs or deadlineMs yet\");\n }\n const { unsupported, ...eutaxy } = await eutaxySide(spec, options);\n const raw = await rawSide(spec, options);\n const differences = compareSides(\n { attempts: eutaxy.attempts, state: flatten(eutaxy.state) },\n { attempts: raw.attempts, state: flatten(raw.state) },\n unsupported,\n );\n return { equal: differences.length === 0, eutaxy, raw, differences, unsupported };\n}\n","/**\n * The half of `eutaxy check` that runs inside workerd: the generated test\n * passes its module globs here and stores what this returns in its task\n * meta, which the CLI reads back. It imports nothing that needs Node, so\n * the Cloudflare Vitest plugin can load it.\n */\n\nimport {\n check,\n createCloudflarePlatform,\n type DurableObjectTestHelpers,\n type WorkerHandler,\n} from \"@eutaxy/cloudflare\";\nimport type { ScenarioSpec, SpecVerdict } from \"@eutaxy/core\";\nimport { observeCore } from \"@eutaxy/engine\";\nimport { checkSpecModule } from \"@eutaxy/prover\";\nimport { renderJson } from \"@eutaxy/report\";\nimport type { ModuleSpecs } from \"@eutaxy/spec\";\nimport { globKey, specKey } from \"./keys.ts\";\n\n/** What the generated test stores in its task meta. */\nexport interface CheckTransport {\n readonly report: unknown;\n /** Set instead of a report when a module the scenario's `specs` names has no usable spec file. */\n readonly specErrors?: readonly SpecError[];\n readonly worker: { readonly entry: string; readonly config: string };\n readonly setup: readonly { readonly kind: string; readonly [key: string]: unknown }[];\n /** The scenario's drive, for what the regression test must pass the platform (a named entrypoint). */\n readonly drive?: { readonly kind: string; readonly [key: string]: unknown };\n /** The core modules observed (as the scenario's specs name them) and the functions on each. */\n readonly observed?: readonly { readonly module: string; readonly functions: readonly string[] }[];\n}\n\nexport interface SpecError {\n readonly module: string;\n readonly line: number;\n readonly message: string;\n}\n\n/** A generated spec entry: the module's specs, read on the Node side, and a loader of its spec file. */\nexport interface SpecEntry {\n readonly specs: ModuleSpecs;\n readonly load: () => Promise<object>;\n}\n\n/** Vite globs, keyed as `import.meta.glob` keys them from `.eutaxy/` (see `globKey`). */\nexport type ModuleGlob = Readonly<Record<string, () => Promise<unknown>>>;\n\n/** Each D1 binding's schema, read from the `.sql` files next to the scenario. */\nexport function schemasFor(\n scenario: ScenarioSpec,\n sqlFiles: Readonly<Record<string, string>>,\n): Record<string, string> {\n const schemas: Record<string, string> = {};\n for (const step of scenario.setup) {\n if (step.kind !== \"d1\") continue;\n const file = String(step[\"schemaFile\"]);\n const sql = sqlFiles[globKey(file)];\n if (sql === undefined) throw new Error(`schema file ${file} not found next to the scenario`);\n schemas[String(step[\"binding\"])] = sql;\n }\n return schemas;\n}\n\nexport interface SelectedModule {\n /** As the scenario names it. */\n readonly path: string;\n readonly key: string;\n readonly namespace: object;\n readonly specs: ModuleSpecs;\n /** The spec file's namespace: its exports are the specs. */\n readonly props: Readonly<Record<string, unknown>>;\n /** The functions observed: the ones with specs, and the decisions `refines` names that the module exports. */\n readonly names: readonly string[];\n}\n\n/**\n * The modules the scenario's `specs` name, loaded with their specs and\n * their spec files, and every reason the check cannot go ahead: a module\n * that is not there, a spec that does not read, a function name observed\n * in two modules (decisions are logged by name, so it would be ambiguous).\n * The spec files are loaded here, before anything is observed, so the\n * functions their specs hold are the modules' own.\n */\nexport async function selectSpecModules(\n scenario: ScenarioSpec,\n modules: ModuleGlob,\n specEntries: Readonly<Record<string, SpecEntry>>,\n): Promise<{\n readonly selected: readonly SelectedModule[];\n readonly specErrors: readonly SpecError[];\n}> {\n const decisions = scenario.invariants.flatMap((i) => (i.kind === \"refines\" ? [i.decision] : []));\n const specErrors: SpecError[] = [];\n const selected: SelectedModule[] = [];\n for (const path of scenario.specs ?? []) {\n const load = modules[globKey(path)];\n if (!load) {\n specErrors.push({ module: path, line: 0, message: \"no such module next to the scenario\" });\n continue;\n }\n const namespace = (await load()) as Record<string, unknown>;\n const key = specKey(path);\n const entry = Object.hasOwn(specEntries, key) ? specEntries[key] : undefined;\n const specs: ModuleSpecs = entry?.specs ?? { functions: [], errors: [] };\n for (const e of specs.errors)\n specErrors.push({\n module: e.inModule ? path : `${path.replace(/\\.ts$/, \"\")}.props.ts`,\n line: e.line,\n message: e.message,\n });\n const props = entry ? ((await entry.load()) as Record<string, unknown>) : {};\n const exported = decisions.filter((d) => typeof namespace[d] === \"function\");\n const names = [...new Set([...specs.functions.map((f) => f.name), ...exported])];\n selected.push({ path, key, namespace, specs, props, names });\n }\n const observedIn = new Map<string, string>();\n for (const m of selected)\n for (const n of m.names) {\n const other = observedIn.get(n);\n if (other === undefined) observedIn.set(n, m.path);\n else\n specErrors.push({\n module: m.path,\n line: 0,\n message: `${n} is observed in both ${other} and ${m.path}; decisions of one name must come from one module`,\n });\n }\n return { selected, specErrors };\n}\n\nexport interface WorkerdCheckInput {\n /** The scenario module's default export. */\n readonly scenario: ScenarioSpec;\n /** `env` from `cloudflare:workers`. */\n readonly env: object;\n /** The `cloudflare:test` module, for Durable Objects. */\n readonly durableObjects: DurableObjectTestHelpers;\n /** The raw text of the `.sql` files next to the scenario. */\n readonly sqlFiles: Readonly<Record<string, string>>;\n /** The TypeScript modules next to the scenario (the Worker and the spec modules among them). */\n readonly modules: ModuleGlob;\n /** The generated `specs.ts` entries, by module key. */\n readonly specEntries: Readonly<Record<string, SpecEntry>>;\n readonly seed: string;\n readonly maxRuns?: number;\n readonly budgetMs?: number;\n readonly exhaustive?: boolean;\n}\n\n/** Run the scenario's check, with its specs observed, and return what the CLI reads back. */\nexport async function checkInWorkerd(input: WorkerdCheckInput): Promise<CheckTransport> {\n const { scenario } = input;\n const schemas = schemasFor(scenario, input.sqlFiles);\n const load = input.modules[globKey(scenario.worker.entry)];\n if (!load)\n throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);\n const worker = (await load()) as { default: WorkerHandler } & Record<string, unknown>;\n const platform = createCloudflarePlatform({\n env: input.env,\n handler: worker.default,\n schemas,\n durableObjects: input.durableObjects,\n exports: worker,\n });\n const { selected, specErrors } = await selectSpecModules(\n scenario,\n input.modules,\n input.specEntries,\n );\n const transportBase = { worker: scenario.worker, setup: scenario.setup, drive: scenario.drive };\n if (specErrors.length > 0) return { report: null, specErrors, ...transportBase };\n const observers = selected.map((m) => observeCore(m.namespace, m.names));\n let verdict: Awaited<ReturnType<typeof check>>;\n try {\n verdict = await check(scenario, platform, {\n seed: input.seed,\n ...(input.maxRuns === undefined ? {} : { maxRuns: input.maxRuns }),\n ...(input.budgetMs === undefined ? {} : { budgetMs: input.budgetMs }),\n ...(input.exhaustive ? { exhaustive: true } : {}),\n });\n } finally {\n for (const o of observers) o.restore();\n }\n // CHECKED on the calls the exploration recorded, then TESTED on inputs drawn from the check's seed.\n const specs: SpecVerdict[] = selected.flatMap((m, i) =>\n checkSpecModule(\n m.key,\n m.specs,\n m.props,\n m.namespace as Record<string, unknown>,\n observers[i] as ReturnType<typeof observeCore>,\n { tested: { seed: input.seed } },\n ),\n );\n return {\n report: JSON.parse(renderJson(verdict, specs)) as unknown,\n ...transportBase,\n observed: selected.map((m) => ({ module: m.path, functions: m.names })),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAOA,SAAgB,UAAU,MAAyB,WAA8B,CAAC,GAAe;CAC/F,MAAM,cAAwB,CAAC;CAC/B,MAAM,QAAuC,CAAC;CAC9C,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,IAAI,KAAK;EACf,IAAI,CAAC,EAAE,WAAW,IAAI,GAAG;GACvB,YAAY,KAAK,CAAC;GAClB;EACF;EACA,MAAM,KAAK,EAAE,QAAQ,GAAG;EACxB,IAAI,OAAO,IAAI;GACb,MAAM,EAAE,MAAM,GAAG,EAAE,KAAK,EAAE,MAAM,KAAK,CAAC;GACtC;EACF;EACA,MAAM,OAAO,EAAE,MAAM,CAAC;EACtB,MAAM,OAAO,KAAK,IAAI;EACtB,IAAI,SAAS,SAAS,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,WAAW,IAAI,GACvE,MAAM,QAAQ;OACT;GACL,MAAM,QAAQ;GACd;EACF;CACF;CACA,OAAO;EAAE;EAAa;CAAM;AAC9B;;;;;;;;;;;;ACNA,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