eutaxy 0.6.0 → 0.8.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.
Files changed (38) hide show
  1. package/README.md +55 -14
  2. package/dist/aws.d.mts +2 -2
  3. package/dist/bin.mjs +2 -2
  4. package/dist/cli-BT7zv5TL.mjs +2 -0
  5. package/dist/cli.d.mts.map +1 -1
  6. package/dist/cli.mjs +2 -2
  7. package/dist/cloudflare.d.mts +9 -9
  8. package/dist/cloudflare.d.mts.map +1 -1
  9. package/dist/cloudflare.mjs +1 -1
  10. package/dist/combinators-Bsd9HKtw.d.mts +42 -0
  11. package/dist/combinators-Bsd9HKtw.d.mts.map +1 -0
  12. package/dist/combinators-CVjxodAJ.mjs +27 -0
  13. package/dist/combinators-CVjxodAJ.mjs.map +1 -0
  14. package/dist/{delivery-invariants-BraYqcYN.d.mts → delivery-invariants-DfPkJL0Q.d.mts} +2 -2
  15. package/dist/{delivery-invariants-BraYqcYN.d.mts.map → delivery-invariants-DfPkJL0Q.d.mts.map} +1 -1
  16. package/dist/explore-Rwe1PPqX.d.mts +233 -0
  17. package/dist/explore-Rwe1PPqX.d.mts.map +1 -0
  18. package/dist/index.d.mts +141 -20
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +2 -61
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/{platform-DfMwknw1.d.mts → platform-Bpnav0kn.d.mts} +6 -4
  23. package/dist/{platform-DfMwknw1.d.mts.map → platform-Bpnav0kn.d.mts.map} +1 -1
  24. package/dist/spec.d.mts +2 -0
  25. package/dist/spec.mjs +1 -0
  26. package/dist/src-B9L96rZW.mjs +9521 -0
  27. package/dist/src-B9L96rZW.mjs.map +1 -0
  28. package/dist/src-BO7I3f-1.mjs.map +1 -1
  29. package/dist/src-BZtuuu_j.mjs +1706 -0
  30. package/dist/src-BZtuuu_j.mjs.map +1 -0
  31. package/package.json +12 -7
  32. package/dist/cli-CsiVEsS-.mjs +0 -2
  33. package/dist/explore-CDpJA9zX.d.mts +0 -342
  34. package/dist/explore-CDpJA9zX.d.mts.map +0 -1
  35. package/dist/src-C43iUZgr.mjs +0 -5039
  36. package/dist/src-C43iUZgr.mjs.map +0 -1
  37. package/dist/src-Cs4Mg55e.mjs +0 -2672
  38. package/dist/src-Cs4Mg55e.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-B9L96rZW.mjs","names":["isPunct","isWord","opens","closes","skipGroup","declarationStarts","splitTopLevel","unknown","skipGroup","join","ident","fail","env","term","emitFunction","binderType","arrowTerm","installHint","run","candidates","engineName","engineAssumptions","proven","unknown","prepare","proveModule","WRITE","READ","retryDelayMs","coreAtLeastOncePerMessage","retryDelayMs"],"sources":["../../cli/src/args.ts","../../prover/src/reader/tokens.ts","../../prover/src/reader/types.ts","../../prover/src/reader/specs.ts","../../prover/src/reader/subset.ts","../../prover-lean/src/emit.ts","../../prover-lean/src/lean.ts","../../prover-lean/src/supplied.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/report.ts","../../cli/src/main.ts","../../cloudflare/src/check.ts","../../cloudflare/src/d1.ts","../../cloudflare/src/background.ts","../../cloudflare/src/scenario.ts","../../cloudflare/src/http.ts","../../cloudflare/src/alarms.ts","../../cloudflare/src/durable-objects.ts","../../cloudflare/src/queues.ts","../../cloudflare/src/r2.ts","../../cloudflare/src/workflows.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 * A tokenizer shaped like TypeScript's scanner: glyphs inside string,\n * template and regex literals are text, never operators, a `/` is a\n * regular expression or a division by what precedes it, and a template\n * substitution nests. It reads the modules and spec files the readers\n * walk; nothing here knows what a token means.\n */\n\nexport type TokenKind = \"ident\" | \"number\" | \"string\" | \"template\" | \"regex\" | \"punct\" | \"comment\";\n\nexport interface Token {\n readonly kind: TokenKind;\n readonly text: string;\n /** Offsets into the scanned text: [start, end). */\n readonly start: number;\n readonly end: number;\n}\n\nconst punctuators = [\n \">>>=\",\n \"...\",\n \"===\",\n \"!==\",\n \"**=\",\n \"<<=\",\n \">>=\",\n \">>>\",\n \"&&=\",\n \"||=\",\n \"??=\",\n \"=>\",\n \"==\",\n \"!=\",\n \"<=\",\n \">=\",\n \"&&\",\n \"||\",\n \"??\",\n \"?.\",\n \"++\",\n \"--\",\n \"+=\",\n \"-=\",\n \"*=\",\n \"/=\",\n \"%=\",\n \"&=\",\n \"|=\",\n \"^=\",\n \"**\",\n \"<<\",\n \">>\",\n];\n\n/** Keywords after which a `/` starts a regular expression rather than a division. */\nconst regexAfter = new Set([\n \"in\",\n \"of\",\n \"typeof\",\n \"instanceof\",\n \"return\",\n \"new\",\n \"delete\",\n \"void\",\n \"case\",\n \"do\",\n \"else\",\n \"yield\",\n \"await\",\n]);\n\nconst identStart = /[\\p{ID_Start}$_]/u;\nconst identPart = /[\\p{ID_Continue}$‌‍]/u;\nconst numberAt =\n /^(?:0[xXoObB][0-9a-fA-F_]+n?|(?:\\d[\\d_]*(?:\\.[\\d_]*)?|\\.\\d[\\d_]*)(?:[eE][+-]?\\d[\\d_]*)?n?)/;\n\nexport class TokenizeError extends Error {}\n\n/** Keywords whose parenthesized condition is followed by a statement, not an operator. */\nconst controlKeywords = new Set([\"if\", \"while\", \"for\", \"with\"]);\n\n/**\n * Whether the code tokens up to `k` end an operand, so a `/` after them\n * divides. `conditions` holds the `)` that close a control statement's\n * condition (`if (x) /re/.test(s)`), after which a statement starts.\n */\nfunction endsOperand(\n tokens: readonly Token[],\n k: number,\n conditions: ReadonlySet<number>,\n blocks: ReadonlySet<number>,\n): boolean {\n while (k >= 0 && tokens[k]?.kind === \"comment\") k--;\n const t = tokens[k];\n if (!t) return false;\n switch (t.kind) {\n case \"ident\": {\n // After `.`, a word is a member name, whatever its spelling (`obj.in`).\n const before = tokens.slice(0, k).findLast((u) => u.kind !== \"comment\");\n if (before?.kind === \"punct\" && (before.text === \".\" || before.text === \"?.\")) return true;\n return !regexAfter.has(t.text);\n }\n case \"punct\":\n // After an operand, `!` (TypeScript's non-null assertion), `++` and `--` are postfix and end one too.\n if (t.text === \"!\" || t.text === \"++\" || t.text === \"--\")\n return endsOperand(tokens, k - 1, conditions, blocks);\n if (t.text === \")\") return !conditions.has(k);\n // A `}` closing a statement block ends no expression; one closing an object literal does.\n if (t.text === \"}\") return !blocks.has(k);\n return t.text === \"]\";\n default:\n return true;\n }\n}\n\n/** The end of a quoted string starting at `i`. */\nfunction endOfString(text: string, i: number): number {\n const quote = text[i];\n for (let j = i + 1; j < text.length; j++) {\n const c = text[j];\n if (c === \"\\\\\") j++;\n else if (c === quote) return j + 1;\n else if (c === \"\\n\") break;\n }\n throw new TokenizeError(`unterminated string at offset ${i}`);\n}\n\n/** The end of the template literal starting at `i`, substitutions included. */\nfunction endOfTemplate(text: string, i: number): number {\n for (let j = i + 1; j < text.length; j++) {\n const c = text[j];\n if (c === \"\\\\\") j++;\n else if (c === \"`\") return j + 1;\n else if (c === \"$\" && text[j + 1] === \"{\") j = endOfSubstitution(text, j + 2) - 1;\n }\n throw new TokenizeError(`unterminated template literal at offset ${i}`);\n}\n\n/** The offset just past the `}` that closes a substitution whose body starts at `i`, scanned as code. */\nfunction endOfSubstitution(text: string, i: number): number {\n return scan(text, i, { untilBrace: true }).end;\n}\n\n/** The source of each `${…}` substitution in a template literal's text, outermost only. */\nexport function templateSubstitutions(template: string): string[] {\n const out: string[] = [];\n for (let j = 1; j < template.length; j++) {\n const c = template[j];\n if (c === \"\\\\\") j++;\n else if (c === \"$\" && template[j + 1] === \"{\") {\n const end = endOfSubstitution(template, j + 2);\n out.push(template.slice(j + 2, end - 1));\n j = end - 1;\n }\n }\n return out;\n}\n\n/** The end of the regex literal starting at `i`, flags included. */\nfunction endOfRegex(text: string, i: number): number {\n let inClass = false;\n for (let j = i + 1; j < text.length; j++) {\n const c = text[j];\n if (c === \"\\\\\") j++;\n else if (c === \"\\n\") break;\n else if (inClass) {\n if (c === \"]\") inClass = false;\n } else if (c === \"[\") inClass = true;\n else if (c === \"/\") {\n let k = j + 1;\n while (k < text.length && identPart.test(text[k] as string)) k++;\n return k;\n }\n }\n throw new TokenizeError(`unterminated regular expression at offset ${i}`);\n}\n\n/** Tokens of `text`; comments are dropped unless `comments` is set (then they are \"comment\" tokens). */\nexport function tokenize(text: string, options: { readonly comments?: boolean } = {}): Token[] {\n return scan(text, 0, options).tokens;\n}\n\n/**\n * Scan from `start`. With `untilBrace`, stop after the `}` that closes an\n * enclosing substitution (one not opened in the scanned code) and return\n * the offset after it.\n */\nfunction scan(\n text: string,\n start: number,\n options: { readonly comments?: boolean; readonly untilBrace?: boolean },\n): { tokens: Token[]; end: number } {\n const tokens: Token[] = [];\n const push = (kind: TokenKind, start: number, end: number): void => {\n tokens.push({ kind, text: text.slice(start, end), start, end });\n };\n // Comments are always tracked here, so regex detection can skip them; they are dropped at the end if unwanted.\n let braces = 0;\n // Open parentheses (true for a control statement's condition), and the `)` that closed a condition.\n const parens: boolean[] = [];\n const conditions = new Set<number>();\n // Open braces (true for a statement block), and the `}` that closed a block.\n const curlies: boolean[] = [];\n const blocks = new Set<number>();\n let i = start;\n while (i < text.length) {\n const c = text[i] as string;\n if (/\\s/u.test(c)) {\n i++;\n continue;\n }\n if (c === \"/\" && text[i + 1] === \"/\") {\n // A line comment ends at any JavaScript line terminator, not only LF: code after a CR or a\n // U+2028/U+2029 is code.\n const from = i;\n while (i < text.length && !/[\\n\\r\\u2028\\u2029]/u.test(text[i] as string)) i++;\n push(\"comment\", from, i);\n continue;\n }\n if (c === \"/\" && text[i + 1] === \"*\") {\n const close = text.indexOf(\"*/\", i + 2);\n if (close < 0) throw new TokenizeError(`unterminated comment at offset ${i}`);\n push(\"comment\", i, close + 2);\n i = close + 2;\n continue;\n }\n if (c === \"/\") {\n if (!endsOperand(tokens, tokens.length - 1, conditions, blocks)) {\n const end = endOfRegex(text, i);\n push(\"regex\", i, end);\n i = end;\n continue;\n }\n }\n if (c === '\"' || c === \"'\") {\n const end = endOfString(text, i);\n push(\"string\", i, end);\n i = end;\n continue;\n }\n if (c === \"`\") {\n const end = endOfTemplate(text, i);\n push(\"template\", i, end);\n i = end;\n continue;\n }\n const num = numberAt.exec(text.slice(i));\n if (num && (/\\d/.test(c) || (c === \".\" && /\\d/.test(text[i + 1] ?? \"\")))) {\n push(\"number\", i, i + num[0].length);\n i += num[0].length;\n continue;\n }\n if (identStart.test(c)) {\n let j = i + 1;\n while (j < text.length && identPart.test(text[j] as string)) j++;\n push(\"ident\", i, j);\n i = j;\n continue;\n }\n const p = punctuators.find((s) => text.startsWith(s, i)) ?? c;\n if (p === \"(\") {\n const before = tokens.findLast((t) => t.kind !== \"comment\");\n parens.push(before?.kind === \"ident\" && controlKeywords.has(before.text));\n } else if (p === \")\" && parens.pop()) conditions.add(tokens.length);\n if (p === \"{\") {\n const before = tokens.findLast((t) => t.kind !== \"comment\");\n curlies.push(\n before === undefined ||\n (before.kind === \"punct\" && [\")\", \"{\", \"}\", \";\", \"=>\"].includes(before.text)) ||\n (before.kind === \"ident\" && [\"else\", \"do\", \"try\", \"finally\"].includes(before.text)),\n );\n } else if (p === \"}\" && curlies.pop()) blocks.add(tokens.length);\n if (p === \"{\") braces++;\n if (p === \"}\" && braces-- === 0 && options.untilBrace) {\n return { tokens: keep(tokens, options), end: i + 1 };\n }\n push(\"punct\", i, i + p.length);\n i += p.length;\n }\n if (options.untilBrace)\n throw new TokenizeError(`unterminated template substitution at offset ${start}`);\n return { tokens: keep(tokens, options), end: i };\n}\n\nfunction keep(tokens: Token[], options: { readonly comments?: boolean }): Token[] {\n return options.comments ? tokens : tokens.filter((t) => t.kind !== \"comment\");\n}\n","/**\n * TypeScript type syntax read into `SpecType`: the primitives, literals,\n * `null` and `undefined`, type literals and the module's own `interface`\n * and `type` declarations (type parameters substituted), unions of them,\n * and arrays (`T[]`, `readonly T[]`, `Array<T>`, `ReadonlyArray<T>`).\n * What the reader cannot read (tuples, intersections, imported types,\n * classes, methods, index signatures, optional fields, recursion) becomes\n * `unknown` with its text, never a guess: a binder of unknown type is still\n * checked on the inputs the simulator passed, only not drawn or proved.\n */\n\nimport type { Field, SpecType } from \"@eutaxy/spec\";\nimport type { Token } from \"./tokens.ts\";\n\n/** An `interface` or `type` declaration at the module's top level. */\nexport interface TypeDeclaration {\n readonly name: string;\n readonly params: readonly string[];\n /** The tokens of the type: the `{ … }` of an interface, the right-hand side of an alias. */\n readonly tokens: readonly Token[];\n /** Set when the declaration is one the reader does not read (`extends`, say). */\n readonly unsupported?: string;\n}\n\nconst isPunct = (t: Token | undefined, text: string): boolean =>\n t?.kind === \"punct\" && t.text === text;\nconst isWord = (t: Token | undefined, text: string): boolean =>\n t?.kind === \"ident\" && t.text === text;\n\nconst opens = new Set([\"(\", \"[\", \"{\"]);\nconst closes = new Set([\")\", \"]\", \"}\"]);\n\n/** The index just past the group opened at `i`. */\nfunction skipGroup(tokens: readonly Token[], i: number): number {\n let depth = 0;\n for (let j = i; j < tokens.length; j++) {\n const t = tokens[j] as Token;\n if (t.kind !== \"punct\") continue;\n if (opens.has(t.text)) depth++;\n else if (closes.has(t.text)) {\n depth--;\n if (depth === 0) return j + 1;\n }\n }\n return tokens.length;\n}\n\n/** The index just past the `>` closing the type arguments opened at `i`. */\nfunction skipAngles(tokens: readonly Token[], i: number): number {\n let depth = 0;\n for (let j = i; j < tokens.length; j++) {\n const t = tokens[j] as Token;\n if (t.kind !== \"punct\") continue;\n if (t.text === \"<\") depth++;\n else if (/^>+$/.test(t.text)) {\n depth -= t.text.length;\n if (depth <= 0) return j + 1;\n } else if (opens.has(t.text)) j = skipGroup(tokens, j) - 1;\n }\n return tokens.length;\n}\n\n/**\n * The tokens inside the list opened at `i` and closed before `end`. A\n * closing `>>` also closes lists inside this one: the inner ones keep\n * their `>`s, so `Array<Array<number>>` reads as it is written.\n */\nfunction anglesInner(tokens: readonly Token[], i: number, end: number): Token[] {\n const inner = tokens.slice(i + 1, end - 1);\n const close = tokens[end - 1];\n if (close?.kind === \"punct\" && /^>{2,}$/.test(close.text))\n // The first `>`s close the innermost lists; the last one closes this list.\n inner.push({ ...close, text: close.text.slice(1), end: close.end - 1 });\n return inner;\n}\n\n/** Type parameter names of the list opened at `i` (`<T, E extends X = Y>`), and the index past it. */\nfunction typeParams(tokens: readonly Token[], i: number): { names: string[]; end: number } {\n const names: string[] = [];\n const end = skipAngles(tokens, i);\n let expectName = true;\n let depth = 0;\n for (let j = i + 1; j < end - 1; j++) {\n const t = tokens[j] as Token;\n if (t.kind === \"punct\") {\n if (t.text === \"<\" || opens.has(t.text)) depth++;\n else if (/^>+$/.test(t.text) || closes.has(t.text)) depth--;\n else if (t.text === \",\" && depth === 0) expectName = true;\n continue;\n }\n if (expectName && depth === 0 && t.kind === \"ident\") names.push(t.text);\n expectName = false;\n }\n return { names, end };\n}\n\n/** Keywords after which an expression continues on the next line. */\nconst continuing = new Set(\n \"new extends typeof await yield void delete in of instanceof\".split(\" \"),\n);\n\nconst declarationStarts = new Set(\n \"export import function interface type const let var class enum declare async abstract namespace module\".split(\n \" \",\n ),\n);\n\n/**\n * The local names one `import` statement binds, from the token after\n * `import`: `{ a, type B, c as D }`, a default, `* as ns` and\n * `x = require(…)`. An import for its effects, `import(…)` and\n * `import.meta` bind none.\n */\nfunction importBindings(tokens: readonly Token[], from: number): string[] {\n const out: string[] = [];\n let j = from;\n if (isWord(tokens[j], \"type\") && !isPunct(tokens[j + 1], \",\") && !isWord(tokens[j + 1], \"from\"))\n j++;\n const first = tokens[j];\n if (!first || first.kind === \"string\" || isPunct(first, \"(\") || isPunct(first, \".\")) return out;\n for (; j < tokens.length; j++) {\n const t = tokens[j] as Token;\n if (isWord(t, \"from\") || t.kind === \"string\" || isPunct(t, \";\") || isPunct(t, \"=\")) break;\n if (isPunct(t, \"{\")) {\n const end = skipGroup(tokens, j);\n for (const spec of splitTopLevel(tokens.slice(j + 1, end - 1), \",\")) {\n const last = spec[spec.length - 1];\n if (last?.kind === \"ident\") out.push(last.text);\n }\n j = end - 1;\n } else if (t.kind === \"ident\" && t.text !== \"as\") out.push(t.text);\n }\n return out;\n}\n\n/**\n * The module's top-level type declarations. An alias runs to its `;`, or\n * to the next declaration keyword on a later line (automatic semicolon\n * insertion); groups are skipped whole.\n */\nexport function typeDeclarations(\n tokens: readonly Token[],\n lineOf: (offset: number) => number,\n): Map<string, TypeDeclaration> {\n const out = new Map<string, TypeDeclaration>();\n let i = 0;\n // Whether token k begins a statement: after `;` or `}`, or on a later line than the token\n // before it (where a semicolon is inserted), modifiers such as `export` included.\n const startsStatement = (k: number): boolean => {\n const before = tokens[k - 1];\n if (before === undefined || isPunct(before, \";\") || isPunct(before, \"}\")) return true;\n // A line break ends a statement only after a token that can end one: not after an operator\n // (`=`, `,`, `(`…) or an operator keyword (`new`, `extends`…), where the expression goes on.\n const canEnd =\n before.kind === \"punct\"\n ? /^(\\)|\\]|>+|\\+\\+|--)$/.test(before.text)\n : !continuing.has(before.text);\n if (canEnd && lineOf(before.end) < lineOf((tokens[k] as Token).start)) return true;\n return (\n [\"export\", \"default\", \"declare\", \"abstract\", \"const\"].includes(before.text) &&\n startsStatement(k - 1)\n );\n };\n while (i < tokens.length) {\n const t = tokens[i] as Token;\n if (t.kind === \"punct\" && opens.has(t.text)) {\n i = skipGroup(tokens, i);\n continue;\n }\n // Names imported from other modules: the reader does not see their declarations, and a type\n // named Array or ReadonlyArray among them is not the built-in.\n if (isWord(t, \"import\") && startsStatement(i)) {\n for (const name of importBindings(tokens, i + 1))\n out.set(name, {\n name,\n params: [],\n tokens: [],\n unsupported: \"imported from another module\",\n });\n i++;\n continue;\n }\n // A class or an enum is the module's own name too, though the reader does not read it; a\n // class expression's name (`const Impl = class Input {}`) is not.\n if (\n (isWord(t, \"class\") || isWord(t, \"enum\")) &&\n tokens[i + 1]?.kind === \"ident\" &&\n startsStatement(i)\n ) {\n const name = (tokens[i + 1] as Token).text;\n // An interface merged with a class keeps its fields; the class adds none the reader sees.\n if (!out.has(name))\n out.set(name, { name, params: [], tokens: [], unsupported: `a ${t.text}` });\n i += 2;\n continue;\n }\n if (t.kind !== \"ident\" || (t.text !== \"interface\" && t.text !== \"type\")) {\n i++;\n continue;\n }\n // `type` is a declaration only when a name and `=` (or `<`) follow; `interface` likewise with `{`.\n const name = tokens[i + 1];\n if (name?.kind !== \"ident\") {\n i++;\n continue;\n }\n let j = i + 2;\n let params: string[] = [];\n if (isPunct(tokens[j], \"<\")) {\n const p = typeParams(tokens, j);\n params = p.names;\n j = p.end;\n }\n if (t.text === \"interface\") {\n if (isWord(tokens[j], \"extends\")) {\n // To the body, then past it.\n while (j < tokens.length && !isPunct(tokens[j], \"{\")) j++;\n const end = skipGroup(tokens, j);\n out.set(name.text, {\n name: name.text,\n params,\n tokens: tokens.slice(j, end),\n unsupported: \"interface inheritance\",\n });\n i = end;\n continue;\n }\n if (!isPunct(tokens[j], \"{\")) {\n i++;\n continue;\n }\n const end = skipGroup(tokens, j);\n out.set(name.text, { name: name.text, params, tokens: tokens.slice(j, end) });\n i = end;\n continue;\n }\n if (!isPunct(tokens[j], \"=\")) {\n i++;\n continue;\n }\n const start = j + 1;\n let end = start;\n let depth = 0;\n while (end < tokens.length) {\n const u = tokens[end] as Token;\n if (u.kind === \"punct\") {\n if (opens.has(u.text) || u.text === \"<\") depth++;\n else if (closes.has(u.text)) depth--;\n else if (/^>+$/.test(u.text)) depth -= u.text.length;\n else if (u.text === \";\" && depth === 0) break;\n } else if (\n depth === 0 &&\n u.kind === \"ident\" &&\n declarationStarts.has(u.text) &&\n end > start &&\n lineOf(u.start) > lineOf((tokens[end - 1] as Token).end)\n )\n break;\n end++;\n }\n out.set(name.text, { name: name.text, params, tokens: tokens.slice(start, end) });\n i = end;\n }\n // The built-in array names, a second time and on purpose conservatively: declared or imported\n // anywhere in the module,\n // however its statements are delimited, they are the module's, so a misread statement boundary\n // can make such a type unknown but never draw arrays where something else is meant.\n for (const name of [\"Array\", \"ReadonlyArray\"]) {\n if (out.has(name)) continue;\n const shadowed = tokens.some((t, k) => {\n if (t.text !== name) return false;\n // In `Array as Box` (or `type Array as Box`) it is the other module's name; Box is local.\n if (isWord(tokens[k + 1], \"as\")) return false;\n if ([\"class\", \"enum\", \"interface\", \"type\", \"namespace\"].includes(tokens[k - 1]?.text ?? \"\"))\n return true;\n // Inside an import clause, between `import` and its `from` or module string, as the local\n // name.\n for (let j = k - 1; j >= 0; j--) {\n const u = tokens[j] as Token;\n // `{ import: Array }` is an object key, `import(…)` and `import.meta` are expressions.\n if (isWord(u, \"import\"))\n return !(\n isPunct(tokens[j + 1], \":\") ||\n isPunct(tokens[j + 1], \"(\") ||\n isPunct(tokens[j + 1], \".\")\n );\n if (isWord(u, \"from\") || u.kind === \"string\" || isPunct(u, \";\")) return false;\n }\n return false;\n });\n if (shadowed)\n out.set(name, {\n name,\n params: [],\n tokens: [],\n unsupported: \"declared or imported by the module\",\n });\n }\n return out;\n}\n\nexport interface TypeEnv {\n readonly source: string;\n readonly declarations: ReadonlyMap<string, TypeDeclaration>;\n /** Type parameters in scope, bound to their arguments. */\n readonly bindings: ReadonlyMap<string, SpecType>;\n /** Declarations being expanded, against recursion. */\n readonly expanding: ReadonlySet<string>;\n}\n\nconst unknown = (text: string): SpecType => ({ kind: \"unknown\", text: text.trim() });\n\n/** The source text spanned by the tokens, for an `unknown`. */\nfunction textOf(source: string, tokens: readonly Token[]): string {\n const first = tokens[0];\n const last = tokens[tokens.length - 1];\n return first && last ? source.slice(first.start, last.end) : \"\";\n}\n\n/** The value of a string literal token, for literal types (simple escapes only; others are `unknown`). */\nfunction stringValue(text: string): string | undefined {\n const body = text.slice(1, -1);\n if (!body.includes(\"\\\\\")) return body;\n try {\n return JSON.parse(`\"${body.replace(/\"/g, '\\\\\"').replace(/\\\\'/g, \"'\")}\"`) as string;\n } catch {\n return undefined;\n }\n}\n\n/** Members of a union, flattened and deduplicated; a single member is itself. */\nexport function union(members: readonly SpecType[]): SpecType {\n const flat: SpecType[] = [];\n const seen = new Set<string>();\n for (const m of members)\n for (const x of m.kind === \"union\" ? m.members : [m]) {\n const key = JSON.stringify(x);\n if (seen.has(key)) continue;\n seen.add(key);\n flat.push(x);\n }\n return flat.length === 1 ? (flat[0] as SpecType) : { kind: \"union\", members: flat };\n}\n\n/**\n * The whole token list as one type. A construct the reader does not\n * read makes the type (or the field, or the union member) `unknown`.\n */\nexport function readType(tokens: readonly Token[], env: TypeEnv): SpecType {\n if (tokens.length === 0) return unknown(\"\");\n const r = new TypeReader(tokens, env);\n const t = r.union();\n if (r.at < tokens.length) return unknown(textOf(env.source, tokens));\n return t;\n}\n\nclass TypeReader {\n at = 0;\n readonly tokens: readonly Token[];\n readonly env: TypeEnv;\n // No parameter properties: Node's type stripping, which runs these sources directly, rejects them.\n constructor(tokens: readonly Token[], env: TypeEnv) {\n this.tokens = tokens;\n this.env = env;\n }\n\n peek(n = 0): Token | undefined {\n return this.tokens[this.at + n];\n }\n\n /** The text from token `from` to the current position, for an `unknown`. */\n since(from: number): string {\n return textOf(this.env.source, this.tokens.slice(from, Math.max(from + 1, this.at)));\n }\n\n union(): SpecType {\n const from = this.at;\n if (isPunct(this.peek(), \"|\")) this.at++;\n const members = [this.intersection()];\n while (isPunct(this.peek(), \"|\")) {\n this.at++;\n members.push(this.intersection());\n }\n // One unreadable member keeps its own text; the union's shape still shows.\n return members.length === 1\n ? (members[0] as SpecType)\n : union(members) || unknown(this.since(from));\n }\n\n intersection(): SpecType {\n const from = this.at;\n const first = this.postfix();\n if (!isPunct(this.peek(), \"&\")) return first;\n while (isPunct(this.peek(), \"&\")) {\n this.at++;\n this.postfix();\n }\n return unknown(this.since(from));\n }\n\n /** A primary type and its `[]` suffixes, each an array; `T[K]` (indexed access) is unknown. */\n postfix(): SpecType {\n const from = this.at;\n let t = this.primary();\n let indexed = false;\n while (isPunct(this.peek(), \"[\")) {\n if (isPunct(this.peek(1), \"]\")) {\n this.at += 2;\n t = { kind: \"array\", element: t };\n continue;\n }\n indexed = true;\n this.at = skipGroup(this.tokens, this.at);\n }\n return indexed ? unknown(this.since(from)) : t;\n }\n\n primary(): SpecType {\n const from = this.at;\n const t = this.peek();\n if (!t) return unknown(\"\");\n this.at++;\n switch (t.kind) {\n case \"string\": {\n const value = stringValue(t.text);\n return value === undefined ? unknown(t.text) : { kind: \"literal\", value };\n }\n case \"number\": {\n const value = Number(t.text.replace(/_/g, \"\"));\n return Number.isFinite(value) && !t.text.endsWith(\"n\")\n ? { kind: \"literal\", value }\n : unknown(t.text);\n }\n case \"punct\":\n if (t.text === \"{\") {\n this.at--;\n return this.record();\n }\n if (t.text === \"(\") {\n const inner = this.union();\n if (!isPunct(this.peek(), \")\")) return unknown(this.since(from));\n this.at++;\n return inner;\n }\n if (t.text === \"-\" && this.peek()?.kind === \"number\") {\n const n = this.peek() as Token;\n this.at++;\n const value = -Number(n.text.replace(/_/g, \"\"));\n return Number.isFinite(value) ? { kind: \"literal\", value } : unknown(this.since(from));\n }\n return unknown(this.since(from));\n case \"ident\":\n return this.named(t, from);\n default:\n return unknown(this.since(from));\n }\n }\n\n /** A keyword type, a literal keyword, a type parameter or a declared name with its arguments. */\n named(t: Token, from: number): SpecType {\n switch (t.text) {\n case \"number\":\n case \"boolean\":\n case \"string\":\n case \"bigint\":\n case \"null\":\n case \"undefined\":\n return { kind: t.text };\n case \"true\":\n case \"false\":\n return { kind: \"literal\", value: t.text === \"true\" };\n case \"readonly\": {\n // `readonly T[]` is the array type; `readonly` before anything else (a tuple) is not read.\n const t = this.postfix();\n return t.kind === \"array\" ? t : unknown(this.since(from));\n }\n case \"typeof\":\n case \"keyof\":\n this.postfix();\n return unknown(this.since(from));\n }\n // A qualified name (`ns.T`) is not the module's own.\n if (isPunct(this.peek(), \".\")) {\n while (isPunct(this.peek(), \".\") && this.peek(1)?.kind === \"ident\") this.at += 2;\n if (isPunct(this.peek(), \"<\")) this.at = skipAngles(this.tokens, this.at);\n return unknown(this.since(from));\n }\n const bound = this.env.bindings.get(t.text);\n if (bound && !isPunct(this.peek(), \"<\")) return bound;\n const args: SpecType[] = [];\n if (isPunct(this.peek(), \"<\")) {\n const end = skipAngles(this.tokens, this.at);\n const inner = anglesInner(this.tokens, this.at, end);\n for (const group of splitTopLevel(inner, \",\")) args.push(readType(group, this.env));\n this.at = end;\n }\n const decl = this.env.declarations.get(t.text);\n // The built-in array types, unless the module declares a type of that name itself.\n if (!decl && (t.text === \"Array\" || t.text === \"ReadonlyArray\"))\n return args.length === 1\n ? { kind: \"array\", element: args[0] as SpecType }\n : unknown(this.since(from));\n if (!decl) return unknown(this.since(from));\n if (decl.unsupported) return unknown(this.since(from));\n if (this.env.expanding.has(t.text)) return unknown(this.since(from));\n if (args.length > decl.params.length) return unknown(this.since(from));\n const bindings = new Map(this.env.bindings);\n decl.params.forEach((p, i) => {\n bindings.set(p, args[i] ?? unknown(p));\n });\n const expanded = readType(decl.tokens, {\n ...this.env,\n bindings,\n expanding: new Set([...this.env.expanding, t.text]),\n });\n const name = this.since(from);\n // A declared record keeps its name; an alias of a union is the union.\n return expanded.kind === \"record\" && expanded.name === undefined\n ? { ...expanded, name }\n : expanded;\n }\n\n /** `{ readonly? name: T; … }`. A method, an index signature, an optional field or a computed key makes it unknown. */\n record(): SpecType {\n const from = this.at;\n const end = skipGroup(this.tokens, this.at);\n const inner = this.tokens.slice(this.at + 1, end - 1);\n this.at = end;\n const fields: Field[] = [];\n for (const member of splitMembers(inner)) {\n let i = 0;\n if (isWord(member[i], \"readonly\")) i++;\n const name = member[i];\n if (name?.kind !== \"ident\") return unknown(this.since(from));\n i++;\n if (isPunct(member[i], \"?\")) return unknown(this.since(from));\n if (!isPunct(member[i], \":\")) return unknown(this.since(from));\n const type = readType(member.slice(i + 1), this.env);\n fields.push({ name: name.text, type });\n }\n return { kind: \"record\", fields };\n }\n}\n\n/** Split tokens at a top-level punctuator. */\nfunction splitTopLevel(tokens: readonly Token[], at: string): Token[][] {\n const out: Token[][] = [];\n let current: Token[] = [];\n let depth = 0;\n for (const t of tokens) {\n if (t.kind === \"punct\") {\n if (opens.has(t.text) || t.text === \"<\") depth++;\n else if (closes.has(t.text)) depth--;\n else if (/^>+$/.test(t.text)) depth -= t.text.length;\n else if (t.text === at && depth === 0) {\n out.push(current);\n current = [];\n continue;\n }\n }\n current.push(t);\n }\n if (current.length > 0 || out.length > 0) out.push(current);\n return out.filter((g) => g.length > 0);\n}\n\n/** Members of a type literal: separated by `;`, `,` or a line break between members. */\nfunction splitMembers(tokens: readonly Token[]): Token[][] {\n const out: Token[][] = [];\n let current: Token[] = [];\n let depth = 0;\n for (const t of tokens) {\n if (t.kind === \"punct\") {\n if (opens.has(t.text) || t.text === \"<\") depth++;\n else if (closes.has(t.text)) depth--;\n else if (/^>+$/.test(t.text)) depth -= t.text.length;\n else if ((t.text === \";\" || t.text === \",\") && depth === 0) {\n if (current.length > 0) out.push(current);\n current = [];\n continue;\n }\n }\n // A new member starts at a name (or readonly) at depth 0 right after a complete member: `a: T\\n b: U`.\n if (\n depth === 0 &&\n current.length >= 3 &&\n (t.kind === \"ident\" || t.kind === \"string\") &&\n isNameStart(current, t)\n ) {\n out.push(current);\n current = [];\n }\n current.push(t);\n }\n if (current.length > 0) out.push(current);\n return out;\n}\n\n/** Whether `t` starts a new member after `current` (a member is `name: type`; a type never ends in a keyword or name followed by a name on a later line). */\nfunction isNameStart(current: readonly Token[], t: Token): boolean {\n const last = current[current.length - 1] as Token;\n // A type continues after an operator (`|`, `,`, `<`…); a closing bracket ends a complete one.\n if (last.kind === \"punct\" && !/^(\\]|\\)|\\}|>+)$/.test(last.text)) return false;\n // So it does after a type operator: `xs: readonly string[]`.\n if ([\"readonly\", \"keyof\", \"typeof\", \"unique\"].includes(last.text)) return false;\n const next = t.kind === \"ident\" ? t : undefined;\n return next !== undefined && last.end < t.start;\n}\n","/**\n * A module and its spec file read into `ModuleSpecs`. From the module:\n * the exported functions and their parameter types (`function`\n * declarations and `const` arrows alike), through the type reader. From\n * the spec file: every `export const name = forall(f, { when, ensures })`\n * and `total(f)`, with the combinators imported from `eutaxy/spec` and `f`\n * from the module; 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 { endpointBigInt, endpointNumber } from \"../generate.ts\";\nimport { type Token, TokenizeError, tokenize } from \"./tokens.ts\";\nimport { readType, type TypeDeclaration, typeDeclarations, union } 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 /** Every import specifier that names the module from the spec file (\"./domain.ts\", \"./domain\", \"./domain.js\"). */\n readonly moduleSpecifiers: readonly string[];\n /** Specifiers the combinators come from; `eutaxy/spec` and the workspace name by default. */\n readonly specSpecifiers?: readonly string[];\n}\n\nconst isPunct = (t: Token | undefined, text: string): boolean =>\n t?.kind === \"punct\" && t.text === text;\nconst isWord = (t: Token | undefined, text: string): boolean =>\n t?.kind === \"ident\" && t.text === text;\nconst opens = new Set([\"(\", \"[\", \"{\"]);\nconst closes = new Set([\")\", \"]\", \"}\"]);\n\n/** Line of an offset, every JavaScript line terminator counted. */\nfunction lineIndex(source: string): (offset: number) => number {\n const starts = [0];\n for (let i = 0; i < source.length; i++) {\n const c = source[i];\n if (c === \"\\r\") {\n if (source[i + 1] === \"\\n\") i++;\n starts.push(i + 1);\n } else if (c === \"\\n\" || c === \"
\" || c === \"
\") starts.push(i + 1);\n }\n return (offset) => {\n let lo = 0;\n let hi = starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if ((starts[mid] as number) <= offset) lo = mid;\n else hi = mid - 1;\n }\n return lo + 1;\n };\n}\n\n/** The index just past the group opened at `i`. */\nfunction skipGroup(tokens: readonly Token[], i: number): number {\n let depth = 0;\n for (let j = i; j < tokens.length; j++) {\n const t = tokens[j] as Token;\n if (t.kind !== \"punct\") continue;\n if (opens.has(t.text)) depth++;\n else if (closes.has(t.text)) {\n depth--;\n if (depth === 0) return j + 1;\n }\n }\n return tokens.length;\n}\n\n/**\n * Split at a top-level punctuator. Angle brackets count as a group where\n * types may appear (parameter lists, imports); in an expression `<` is a\n * comparison and does not.\n */\nfunction splitTopLevel(tokens: readonly Token[], at: string, angles = true): Token[][] {\n const out: Token[][] = [];\n let current: Token[] = [];\n let depth = 0;\n for (const t of tokens) {\n if (t.kind === \"punct\") {\n if (opens.has(t.text) || (angles && t.text === \"<\")) depth++;\n else if (closes.has(t.text)) depth--;\n else if (angles && /^>+$/.test(t.text)) depth -= t.text.length;\n else if (t.text === at && depth === 0) {\n out.push(current);\n current = [];\n continue;\n }\n }\n current.push(t);\n }\n out.push(current);\n return out.filter((g) => g.length > 0);\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/**\n * The parameters of the list opened at `open`: `name?: T = default`,\n * `...rest`, destructured. The index past the `)` is returned with them.\n */\nfunction readParams(\n tokens: readonly Token[],\n open: number,\n types: { readonly source: string; readonly declarations: ReadonlyMap<string, TypeDeclaration> },\n): { params: Param[]; end: number } {\n const end = skipGroup(tokens, open);\n const inner = tokens.slice(open + 1, end - 1);\n const params: Param[] = [];\n for (const group of splitTopLevel(inner, \",\")) {\n let i = 0;\n let name: string | null = null;\n let rest = false;\n if (isPunct(group[i], \"...\")) {\n rest = true;\n i++;\n }\n const head = group[i];\n if (head?.kind === \"ident\") {\n name = head.text;\n i++;\n } else if (head?.kind === \"punct\" && (head.text === \"{\" || head.text === \"[\")) {\n i = skipGroup(group, i);\n }\n if (name === \"this\") continue; // a receiver annotation, no argument\n let optional = false;\n if (isPunct(group[i], \"?\")) {\n optional = true;\n i++;\n }\n let type: SpecType = { kind: \"unknown\", text: \"(no type annotation)\" };\n if (isPunct(group[i], \":\")) {\n i++;\n let j = i;\n let depth = 0;\n while (j < group.length) {\n const t = group[j] as Token;\n if (t.kind === \"punct\") {\n if (opens.has(t.text) || t.text === \"<\") depth++;\n else if (closes.has(t.text)) depth--;\n else if (/^>+$/.test(t.text)) depth -= t.text.length;\n else if (t.text === \"=\" && depth === 0) break;\n }\n j++;\n }\n type = readType(group.slice(i, j), {\n source: types.source,\n declarations: types.declarations,\n bindings: new Map(),\n expanding: new Set(),\n });\n i = j;\n }\n if (isPunct(group[i], \"=\")) optional = true; // a default: the caller may pass undefined\n if (rest) type = { kind: \"unknown\", text: `...${name ?? \"\"}` };\n else if (optional) type = union([type, { kind: \"undefined\" }]);\n params.push({ name: rest ? null : name, type });\n }\n return { params, end };\n}\n\n/**\n * Whether the `function` at `i` is a declaration (not an expression): at\n * the start of the module, after a statement end, or on a new line after\n * a finished statement (automatic semicolon insertion), with `export` and\n * `async` allowed in front.\n */\nfunction isFunctionDeclaration(\n tokens: readonly Token[],\n i: number,\n lineOf: (offset: number) => number,\n): boolean {\n let k = i - 1;\n while (\n tokens[k]?.kind === \"ident\" &&\n [\"async\", \"export\", \"default\"].includes(tokens[k]?.text ?? \"\")\n )\n k--;\n const before = tokens[k];\n if (before === undefined) return true;\n if (before.kind === \"punct\" && (before.text === \";\" || before.text === \"}\")) return true;\n if (lineOf(before.end) === lineOf((tokens[i] as Token).start)) return false;\n if (before.kind === \"punct\") return [\")\", \"]\", \"++\", \"--\"].includes(before.text);\n if (before.kind === \"ident\")\n return !\"return typeof void new else case in of do yield await delete instanceof throw export default async\"\n .split(\" \")\n .includes(before.text);\n return true;\n}\n\nfunction readModuleSide(source: string): ModuleSide {\n const errors: SpecError[] = [];\n let tokens: Token[];\n try {\n tokens = tokenize(source);\n } catch (err) {\n if (!(err instanceof TokenizeError)) throw err;\n errors.push({\n line: 1,\n message: `the module could not be tokenized: ${err.message}`,\n inModule: true,\n });\n return { declarations: new Map(), exports: new Map(), errors };\n }\n const lineOf = lineIndex(source);\n const declarations = new Map<string, Declaration>();\n const exports = new Map<string, string>();\n const types = { source, declarations: typeDeclarations(tokens, lineOf) };\n let i = 0;\n while (i < tokens.length) {\n const t = tokens[i] as Token;\n if (t.kind === \"punct\" && opens.has(t.text)) {\n i = skipGroup(tokens, i);\n continue;\n }\n if (t.kind !== \"ident\") {\n i++;\n continue;\n }\n if (t.text === \"export\" && isPunct(tokens[i + 1], \"{\")) {\n // `export { a, b as c }`; with `from`, a re-export of another module's names (not this module's).\n const end = skipGroup(tokens, i + 1);\n if (!isWord(tokens[end], \"from\"))\n for (const group of splitTopLevel(tokens.slice(i + 2, end - 1), \",\")) {\n if (isWord(group[0], \"type\")) continue;\n const local = group[0];\n const exported = isWord(group[1], \"as\") ? group[2] : group[0];\n if (local?.kind === \"ident\" && exported?.kind === \"ident\")\n exports.set(exported.text, local.text);\n }\n i = end;\n continue;\n }\n if (t.text === \"function\" && isFunctionDeclaration(tokens, i, lineOf)) {\n let j = i + 1;\n if (isPunct(tokens[j], \"*\")) j++;\n const name = tokens[j];\n if (name?.kind !== \"ident\") {\n i++;\n continue;\n }\n j++;\n if (isPunct(tokens[j], \"<\")) {\n // Type parameters: skip to the parameter list.\n let depth = 0;\n for (; j < tokens.length; j++) {\n const u = tokens[j] as Token;\n if (u.kind !== \"punct\") continue;\n if (u.text === \"<\") depth++;\n else if (/^>+$/.test(u.text)) {\n depth -= u.text.length;\n if (depth <= 0) {\n j++;\n break;\n }\n }\n }\n }\n if (!isPunct(tokens[j], \"(\")) {\n i++;\n continue;\n }\n let k = i - 1;\n let exported = false;\n while (\n tokens[k]?.kind === \"ident\" &&\n [\"async\", \"export\", \"default\"].includes(tokens[k]?.text ?? \"\")\n ) {\n if (tokens[k]?.text === \"export\") exported = true;\n k--;\n }\n const read = readParams(tokens, j, types);\n if (!declarations.has(name.text))\n declarations.set(name.text, {\n name: name.text,\n params: read.params,\n line: lineOf(t.start),\n offset: (tokens[j] as Token).start,\n });\n else\n errors.push({\n line: lineOf(t.start),\n message: `${name.text} is declared more than once (overloads): a spec is checked against one signature`,\n inModule: true,\n });\n if (exported) exports.set(name.text, name.text);\n i = read.end;\n continue;\n }\n if (t.text === \"const\" || t.text === \"let\" || t.text === \"var\") {\n // `export const f = (a: T): R => …` or `= function (a: T) …`: a function by another declaration.\n const exported = isWord(tokens[i - 1], \"export\");\n const name = tokens[i + 1];\n if (name?.kind !== \"ident\" || !isPunct(tokens[i + 2], \"=\")) {\n i++;\n continue;\n }\n let j = i + 3;\n if (isWord(tokens[j], \"async\")) j++;\n if (isWord(tokens[j], \"function\")) {\n j++;\n if (isPunct(tokens[j], \"*\")) j++;\n if (tokens[j]?.kind === \"ident\") j++;\n }\n if (!isPunct(tokens[j], \"(\")) {\n i++;\n continue;\n }\n const close = skipGroup(tokens, j);\n // An arrow: `)` then `=>`, or `):` a return type then `=>`; a function expression: `)` then `{` or `:`.\n let k = close;\n if (isPunct(tokens[k], \":\")) {\n let depth = 0;\n for (; k < tokens.length; k++) {\n const u = tokens[k] as Token;\n if (u.kind !== \"punct\") continue;\n if (opens.has(u.text) || u.text === \"<\") depth++;\n else if (closes.has(u.text)) depth--;\n else if (/^>+$/.test(u.text)) depth -= u.text.length;\n else if (u.text === \"=>\" && depth === 0) break;\n if (depth < 0) break;\n }\n }\n const isFunction = isPunct(tokens[k], \"=>\") || isPunct(tokens[close], \"{\");\n if (!isFunction) {\n i++;\n continue;\n }\n const read = readParams(tokens, j, types);\n if (!declarations.has(name.text))\n declarations.set(name.text, {\n name: name.text,\n params: read.params,\n line: lineOf(t.start),\n offset: (tokens[j] as Token).start,\n });\n if (exported) exports.set(name.text, name.text);\n i = read.end;\n continue;\n }\n i++;\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}\n\n/** `import { a, b as c } from \"x\"`, `import * as ns from \"x\"`, `import d from \"x\"`; type-only imports skipped. */\nfunction imports(tokens: readonly Token[]): Map<string, Imported> {\n const out = new Map<string, Imported>();\n let i = 0;\n while (i < tokens.length) {\n const t = tokens[i] as Token;\n if (t.kind === \"punct\" && opens.has(t.text)) {\n i = skipGroup(tokens, i);\n continue;\n }\n if (!isWord(t, \"import\") || isPunct(tokens[i + 1], \"(\")) {\n i++;\n continue;\n }\n let j = i + 1;\n const typeOnly =\n isWord(tokens[j], \"type\") && !isPunct(tokens[j + 1], \",\") && !isWord(tokens[j + 1], \"from\");\n if (typeOnly) j++;\n const bound: { local: string; name: string }[] = [];\n if (tokens[j]?.kind === \"ident\" && !isWord(tokens[j], \"from\")) {\n bound.push({ local: (tokens[j] as Token).text, name: \"default\" });\n j++;\n if (isPunct(tokens[j], \",\")) j++;\n }\n if (isPunct(tokens[j], \"*\")) {\n j++;\n if (isWord(tokens[j], \"as\") && tokens[j + 1]?.kind === \"ident\") {\n bound.push({ local: (tokens[j + 1] as Token).text, name: \"*\" });\n j += 2;\n }\n } else if (isPunct(tokens[j], \"{\")) {\n const end = skipGroup(tokens, j);\n for (const group of splitTopLevel(tokens.slice(j + 1, end - 1), \",\")) {\n let g = 0;\n if (isWord(group[g], \"type\") && group.length > 1) continue;\n const name = group[g];\n if (name?.kind !== \"ident\" && name?.kind !== \"string\") continue;\n g++;\n const local = isWord(group[g], \"as\") ? group[g + 1] : name;\n if (local?.kind !== \"ident\") continue;\n bound.push({\n local: local.text,\n name: name.kind === \"string\" ? name.text.slice(1, -1) : name.text,\n });\n }\n j = end;\n }\n if (!isWord(tokens[j], \"from\")) {\n i = j;\n continue;\n }\n const from = tokens[j + 1];\n if (from?.kind === \"string\" && !typeOnly)\n for (const b of bound) out.set(b.local, { from: from.text.slice(1, -1), name: b.name });\n i = j + 2;\n }\n return out;\n}\n\n/** The arrow's parameter names; null for a destructured one. Type annotations and defaults are skipped. */\nfunction arrowParams(tokens: readonly Token[]): (string | null)[] {\n return splitTopLevel(tokens, \",\").map((group) => {\n const head = group[0];\n return head?.kind === \"ident\" ? head.text : null;\n });\n}\n\n/** `1`, `-1`, `1_000`, `1.5` as an endpoint value; undefined otherwise. */\nfunction numberText(tokens: readonly Token[]): string | undefined {\n if (tokens.length === 1 && tokens[0]?.kind === \"number\") return tokens[0].text.replace(/_/g, \"\");\n if (tokens.length === 2 && isPunct(tokens[0], \"-\") && tokens[1]?.kind === \"number\")\n return `-${tokens[1].text.replace(/_/g, \"\")}`;\n return undefined;\n}\n\n/**\n * What the precondition says about each of its parameters on its own: its\n * top-level conjuncts of the forms `Number.isInteger(x)`, `x < n`, `n <= x`\n * (and the other comparisons) and `/re/.test(x)`, by parameter index.\n */\nexport function hintsOf(arrow: Arrow): Map<number, Hint> {\n const out = new Map<number, Hint>();\n if (arrow.block) return out;\n let tokens: Token[];\n try {\n tokens = tokenize(arrow.body);\n } catch {\n return out;\n }\n const position = new Map<string, number>();\n arrow.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 (let conjunct of splitTopLevel(tokens, \"&&\", false)) {\n while (\n conjunct.length >= 2 &&\n isPunct(conjunct[0], \"(\") &&\n skipGroup(conjunct, 0) === conjunct.length\n )\n conjunct = conjunct.slice(1, -1);\n // Number.isInteger(x)\n if (\n conjunct.length === 6 &&\n isWord(conjunct[0], \"Number\") &&\n isPunct(conjunct[1], \".\") &&\n isWord(conjunct[2], \"isInteger\") &&\n isPunct(conjunct[3], \"(\") &&\n conjunct[4]?.kind === \"ident\" &&\n isPunct(conjunct[5], \")\")\n ) {\n const at = position.get(conjunct[4].text);\n if (at !== undefined) merge(at, { integer: true });\n continue;\n }\n // /re/.test(x)\n if (\n conjunct.length === 6 &&\n conjunct[0]?.kind === \"regex\" &&\n isPunct(conjunct[1], \".\") &&\n isWord(conjunct[2], \"test\") &&\n isPunct(conjunct[3], \"(\") &&\n conjunct[4]?.kind === \"ident\" &&\n isPunct(conjunct[5], \")\")\n ) {\n const at = position.get(conjunct[4].text);\n const m = /^\\/([\\s\\S]*)\\/([a-z]*)$/.exec(conjunct[0].text);\n if (at !== undefined && m)\n merge(at, { regex: { pattern: m[1] as string, flags: m[2] as string } });\n continue;\n }\n // x op n, n op x\n const opAt = conjunct.findIndex(\n (t) => t.kind === \"punct\" && [\"<\", \"<=\", \">\", \">=\"].includes(t.text),\n );\n if (opAt < 0) continue;\n const op = (conjunct[opAt] as Token).text;\n const left = conjunct.slice(0, opAt);\n const right = conjunct.slice(opAt + 1);\n const bound = (variable: Token[], literal: Token[], variableOnLeft: boolean) => {\n const name =\n variable.length === 1 && variable[0]?.kind === \"ident\" ? variable[0].text : undefined;\n const value = numberText(literal);\n if (name === undefined || value === undefined) return;\n const at = position.get(name);\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 (left.length === 1 && left[0]?.kind === \"ident\") bound(left, right, true);\n else if (right.length === 1 && right[0]?.kind === \"ident\") bound(right, left, false);\n }\n return out;\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}\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 source: string,\n moduleSpecifiers: ReadonlySet<string>,\n specSpecifiers: ReadonlySet<string>,\n): { specs: SpecExport[]; errors: SpecError[]; imports: ModuleImport[] } {\n const errors: SpecError[] = [];\n let tokens: Token[];\n try {\n tokens = tokenize(source);\n } catch (err) {\n if (!(err instanceof TokenizeError)) throw err;\n return {\n specs: [],\n errors: [{ line: 1, message: `the spec file could not be tokenized: ${err.message}` }],\n imports: [],\n };\n }\n const lineOf = lineIndex(source);\n const bound = imports(tokens);\n const specs: SpecExport[] = [];\n const fail: (message: string, t: Token | undefined) => never = (message, t) => {\n throw new SpecFail(message, t ? lineOf(t.start) : lineOf(source.length));\n };\n /** The combinator a callee names (`forall`, `ns.forall`), or undefined. */\n const combinator = (i: number): { kind: \"forall\" | \"total\"; next: number } | undefined => {\n const t = tokens[i];\n if (t?.kind !== \"ident\") return undefined;\n if (isPunct(tokens[i + 1], \".\") && tokens[i + 2]?.kind === \"ident\") {\n const ns = bound.get(t.text);\n const member = (tokens[i + 2] as Token).text;\n if (\n ns?.name === \"*\" &&\n specSpecifiers.has(ns.from) &&\n (member === \"forall\" || member === \"total\")\n )\n return { kind: member, next: i + 3 };\n return undefined;\n }\n const imp = bound.get(t.text);\n if (imp && specSpecifiers.has(imp.from) && (imp.name === \"forall\" || imp.name === \"total\"))\n return { kind: imp.name, next: i + 1 };\n return undefined;\n };\n /** The module function a first argument names, or why not. */\n const functionArg = (i: number): { fn: string; next: number } => {\n const t = tokens[i];\n if (t?.kind !== \"ident\")\n return fail(\n `the first argument must name a function of the module, found ${t?.text ?? \"the end\"}`,\n t,\n );\n if (isPunct(tokens[i + 1], \".\") && tokens[i + 2]?.kind === \"ident\") {\n const ns = bound.get(t.text);\n if (ns?.name === \"*\" && moduleSpecifiers.has(ns.from))\n return { fn: (tokens[i + 2] as Token).text, next: i + 3 };\n return fail(\n `${t.text}.${(tokens[i + 2] as Token).text} is not a function imported from the module`,\n t,\n );\n }\n const imp = bound.get(t.text);\n if (!imp)\n return fail(\n `${t.text} is not imported from the module (import it from ${[...moduleSpecifiers][0]})`,\n t,\n );\n if (!moduleSpecifiers.has(imp.from))\n return fail(\n `${t.text} is imported from ${JSON.stringify(imp.from)}, not from the module beside this spec file`,\n t,\n );\n if (imp.name === \"*\" || imp.name === \"default\")\n return fail(`${t.text} must be a named import of the module's function`, t);\n return { fn: imp.name, next: i + 1 };\n };\n /** An arrow function at `i`: its params, body text and whether the body is a block; the index past it. */\n const arrow = (i: number, what: string): { arrow: Arrow; next: number } => {\n const start = tokens[i];\n if (isWord(start, \"async\")) fail(`${what} is an async arrow; it must be synchronous`, start);\n let params: (string | null)[];\n let j: number;\n if (isPunct(start, \"(\")) {\n const end = skipGroup(tokens, i);\n params = arrowParams(tokens.slice(i + 1, end - 1));\n j = end;\n // A return type annotation before the arrow is skipped.\n if (isPunct(tokens[j], \":\")) {\n let depth = 0;\n for (; j < tokens.length; j++) {\n const u = tokens[j] as Token;\n if (u.kind !== \"punct\") continue;\n if (opens.has(u.text) || u.text === \"<\") depth++;\n else if (closes.has(u.text)) depth--;\n else if (/^>+$/.test(u.text)) depth -= u.text.length;\n else if (u.text === \"=>\" && depth === 0) break;\n }\n }\n } else if (start?.kind === \"ident\" && isPunct(tokens[i + 1], \"=>\")) {\n params = [start.text];\n j = i + 1;\n } else\n return fail(`${what} must be an arrow function, found ${start?.text ?? \"the end\"}`, start);\n if (!isPunct(tokens[j], \"=>\"))\n return fail(`${what} must be an arrow function (no => after its parameters)`, start);\n j++;\n const first = tokens[j];\n if (!first) return fail(`${what} has no body`, start);\n if (isPunct(first, \"{\")) {\n const end = skipGroup(tokens, j);\n const last = tokens[end - 1] as Token;\n return {\n arrow: {\n params,\n body: source.slice(first.end, last.start),\n block: true,\n line: lineOf((start as Token).start),\n },\n next: end,\n };\n }\n // An expression body runs to the `,` or `}` that ends the property.\n let depth = 0;\n let k = j;\n for (; k < tokens.length; k++) {\n const u = tokens[k] as Token;\n if (u.kind !== \"punct\") continue;\n if (opens.has(u.text)) depth++;\n else if (closes.has(u.text)) {\n if (depth === 0) break;\n depth--;\n } else if (u.text === \",\" && depth === 0) break;\n }\n const last = tokens[k - 1] as Token;\n return {\n arrow: {\n params,\n body: source.slice(first.start, last.end),\n block: false,\n line: lineOf((start as Token).start),\n },\n next: k,\n };\n };\n let i = 0;\n while (i < tokens.length) {\n const t = tokens[i] as Token;\n if (t.kind === \"punct\" && opens.has(t.text)) {\n i = skipGroup(tokens, i);\n continue;\n }\n if (t.kind !== \"ident\" || (t.text !== \"const\" && t.text !== \"let\" && t.text !== \"var\")) {\n i++;\n continue;\n }\n const exported = isWord(tokens[i - 1], \"export\");\n const name = tokens[i + 1];\n if (name?.kind !== \"ident\") {\n i++;\n continue;\n }\n // `export const p: Forall<typeof f> = …`: the annotation runs to the `=` at depth 0.\n let eq = i + 2;\n if (isPunct(tokens[eq], \":\")) {\n let depth = 0;\n for (eq++; eq < tokens.length; eq++) {\n const u = tokens[eq] as Token;\n if (u.kind !== \"punct\") continue;\n if (opens.has(u.text) || u.text === \"<\") depth++;\n else if (closes.has(u.text)) depth--;\n else if (/^>+$/.test(u.text)) depth -= u.text.length;\n else if (u.text === \"=\" && depth === 0) break;\n if (depth < 0) break;\n }\n }\n if (!isPunct(tokens[eq], \"=\")) {\n i++;\n continue;\n }\n const call = combinator(eq + 1);\n if (!call) {\n i++;\n continue;\n }\n const line = lineOf(t.start);\n try {\n if (!exported) fail(`${name.text} is a spec but not exported, so nothing would check it`, t);\n if (t.text !== \"const\") fail(`a spec must be a const export, not ${t.text}`, t);\n let j = call.next;\n if (!isPunct(tokens[j], \"(\")) fail(`${call.kind} must be called`, tokens[j]);\n const callEnd = skipGroup(tokens, j);\n j++;\n const arg = functionArg(j);\n j = arg.next;\n if (call.kind === \"total\") {\n if (!isPunct(tokens[j], \")\")) fail(\"total takes the function alone\", tokens[j]);\n specs.push({ name: name.text, kind: \"total\", fn: arg.fn, text: `total(${arg.fn})`, line });\n i = callEnd;\n continue;\n }\n if (!isPunct(tokens[j], \",\"))\n fail(\"forall takes the function, then { when, ensures }\", tokens[j]);\n j++;\n if (!isPunct(tokens[j], \"{\"))\n fail(\"forall's second argument must be an object literal { when, ensures }\", tokens[j]);\n const objectEnd = skipGroup(tokens, j);\n j++;\n let sample: Arrow | undefined;\n let when: Arrow | undefined;\n let ensures: Arrow | undefined;\n while (j < objectEnd - 1) {\n const key = tokens[j] as Token;\n if (isPunct(key, \",\")) {\n j++;\n continue;\n }\n if (\n key.kind !== \"ident\" ||\n (key.text !== \"sample\" && key.text !== \"when\" && key.text !== \"ensures\")\n )\n fail(`forall's properties are sample, when and ensures, found ${key.text}`, key);\n if (!isPunct(tokens[j + 1], \":\"))\n fail(`${key.text} must be written as ${key.text}: (…) => …`, key);\n const read = arrow(j + 2, key.text);\n if (key.text === \"sample\") {\n if (sample) fail(\"sample is given twice\", key);\n sample = read.arrow;\n } else if (key.text === \"when\") {\n if (when) fail(\"when is given twice\", key);\n when = read.arrow;\n } else {\n if (ensures) fail(\"ensures is given twice\", key);\n ensures = read.arrow;\n }\n j = read.next;\n }\n if (!ensures) return fail(\"forall needs an ensures\", tokens[objectEnd - 1]);\n j = objectEnd;\n if (!isPunct(tokens[j], \")\"))\n fail(`unexpected ${tokens[j]?.text ?? \"end\"} after forall's arguments`, tokens[j]);\n specs.push({\n name: name.text,\n kind: \"forall\",\n fn: arg.fn,\n ...(sample ? { sample } : {}),\n ...(when ? { when } : {}),\n ensures,\n text: ensures.body.replace(/\\s+/g, \" \").trim(),\n line,\n });\n i = callEnd;\n } catch (err) {\n if (!(err instanceof SpecFail)) throw err;\n errors.push({ line: err.line, message: `${name.text}: ${err.message}` });\n i++;\n }\n }\n const moduleImports: ModuleImport[] = [...bound]\n .filter(\n ([, imp]) => moduleSpecifiers.has(imp.from) && imp.name !== \"*\" && imp.name !== \"default\",\n )\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 moduleSide = readModuleSide(input.module);\n const specSide = readSpecSide(\n input.spec,\n new Set(input.moduleSpecifiers),\n new Set(input.specSpecifiers ?? [\"eutaxy/spec\", \"@eutaxy/spec\"]),\n );\n const errors: SpecError[] = [...moduleSide.errors, ...specSide.errors];\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 // The precondition and the sample both steer the draws, combined per binder.\n const fromSample = s.sample ? hintsOf(s.sample) : new Map<number, Hint>();\n const fromWhen = s.when ? hintsOf(s.when) : new Map<number, Hint>();\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 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 = 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 * The pure TypeScript subset the first-party engines accept, read into a\n * small tree: exported functions over `number`, `boolean` and `string`,\n * the module's own record types, nullable types (`T | null`) and tagged\n * unions of records declared as type aliases, returning any of those;\n * bodies made of `const` bindings, `if` with early returns, `return`, and\n * expressions from arithmetic (`+ - *`), comparisons, `=== !==` (`null`\n * included, which narrows a nullable name in the branch it guards),\n * `&& || !`, the conditional operator, record literals, field reads (on\n * a union, only a field every member has) and calls to the module's own\n * functions. Anything else is `OutsideSubset`, with the construct named:\n * the subset is specified by the contract corpus and widens one\n * characterised class at a time. What each engine takes of it is the\n * engine's business (`restrictModule`).\n */\n\nimport type { Arrow } from \"@eutaxy/spec\";\nimport { type Token, TokenizeError, templateSubstitutions, tokenize } from \"./tokens.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 /** The tagged union this record is a member of, when it is one; its name is then `<union>.<tag>`. */\n readonly union?: string;\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\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 | { 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 | { 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 }\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\n/** A function's header, with the token index its body starts at. */\ninterface Signature {\n readonly name: string;\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n readonly line: number;\n readonly offset: number;\n readonly body: number;\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/** Binary operators by precedence, loosest first; all left-associative here. */\nconst levels: readonly (readonly BinaryOp[])[] = [\n [\"||\"],\n [\"&&\"],\n [\"===\", \"!==\"],\n [\"<\", \"<=\", \">\", \">=\"],\n [\"+\", \"-\"],\n [\"*\"],\n];\n\nclass Reader {\n at = 0;\n readonly tokens: readonly Token[];\n private readonly lineOf: (offset: number) => number;\n constructor(tokens: readonly Token[], lineOf: (offset: number) => number) {\n this.tokens = tokens;\n this.lineOf = lineOf;\n }\n\n peek(n = 0): Token | undefined {\n return this.tokens[this.at + n];\n }\n\n line(t: Token | undefined = this.peek()): number {\n return t ? this.lineOf(t.start) : this.lineOf(this.tokens.at(-1)?.end ?? 0);\n }\n\n fail(what: string, t: Token | undefined = this.peek()): never {\n throw new OutsideSubset(what, this.line(t));\n }\n\n isPunct(text: string, n = 0): boolean {\n const t = this.peek(n);\n return t?.kind === \"punct\" && t.text === text;\n }\n\n isWord(text: string, n = 0): boolean {\n const t = this.peek(n);\n return t?.kind === \"ident\" && t.text === text;\n }\n\n take(): Token {\n const t = this.peek();\n if (!t) this.fail(\"the module ends early\");\n this.at++;\n return t;\n }\n\n expectPunct(text: string): void {\n if (!this.isPunct(text)) this.fail(`expected ${text}, found ${this.peek()?.text ?? \"the end\"}`);\n this.at++;\n }\n\n ident(): string {\n const t = this.peek();\n if (t?.kind !== \"ident\") this.fail(`expected a name, found ${t?.text ?? \"the end\"}`);\n this.at++;\n return t.text;\n }\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/**\n * The value of a string literal token. Simple escapes and `\\xHH`, `\\uHHHH`,\n * `\\u{H…}` are decoded; a line continuation, an octal escape or a lone\n * surrogate (which Lean's strings cannot hold) is outside the subset.\n */\nfunction stringLiteralValue(text: string, r: Reader, t: Token): string {\n const body = text.slice(1, -1);\n let out = \"\";\n for (let i = 0; i < body.length; i++) {\n const c = body[i] as string;\n if (c !== \"\\\\\") {\n out += c;\n continue;\n }\n const e = body[++i];\n const simple: Record<string, string> = {\n n: \"\\n\",\n t: \"\\t\",\n r: \"\\r\",\n b: \"\\b\",\n f: \"\\f\",\n v: \"\\v\",\n \"0\": \"\\0\",\n \"\\\\\": \"\\\\\",\n '\"': '\"',\n \"'\": \"'\",\n };\n if (e !== undefined && e in simple && !(e === \"0\" && /[0-9]/.test(body[i + 1] ?? \"\"))) {\n out += simple[e];\n continue;\n }\n if (e === \"x\" && /^[0-9a-fA-F]{2}$/.test(body.slice(i + 1, i + 3))) {\n out += String.fromCharCode(Number.parseInt(body.slice(i + 1, i + 3), 16));\n i += 2;\n continue;\n }\n if (e === \"u\") {\n const m = /^\\{([0-9a-fA-F]{1,6})\\}|^([0-9a-fA-F]{4})/.exec(body.slice(i + 1));\n if (m) {\n const code = Number.parseInt((m[1] ?? m[2]) as string, 16);\n if (code > 0x10ffff) r.fail(`a code point escape beyond U+10FFFF in a string literal`, t);\n out += String.fromCodePoint(code);\n i += m[0].length;\n continue;\n }\n }\n r.fail(`an escape sequence \\\\${e ?? \"\"} in a string literal`, t);\n }\n if (hasLoneSurrogate(out))\n r.fail(\"a string literal with a lone surrogate, which Lean's strings cannot hold\", t);\n return out;\n}\n\n/** Record types the module declares but the subset does not take, with why. */\ntype BadRecords = ReadonlyMap<string, string>;\n\n/** The module's declared types, as the reader resolves names. */\nexport interface Declared {\n readonly records: ReadonlySet<string>;\n /** The records themselves, for a union naming its members. */\n readonly recordsByName?: ReadonlyMap<string, RecordType>;\n /** Type aliases to a type the subset reads (`type Status = \"a\" | \"b\"`, `type Maybe = T | null`) and the unions by name. */\n readonly aliases: ReadonlyMap<string, SubsetType>;\n}\n\n/** One alternative of a type expression, before the union is classified. */\ntype Alternative =\n | { readonly kind: \"type\"; readonly type: SubsetType; readonly token: Token }\n | { readonly kind: \"literal\"; readonly value: string | boolean; readonly token: Token }\n | { readonly kind: \"null\"; readonly token: Token };\n\n/** A type annotation: one alternative, or a union of them, read in full. */\nfunction typeAnnotation(r: Reader, declared: Declared, bad: BadRecords = new Map()): SubsetType {\n const first = r.peek();\n const alternatives: Alternative[] = [];\n if (r.isPunct(\"|\")) r.at++;\n for (;;) {\n alternatives.push(listed(r, declared, bad));\n if (!r.isPunct(\"|\")) break;\n r.at++;\n }\n if (r.isPunct(\"[\") || r.isPunct(\"<\") || r.isPunct(\"&\"))\n r.fail(\n `type …${r.peek()?.text}… (generics, intersections and index access are outside the subset; an array is readonly T[] or T[])`,\n );\n return classify(alternatives, r, first);\n}\n\n/**\n * One alternative with its `[]` suffixes, each a list of it, or\n * `readonly` before one that has them; a parenthesized type is one\n * alternative. Only a type is listed: `\"a\"[]` and `null[]` are not read.\n */\nfunction listed(r: Reader, declared: Declared, bad: BadRecords): Alternative {\n const start = r.peek();\n const readonly = r.isWord(\"readonly\");\n if (readonly) r.at++;\n let a: Alternative;\n if (r.isPunct(\"(\")) {\n const open = r.take();\n a = { kind: \"type\", type: typeAnnotation(r, declared, bad), token: open };\n r.expectPunct(\")\");\n } else a = alternative(r, declared, bad);\n let lists = 0;\n while (r.isPunct(\"[\") && r.isPunct(\"]\", 1)) {\n if (a.kind !== \"type\")\n r.fail(\"an array of literals or null (declare its element type)\", a.token);\n r.at += 2;\n a = { kind: \"type\", type: { kind: \"list\", element: a.type }, token: a.token };\n lists++;\n }\n if (readonly && lists === 0) r.fail(\"readonly before a type that is not an array\", start);\n if (a.kind === \"type\" && start && r.isPunct(\"[\")) r.fail(\"index access in a type\", r.peek());\n return a;\n}\n\nfunction alternative(r: Reader, declared: Declared, bad: BadRecords): Alternative {\n const t = r.take();\n if (t.kind === \"string\")\n return { kind: \"literal\", value: stringLiteralValue(t.text, r, t), token: t };\n if (t.kind !== \"ident\") r.fail(`a type that is not a name: ${t.text}`, t);\n if (t.text === \"null\") return { kind: \"null\", token: t };\n if (t.text === \"true\" || t.text === \"false\")\n return { kind: \"literal\", value: t.text === \"true\", token: t };\n if (t.text === \"undefined\") r.fail(\"undefined in a type (the subset has null)\", t);\n const why = bad.get(t.text);\n if (why !== undefined) r.fail(`type ${t.text} is outside the subset: ${why}`, t);\n if (t.text === \"number\") return { kind: \"type\", type: { kind: \"int\" }, token: t };\n if (t.text === \"boolean\") return { kind: \"type\", type: { kind: \"bool\" }, token: t };\n if (t.text === \"string\") return { kind: \"type\", type: { kind: \"string\" }, token: t };\n if (declared.records.has(t.text))\n return { kind: \"type\", type: { kind: \"record\", name: t.text }, token: t };\n const alias = declared.aliases.get(t.text);\n if (alias) return { kind: \"type\", type: alias, token: t };\n if (t.text === \"Array\" || t.text === \"ReadonlyArray\")\n r.fail(`${t.text}<…> (the subset spells an array readonly T[] or T[])`, t);\n r.fail(\n `type ${t.text} (the subset has number, boolean, string, null, and the module's own record types, unions and aliases)`,\n t,\n );\n}\n\n/**\n * The type a list of alternatives names: a single type; string literals as\n * `string` (the proof covers every string, more than the type admits);\n * either with `null` as nullable. Several records are a tagged union only\n * when declared as an alias, where `unionAt` classifies them.\n */\nfunction classify(\n alternatives: readonly Alternative[],\n r: Reader,\n at: Token | undefined,\n): SubsetType {\n const nulls = alternatives.filter((a) => a.kind === \"null\");\n const literals = alternatives.filter(\n (a): a is Extract<Alternative, { kind: \"literal\" }> => a.kind === \"literal\",\n );\n const types = alternatives.filter(\n (a): a is Extract<Alternative, { kind: \"type\" }> => a.kind === \"type\",\n );\n let base: SubsetType | undefined;\n if (literals.length > 0 && types.length === 0) {\n const kinds = new Set(literals.map((l) => typeof l.value));\n if (kinds.size > 1) r.fail(\"a union mixing string and boolean literals\", at);\n base =\n literals[0]?.value === true || literals[0]?.value === false\n ? { kind: \"bool\" }\n : { kind: \"string\" };\n } else if (types.length === 1 && literals.length === 0)\n base = (types[0] as (typeof types)[number]).type;\n else if (types.length === 0 && literals.length === 0)\n r.fail(\"null alone is not a type the subset takes\", at);\n else\n r.fail(\n \"a union of several types (a tagged union of records is read only where it is declared as a type alias)\",\n at,\n );\n if (!base) r.fail(\"an empty type\", at);\n if (base.kind === \"nullable\" && nulls.length > 0) return base;\n if (base.kind === \"null\") r.fail(\"null alone is not a type the subset takes\", at);\n return nulls.length > 0 ? { kind: \"nullable\", inner: base } : base;\n}\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/** The fields of the `{ … }` at the reader; a literal-typed field keeps its literal. */\nfunction fieldsAt(r: Reader, declared: Declared): Field[] {\n r.expectPunct(\"{\");\n const fields: Field[] = [];\n while (!r.isPunct(\"}\")) {\n if (r.isWord(\"readonly\")) r.at++;\n const fname = r.ident();\n if (r.isPunct(\"?\")) r.fail(`optional field ${fname}`);\n if (structureNames.has(fname)) r.fail(`field ${fname} takes a name Lean's structures reserve`);\n if (fname === \"__proto__\") r.fail(\"a field named __proto__, which JavaScript treats specially\");\n r.expectPunct(\":\");\n const literalToken = r.peek();\n const type = typeAnnotation(r, declared);\n // One literal alone (`ok: true`, `type: \"locked\"`): a tag; a union of literals is its base type.\n const alone = r.peek(-1) === literalToken;\n const literal = !alone\n ? undefined\n : literalToken?.kind === \"string\" && type.kind === \"string\"\n ? stringLiteralValue(literalToken.text, r, literalToken)\n : literalToken?.kind === \"ident\" &&\n (literalToken.text === \"true\" || literalToken.text === \"false\") &&\n type.kind === \"bool\"\n ? literalToken.text === \"true\"\n : undefined;\n fields.push({ name: fname, type, ...(literal === undefined ? {} : { literal }) });\n if (r.isPunct(\";\") || r.isPunct(\",\")) r.at++;\n }\n r.expectPunct(\"}\");\n return fields;\n}\n\n/** What a type declaration at the reader declares. */\nexport type Declaration =\n | { readonly kind: \"record\"; readonly record: RecordType }\n | { readonly kind: \"alias\"; readonly name: string; readonly type: SubsetType }\n | {\n readonly kind: \"union\";\n readonly union: UnionType;\n readonly members: readonly RecordType[];\n };\n\n/**\n * `interface Name { … }`, `type Name = { … }`, `type Name = <type>` or\n * `type Name = A | B | { … }` at the reader, after any `export`. A union of\n * records needs a tag: a field every member has, literal-typed, with a\n * different literal in each.\n */\nfunction declarationAt(r: Reader, declared: Declared): Declaration | undefined {\n const start = r.at;\n if (r.isWord(\"export\")) r.at++;\n const alias = r.isWord(\"type\");\n if (!r.isWord(\"interface\") && !alias) {\n r.at = start;\n return undefined;\n }\n r.at++;\n const name = r.ident();\n if (r.isPunct(\"<\")) r.fail(\"type parameters on a type declaration\", r.peek());\n if (!alias) {\n if (r.isWord(\"extends\")) r.fail(\"interface inheritance\", r.peek());\n const fields = fieldsAt(r, declared);\n if (r.isPunct(\";\")) r.at++;\n return { kind: \"record\", record: { name, fields } };\n }\n r.expectPunct(\"=\");\n if (r.isPunct(\"|\")) r.at++;\n // Alternatives: inline records, declared records, literals, null; a tagged union when several are records.\n const inline: RecordType[] = [];\n const named: string[] = [];\n const others: Alternative[] = [];\n const at = r.peek();\n for (;;) {\n if (r.isPunct(\"{\"))\n inline.push({\n name: `${name}.${inline.length + named.length}`,\n fields: fieldsAt(r, declared),\n });\n else {\n const a = alternative(r, declared, new Map());\n if (a.kind === \"type\" && a.type.kind === \"record\") named.push(a.type.name);\n else others.push(a);\n }\n if (!r.isPunct(\"|\")) break;\n r.at++;\n }\n if (r.isPunct(\";\")) r.at++;\n const recordCount = inline.length + named.length;\n if (recordCount === 0) return { kind: \"alias\", name, type: classify(others, r, at) };\n if (others.some((o) => o.kind !== \"null\")) r.fail(\"a union mixing records with other types\", at);\n if (recordCount === 1 && inline.length === 1) {\n const only = inline[0] as RecordType;\n if (others.length > 0)\n r.fail(\n `${name}: a nullable record type is written on the parameter, not declared as an alias`,\n at,\n );\n return { kind: \"record\", record: { name, fields: only.fields } };\n }\n if (recordCount === 1) {\n const type: SubsetType = { kind: \"record\", name: named[0] as string };\n return {\n kind: \"alias\",\n name,\n type: others.length > 0 ? { kind: \"nullable\", inner: type } : type,\n };\n }\n if (others.length > 0)\n r.fail(\n `${name}: a union of records with null is written as the union, then | null, on the parameter`,\n at,\n );\n // Named members are the module's records as they are; inline members become records of the union.\n const memberRecords: RecordType[] = [...inline];\n const memberNames = [...inline.map((m) => m.name), ...named];\n const lookup = (n: string): RecordType | undefined =>\n memberRecords.find((m) => m.name === n) ?? declared.recordsByName?.get(n);\n const first = lookup(memberNames[0] as string);\n if (!first) r.fail(`${name}: member ${memberNames[0]} is not a record the subset read`, at);\n const tags = first.fields\n .filter((f) => f.literal !== undefined)\n .map((f) => f.name)\n .filter((tag) =>\n memberNames.every((m) => {\n const rec = lookup(m);\n return rec?.fields.some((f) => f.name === tag && f.literal !== undefined);\n }),\n )\n .filter((tag) => {\n const values = memberNames.map((m) => lookup(m)?.fields.find((f) => f.name === tag)?.literal);\n return new Set(values.map((v) => JSON.stringify(v))).size === values.length;\n });\n const tag = tags[0];\n if (tag === undefined)\n r.fail(\n `${name}: a union of records without a tag (a literal-typed field every member has, different in each)`,\n at,\n );\n const members = memberNames.map((m) => {\n const rec = lookup(m) as RecordType;\n const value = rec.fields.find((f) => f.name === tag)?.literal as string | boolean;\n return { tag: value, record: m };\n });\n // Inline members are named by their tag, so the constructor names read: `Outcome.true`, `Refused.locked`.\n const renamed = new Map(\n inline.map((m, i) => [\n m.name,\n `${name}.${String((members[i] as (typeof members)[number]).tag)}`,\n ]),\n );\n const finalMembers = members.map((m) => ({ ...m, record: renamed.get(m.record) ?? m.record }));\n const finalRecords = inline.map((m) => ({\n ...m,\n name: renamed.get(m.name) as string,\n union: name,\n }));\n return { kind: \"union\", union: { name, tag, members: finalMembers }, members: finalRecords };\n}\n\n/** Skip a balanced bracket group starting at the reader. */\nfunction skipGroup(r: Reader): void {\n const open = r.take();\n const close = { \"(\": \")\", \"[\": \"]\", \"{\": \"}\" }[open.text];\n let depth = 1;\n while (depth > 0) {\n const t = r.take();\n if (t.kind !== \"punct\") continue;\n if (t.text === open.text) depth++;\n else if (t.text === close) depth--;\n }\n}\n\n/**\n * Whether the `function` token at `i` starts a declaration: at the start of\n * the module or after a statement end, with `export` and `async` allowed in\n * front. A `function` after `=`, `(`, `,`, `return` or `:` is an\n * expression, whose name is its own, not the module's.\n */\nfunction isDeclaration(\n tokens: readonly Token[],\n i: number,\n lineOf: (offset: number) => number,\n): boolean {\n let k = i - 1;\n while (\n tokens[k]?.kind === \"ident\" &&\n [\"async\", \"export\", \"default\"].includes(tokens[k]?.text ?? \"\")\n )\n k--;\n const before = tokens[k];\n if (before === undefined) return true;\n if (before.kind === \"punct\" && (before.text === \";\" || before.text === \"}\")) return true;\n // A line break ends the previous statement (automatic semicolon insertion) unless that statement\n // is unfinished: an operator, an open bracket or a keyword still waiting for its operand.\n if (lineOf(before.end) === lineOf(tokens[i]?.start ?? 0)) return false;\n if (before.kind === \"punct\") return [\")\", \"]\", \"++\", \"--\"].includes(before.text);\n if (before.kind === \"ident\")\n return !\"return typeof void new else case in of do yield await delete instanceof throw export default async\"\n .split(\" \")\n .includes(before.text);\n return true; // a literal\n}\n\n/**\n * Names used as values anywhere in the token stream, with the line of the\n * first use: a bare identifier that is not being called (`f(`), not a\n * property (`o.f`), not an object key (`{ f: … }`) and not the name in its\n * own declaration (`function f`, `const f`). A function used that way may\n * be reassigned, wrapped, aliased or passed on, so what runs under its name\n * is not what its declaration says; one rule covers every assignment form\n * (`f = …`, `f! = …`, `f as T = …`, `[f] = …`, `for (f of …)`) and the\n * aliases besides. Template substitutions are code too and are scanned.\n */\nfunction valueUses(\n tokens: readonly Token[],\n lineOf: (offset: number) => number,\n): Map<string, number> {\n const out = new Map<string, number>();\n const isPunct = (t: Token | undefined, text: string) => t?.kind === \"punct\" && t.text === text;\n tokens.forEach((t, i) => {\n if (t.kind === \"template\") {\n for (const sub of templateSubstitutions(t.text))\n for (const [name, line] of valueUses(tokenize(sub), () => lineOf(t.start)))\n if (!out.has(name)) out.set(name, line);\n return;\n }\n if (t.kind !== \"ident\") return;\n const before = tokens[i - 1];\n const after = tokens[i + 1];\n if (isPunct(after, \"(\")) return; // a call\n if (isPunct(before, \".\") || isPunct(before, \"?.\")) return; // a property of something else\n // An object key, or a type's member (`readonly attempts: number;`), is no use of a value.\n if (\n isPunct(after, \":\") &&\n (isPunct(before, \"{\") ||\n isPunct(before, \",\") ||\n isPunct(before, \";\") ||\n (before?.kind === \"ident\" && before.text === \"readonly\"))\n )\n return;\n if (before?.kind === \"ident\" && [\"function\", \"const\", \"let\", \"var\"].includes(before.text))\n return;\n if (!out.has(t.text)) out.set(t.text, lineOf(t.start));\n });\n return out;\n}\n\n/** The line of the first token matching, template substitutions included (recursively). */\nfunction firstLine(\n tokens: readonly Token[],\n lineOf: (offset: number) => number,\n matches: (t: Token, before: Token | undefined) => boolean,\n): number | undefined {\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i] as Token;\n if (t.kind === \"template\") {\n for (const sub of templateSubstitutions(t.text)) {\n let inner: Token[];\n try {\n inner = tokenize(sub);\n } catch (err) {\n if (!(err instanceof TokenizeError)) throw err;\n return lineOf(t.start); // what cannot be read cannot be cleared\n }\n if (firstLine(inner, () => lineOf(t.start), matches) !== undefined) return lineOf(t.start);\n }\n continue;\n }\n if (matches(t, tokens[i - 1])) return lineOf(t.start);\n }\n return undefined;\n}\n\n/** The line of the first `eval` that is not a property of something else, template substitutions included. */\nfunction mentionsEval(\n tokens: readonly Token[],\n lineOf: (offset: number) => number,\n): number | undefined {\n return firstLine(\n tokens,\n lineOf,\n (t, before) =>\n t.kind === \"ident\" &&\n t.text === \"eval\" &&\n !(before?.kind === \"punct\" && (before.text === \".\" || before.text === \"?.\")),\n );\n}\n\n/** Words that start a declaration at module level, where a declaration the reader skips must stop. */\nconst declarationStarts = new Set(\n \"export import function interface type const let var class enum declare async\".split(\" \"),\n);\n\n/** Skip the rest of a declaration the subset does not take: to its `;`, or to the next declaration. */\nfunction skipDeclaration(r: Reader): void {\n while (r.at < r.tokens.length) {\n const t = r.peek() as Token;\n if (t.kind === \"punct\" && t.text === \";\") {\n r.at++;\n return;\n }\n if (t.kind === \"punct\" && [\"(\", \"[\", \"{\"].includes(t.text)) {\n skipGroup(r);\n continue;\n }\n if (t.kind === \"ident\" && declarationStarts.has(t.text)) return;\n r.at++;\n }\n}\n\nclass FunctionParser {\n private readonly r: Reader;\n private readonly records: ReadonlyMap<string, RecordType>;\n private readonly functions: ReadonlySet<string>;\n /** Every function the module declares, in the subset or not, for messages. */\n private readonly declared: ReadonlySet<string>;\n private readonly badRecords: BadRecords;\n /** For a spec file's arrow: its local names for the module's functions (the keys are what `declared` and `functions` hold). */\n private readonly aliases: ReadonlyMap<string, string> | undefined;\n /** The module's type aliases and unions, by name. */\n private readonly typeAliases: ReadonlyMap<string, SubsetType>;\n readonly signatures = new Map<string, CalleeSignature>();\n constructor(\n r: Reader,\n records: ReadonlyMap<string, RecordType>,\n functions: ReadonlySet<string>,\n badRecords: BadRecords = new Map(),\n declared: ReadonlySet<string> = functions,\n aliases?: ReadonlyMap<string, string>,\n typeAliases: ReadonlyMap<string, SubsetType> = new Map(),\n ) {\n this.r = r;\n this.records = records;\n this.functions = functions;\n this.badRecords = badRecords;\n this.declared = declared;\n this.aliases = aliases;\n this.typeAliases = typeAliases;\n }\n\n private get types(): Declared {\n return {\n records: new Set(this.records.keys()),\n recordsByName: this.records,\n aliases: this.typeAliases,\n };\n }\n\n private get ctx(): TypeContext {\n return { records: this.records, signatures: this.signatures };\n }\n\n /** `export function name(params): Type` at the reader, up to and including the body's `{`. */\n signature(): Signature {\n const r: Reader = this.r;\n const line = r.line();\n if (r.isWord(\"export\")) r.at++;\n if (r.isWord(\"async\")) r.fail(\"an async function (core functions are synchronous)\");\n if (!r.isWord(\"function\")) r.fail(`a declaration that is not a function: ${r.peek()?.text}`);\n r.at++;\n if (r.isPunct(\"*\")) r.fail(\"a generator function\");\n const name = r.ident();\n if (r.isPunct(\"<\")) r.fail(\"type parameters\");\n const offset = r.peek()?.start ?? -1;\n r.expectPunct(\"(\");\n const params: Param[] = [];\n while (!r.isPunct(\")\")) {\n if (r.isPunct(\"{\") || r.isPunct(\"[\")) r.fail(\"a destructured parameter\");\n if (r.isPunct(\"...\")) r.fail(\"a rest parameter\");\n const pname = r.ident();\n // `this: T` annotates the receiver and is erased; it is no argument the function is called with.\n if (pname === \"this\") r.fail(\"a this parameter (the receiver is not modelled)\");\n if (r.isPunct(\"?\")) r.fail(`optional parameter ${pname}`);\n if (!r.isPunct(\":\")) r.fail(`parameter ${pname} without a type`);\n r.at++;\n const type = typeAnnotation(r, this.types, this.badRecords);\n if (r.isPunct(\"=\")) r.fail(`a default value for ${pname}`);\n params.push({ name: pname, type });\n if (r.isPunct(\",\")) r.at++;\n }\n r.expectPunct(\")\");\n if (!r.isPunct(\":\"))\n r.fail(`${name} without a return type (the subset needs it to name the record returned)`);\n r.at++;\n const returns = typeAnnotation(r, this.types, this.badRecords);\n r.expectPunct(\"{\");\n return { name, params, returns, line, offset, body: r.at };\n }\n\n /** The function, its body read from where the signature stopped. */\n declaration(sig: Signature): SubsetFunction {\n this.r.at = sig.body;\n const scope = new Map(sig.params.map((p) => [p.name, p.type]));\n // Null checks narrow the names they guard in the branches they guard, before anything is typed.\n const body = this.narrowed(this.block(scope, sig.returns), scope);\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 = this.typeOfExpr(body, scope);\n if (!fits(actual, sig.returns, this.ctx))\n this.r.fail(\n `${sig.name} returns a ${describe(actual)} but declares ${describe(sig.returns)}`,\n );\n return {\n name: sig.name,\n params: sig.params,\n returns: sig.returns,\n body,\n line: sig.line,\n offset: sig.offset,\n };\n }\n\n /**\n * The statements up to the closing `}` as one expression: `const` becomes\n * `let`, `if (c) return a; rest` becomes a conditional, and the last\n * statement must return. Every path ends in a `return`.\n */\n /** A statement block's statements up to its `}`, for an arrow's block body. */\n blockBody(scope: Map<string, SubsetType>, returns: SubsetType): Expr {\n return this.block(scope, returns);\n }\n\n /** The expression with `narrow` nodes inserted where a null check guards a nullable name. */\n narrowed(e: Expr, scope: ReadonlyMap<string, SubsetType>): Expr {\n return insertNarrows(e, scope, this.ctx, (m) => this.r.fail(m));\n }\n\n private block(scope: Map<string, SubsetType>, returns: SubsetType): Expr {\n const r: Reader = this.r;\n if (r.isWord(\"const\")) {\n r.at++;\n const name = r.ident();\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.declared.has(name))\n r.fail(`const ${name} shadows the module's function ${name} in its block`);\n if (scope.has(name)) r.fail(`const ${name} redeclares a name already bound here`);\n let annotated: SubsetType | undefined;\n if (r.isPunct(\":\")) {\n r.at++;\n annotated = typeAnnotation(r, this.types, this.badRecords);\n }\n r.expectPunct(\"=\");\n const value = this.expression(scope);\n if (r.isPunct(\";\")) r.at++;\n // While parsing, 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.block(inner, returns);\n return { kind: \"let\", name, value, body, ...(annotated ? { type: annotated } : {}) };\n }\n if (r.isWord(\"if\")) {\n r.at++;\n r.expectPunct(\"(\");\n const test = this.expression(scope);\n r.expectPunct(\")\");\n const then = this.branch(scope, returns);\n let otherwise: Expr;\n if (r.isWord(\"else\")) {\n r.at++;\n otherwise = this.branch(scope, returns);\n if (!r.isPunct(\"}\")) r.fail(\"statements after an if/else that both return\");\n r.at++; // the block's closing brace, as the return path consumes it\n } else otherwise = this.block(scope, returns);\n return { kind: \"cond\", test, ifTrue: then, ifFalse: otherwise };\n }\n if (r.isWord(\"return\")) {\n const value = this.returned(scope);\n if (!r.isPunct(\"}\")) r.fail(\"statements after a return\");\n r.at++;\n return value;\n }\n if (r.isWord(\"let\") || r.isWord(\"var\")) r.fail(\"a mutable binding (use const)\");\n if (r.isWord(\"for\") || r.isWord(\"while\") || r.isWord(\"do\")) r.fail(\"a loop\");\n if (r.isWord(\"throw\")) r.fail(\"throw\");\n if (r.isWord(\"switch\")) r.fail(\"switch\");\n if (r.isWord(\"try\")) r.fail(\"try\");\n if (r.isPunct(\"}\")) r.fail(\"a path that does not return\");\n r.fail(`statement starting with ${r.peek()?.text}`);\n }\n\n /** An `if` branch: `return e;` or `{ ...statements ending in return }`. */\n private branch(scope: Map<string, SubsetType>, returns: SubsetType): Expr {\n const r: Reader = this.r;\n if (r.isPunct(\"{\")) {\n r.at++;\n return this.block(scope, returns);\n }\n if (!r.isWord(\"return\")) r.fail(\"an if branch that does not return\");\n return this.returned(scope);\n }\n\n /** `return e;` at the reader. A line break after `return` makes JavaScript return undefined, so it is refused. */\n private returned(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const keyword = r.take();\n if (r.isPunct(\";\") || r.isPunct(\"}\")) r.fail(\"a return without a value\", keyword);\n if (r.line() !== r.line(keyword))\n r.fail(\n \"a line break after return (JavaScript inserts a semicolon and returns undefined)\",\n keyword,\n );\n const value = this.expression(scope);\n if (r.isPunct(\";\")) r.at++;\n return value;\n }\n\n /** `xs[0]` just read, with `??` next: `expression` takes it if it is the whole left operand. */\n private pendingIndex: { readonly list: Expr; readonly at: number } | undefined;\n\n expression(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const start = r.at;\n let left = this.binary(scope, 0);\n if (r.isPunct(\"??\")) {\n const pending = this.pendingIndex;\n // The left operand must be `xs[0]` alone: nothing but the list and its index since `start`.\n if (!pending || pending.at !== r.at || left !== pending.list || !this.indexOnly(start))\n r.fail(\n \"?? after anything but xs[0] (write xs[0] ?? fallback, parenthesized where it meets other operators)\",\n );\n this.pendingIndex = undefined;\n r.at++;\n left = { kind: \"headOr\", list: pending.list, fallback: this.binary(scope, 0) };\n if (r.isPunct(\"??\")) r.fail(\"a chain of ??\");\n }\n if (r.isPunct(\"?\")) {\n r.at++;\n const then = this.expression(scope);\n r.expectPunct(\":\");\n const otherwise = this.expression(scope);\n return { kind: \"cond\", test: left, ifTrue: then, ifFalse: otherwise };\n }\n return left;\n }\n\n /** Whether the tokens from `start` to here hold no operator outside brackets: an operand and its `[0]`. */\n private indexOnly(start: number): boolean {\n let depth = 0;\n for (let i = start; i < this.r.at; i++) {\n const t = this.r.tokens[i] as Token;\n if (t.kind !== \"punct\") continue;\n if (t.text === \"(\" || t.text === \"[\" || t.text === \"{\") depth++;\n else if (t.text === \")\" || t.text === \"]\" || t.text === \"}\") depth--;\n else if (depth === 0 && t.text !== \".\") return false;\n }\n return true;\n }\n\n private binary(scope: ReadonlyMap<string, SubsetType>, level: number): Expr {\n if (level >= levels.length) return this.unary(scope);\n let left = this.binary(scope, level + 1);\n const ops = levels[level] as readonly BinaryOp[];\n for (;;) {\n const t = this.r.peek();\n if (t?.kind !== \"punct\" || !ops.includes(t.text as BinaryOp)) {\n if (\n t?.kind === \"punct\" &&\n [\"==\", \"!=\", \"/\", \"%\", \"**\", \"<<\", \">>\", \"&\", \"|\", \"^\"].includes(t.text)\n )\n this.r.fail(`the ${t.text} operator`, t);\n return left;\n }\n this.r.at++;\n const right = this.binary(scope, level + 1);\n left = { kind: \"binary\", op: t.text as BinaryOp, left, right };\n }\n }\n\n private unary(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n if (r.isPunct(\"!\")) {\n r.at++;\n return { kind: \"not\", operand: this.unary(scope) };\n }\n if (r.isPunct(\"-\")) {\n r.at++;\n const operand = this.unary(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 (r.isPunct(\"+\")) r.fail(\"unary plus\");\n if (r.isWord(\"typeof\") || r.isWord(\"void\") || r.isWord(\"await\") || r.isWord(\"new\"))\n r.fail(`the ${r.peek()?.text} operator`);\n return this.postfix(scope, this.primary(scope));\n }\n\n private postfix(scope: ReadonlyMap<string, SubsetType>, base: Expr): Expr {\n const r: Reader = this.r;\n let e = base;\n for (;;) {\n if (r.isPunct(\".\")) {\n r.at++;\n const field = r.ident();\n if (r.isPunct(\"(\")) {\n e = this.method(scope, e, field);\n continue;\n }\n e = { kind: \"field\", object: e, field };\n continue;\n }\n if (r.isPunct(\"?.\")) r.fail(\"optional chaining\");\n if (r.isPunct(\"[\")) {\n // `xs[0] ?? fallback` only: any other index may be past the end, which is undefined.\n const open = r.take();\n const index = r.take();\n if (index.kind !== \"number\" || index.text !== \"0\" || !r.isPunct(\"]\"))\n r.fail(\"index access other than xs[0] ?? fallback\", open);\n r.at++;\n // `??` binds looser than every other operator: `expression` pairs it with this index, and\n // only when the index is all of its left operand (`a === xs[0] ?? b` is `(a === xs[0]) ?? b`).\n if (!r.isPunct(\"??\"))\n r.fail(\"xs[0] without ?? fallback (it is undefined on an empty list)\", open);\n this.pendingIndex = { list: e, at: r.at };\n return e;\n }\n if (r.isPunct(\"(\")) {\n // A binder or local named like a function shadows it: the call is to a number, which throws.\n if (e.kind === \"var\" && scope.has(e.name))\n r.fail(`a call to ${e.name}, which names a value here, not the module's function`);\n if (e.kind !== \"var\" || !this.functions.has(e.name))\n r.fail(\n e.kind !== \"var\"\n ? \"a call to a computed callee\"\n : this.declared.has(e.name)\n ? `a call to ${e.name}, which is outside the subset`\n : this.aliases\n ? `a call to ${e.name}, which is not a function imported from the module beside the spec file`\n : `a call to ${e.name}, which this module does not declare`,\n );\n r.at++;\n const args: Expr[] = [];\n while (!r.isPunct(\")\")) {\n args.push(this.expression(scope));\n if (r.isPunct(\",\")) r.at++;\n }\n r.at++;\n // A spec file's local name for a module function resolves to the function.\n e = { kind: \"call\", callee: this.aliases?.get(e.name) ?? e.name, args };\n continue;\n }\n if (r.isWord(\"as\") || r.isWord(\"satisfies\")) r.fail(`the ${r.peek()?.text} operator`);\n return e;\n }\n }\n\n private primary(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const t = r.take();\n switch (t.kind) {\n case \"number\":\n if (!/^[0-9](_?[0-9])*$/.test(t.text))\n r.fail(`the numeric literal ${t.text} (integers in decimal only)`, t);\n return { kind: \"int\", value: t.text.replace(/_/g, \"\") };\n case \"string\":\n return { kind: \"string\", value: stringLiteralValue(t.text, r, t) };\n case \"template\":\n r.fail(\"a template literal\", t);\n break;\n case \"regex\":\n r.fail(\"a regular expression\", t);\n break;\n case \"ident\":\n if (t.text === \"true\" || t.text === \"false\")\n return { kind: \"bool\", value: t.text === \"true\" };\n if (t.text === \"null\") return { kind: \"null\" };\n if (t.text === \"undefined\") r.fail(\"undefined (the subset has null)\", t);\n if (\n t.text === \"Number\" &&\n !scope.has(\"Number\") &&\n !this.declared.has(\"Number\") &&\n r.isPunct(\".\") &&\n r.isWord(\"isInteger\", 1) &&\n r.isPunct(\"(\", 2)\n ) {\n r.at += 3;\n const operand = this.expression(scope);\n r.expectPunct(\")\");\n return { kind: \"isInteger\", operand };\n }\n if (scope.has(t.text) || this.declared.has(t.text)) return { kind: \"var\", name: t.text };\n r.fail(\n this.aliases\n ? `${t.text}, which is neither a parameter, a const nor a function imported from the module beside the spec file`\n : `${t.text}, which is neither a parameter, a const nor a function of this module`,\n t,\n );\n break;\n case \"punct\":\n if (t.text === \"(\") {\n const e = this.expression(scope);\n r.expectPunct(\")\");\n return e;\n }\n if (t.text === \"{\") return this.record(scope);\n if (t.text === \"[\") return this.listLiteral(scope);\n r.fail(`unexpected ${t.text}`, t);\n break;\n default:\n r.fail(`unexpected ${t.text}`, t);\n }\n }\n\n /** `[a, b]` or `[a, b, ...rest]`, the `[` taken. */\n private listLiteral(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const items: Expr[] = [];\n let rest: Expr | undefined;\n while (!r.isPunct(\"]\")) {\n if (rest) r.fail(\"a spread that is not last in an array literal\");\n if (r.isPunct(\"...\")) {\n r.at++;\n rest = this.expression(scope);\n } else items.push(this.expression(scope));\n if (r.isPunct(\",\")) r.at++;\n else if (!r.isPunct(\"]\")) r.fail(`unexpected ${r.peek()?.text} in an array literal`);\n }\n r.at++;\n return { kind: \"list\", items, ...(rest ? { rest } : {}) };\n }\n\n /** `(a, b) => body` or `a => body`, an expression body only; the names it binds go into scope. */\n private callback(\n scope: ReadonlyMap<string, SubsetType>,\n arity: number,\n what: string,\n ): { names: string[]; body: Expr } {\n const r: Reader = this.r;\n const names: string[] = [];\n if (r.isPunct(\"(\")) {\n r.at++;\n while (!r.isPunct(\")\")) {\n names.push(r.ident());\n if (r.isPunct(\":\")) r.fail(`a type annotation on ${what}'s parameter`);\n if (r.isPunct(\",\")) r.at++;\n }\n r.at++;\n } else names.push(r.ident());\n if (names.length === 0 || names.length > arity)\n r.fail(`${what} takes a callback of 1 to ${arity} parameter(s), given ${names.length}`);\n for (const n of names)\n if (scope.has(n) || this.declared.has(n))\n r.fail(`${what}'s parameter ${n} shadows a name already bound here`);\n if (new Set(names).size !== names.length) r.fail(`${what}'s parameters repeat a name`);\n r.expectPunct(\"=>\");\n if (r.isPunct(\"{\")) r.fail(`a block body in ${what}'s callback (write an expression)`);\n const inner = new Map(scope);\n for (const n of names) inner.set(n, { kind: \"null\" });\n return { names, body: this.expression(inner) };\n }\n\n /** A method call on a list: slice(1), map, flatMap, every, some, reduce; the `(` not yet taken. */\n private method(scope: ReadonlyMap<string, SubsetType>, list: Expr, name: string): Expr {\n const r: Reader = this.r;\n r.at++;\n let e: Expr;\n if (name === \"slice\") {\n const one = r.take();\n if (one.kind !== \"number\" || one.text !== \"1\")\n r.fail(\"slice with an argument other than 1\", one);\n e = { kind: \"tail\", list };\n } else if (name === \"map\" || name === \"flatMap\" || name === \"every\" || name === \"some\") {\n const { names, body } = this.callback(scope, 2, name);\n e = {\n kind: \"iterate\",\n op: name,\n list,\n item: names[0] as string,\n ...(names[1] === undefined ? {} : { index: names[1] }),\n body,\n };\n } else if (name === \"reduce\") {\n const { names, body } = this.callback(scope, 2, \"reduce\");\n if (names.length !== 2) r.fail(\"reduce takes a callback of (accumulator, item)\");\n r.expectPunct(\",\");\n const init = this.expression(scope);\n e = { kind: \"fold\", list, acc: names[0] as string, item: names[1] as string, body, init };\n } else\n r.fail(`the method ${name} (the subset has slice(1), map, flatMap, every, some and reduce)`);\n if (r.isPunct(\",\")) r.at++;\n r.expectPunct(\")\");\n return e;\n }\n\n private record(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const fields: { name: string; value: Expr }[] = [];\n while (!r.isPunct(\"}\")) {\n if (r.isPunct(\"...\")) r.fail(\"spread in a record literal\");\n if (r.isPunct(\"[\")) r.fail(\"a computed key\");\n const t = r.take();\n if (t.kind !== \"ident\") r.fail(`a key that is not a name: ${t.text}`, t);\n if (t.text === \"__proto__\")\n r.fail(\"a __proto__ key, which sets the prototype, not a field\", t);\n if (r.isPunct(\"(\")) r.fail(`a method ${t.text}`, t);\n if (r.isPunct(\":\")) {\n r.at++;\n fields.push({ name: t.text, value: this.expression(scope) });\n } else {\n if (!scope.has(t.text)) r.fail(`shorthand ${t.text} names nothing in scope`, t);\n fields.push({ name: t.text, value: { kind: \"var\", name: t.text } });\n }\n if (r.isPunct(\",\")) r.at++;\n }\n r.at++;\n return { kind: \"record\", fields };\n }\n\n typeOfExpr(e: Expr, scope: ReadonlyMap<string, SubsetType>): SubsetType {\n return typeOf(e, scope, this.ctx, (m) => this.r.fail(m));\n }\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\" && ctx.records.get(actual.name)?.union === 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 const ua = ctx.records.get(a.name)?.union;\n if (ua !== undefined && ua === ctx.records.get(b.name)?.union)\n return { kind: \"union\", name: ua };\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 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/**\n * `narrow` nodes inserted where a null check guards: in a conditional's\n * branches, and in the right operand of `&&` and `||`, for each nullable\n * name the test shows to be non-null 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 const wrap = (\n body: Expr,\n names: readonly string[],\n sc: ReadonlyMap<string, SubsetType>,\n ): Expr => {\n const inner = new Map(sc);\n let out = body;\n const nullable = [...new Set(names)].filter((n) => sc.get(n)?.kind === \"nullable\");\n for (const n of nullable) inner.set(n, (sc.get(n) as { inner: SubsetType }).inner);\n out = go(out, inner);\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 \"neg\":\n case \"not\":\n case \"isInteger\":\n return { kind: e.kind, operand: go(e.operand, scope) };\n case \"narrow\":\n return e;\n case \"binary\": {\n const left = go(e.left, scope);\n if (e.op === \"&&\")\n return {\n kind: \"binary\",\n op: e.op,\n left,\n right: wrap(e.right, narrowsOf(left, true), scope),\n };\n if (e.op === \"||\")\n return {\n kind: \"binary\",\n op: e.op,\n left,\n right: wrap(e.right, narrowsOf(left, false), scope),\n };\n return { kind: \"binary\", op: e.op, left, right: go(e.right, scope) };\n }\n case \"cond\": {\n const test = go(e.test, scope);\n return {\n kind: \"cond\",\n test,\n ifTrue: wrap(e.ifTrue, narrowsOf(test, true), scope),\n ifFalse: wrap(e.ifFalse, narrowsOf(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 {\n kind: \"record\",\n fields: e.fields.map((f) => ({ name: f.name, value: go(f.value, scope) })),\n };\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): 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);\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 \"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);\n const b = typeOf(e.ifFalse, scope, ctx, fail);\n const joined = join(a, b, ctx);\n if (!joined)\n fail(\n `the branches of a conditional have different types (${describe(a)} and ${describe(b)})`,\n );\n return joined;\n }\n case \"let\": {\n const inferred = typeOf(e.value, scope, ctx, fail);\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);\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);\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 = [...ctx.records.values()].filter((rec) => rec.union === o.name);\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} (narrowing by the tag is not in the subset yet)`,\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 const byNames = [...ctx.records.values()].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/**\n * A parser 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 */\nfunction parserFor(\n text: string,\n module: SubsetModule,\n aliases?: ReadonlyMap<string, string>,\n): { r: Reader; parser: FunctionParser } {\n let tokens: Token[];\n try {\n tokens = tokenize(text);\n } catch (err) {\n if (!(err instanceof TokenizeError)) throw err;\n throw new OutsideSubset(`could not be tokenized: ${err.message}`, 0);\n }\n const r = new Reader(tokens, () => 0);\n const records = new Map(module.records.map((rec) => [rec.name, rec]));\n const inSubset = new Set(module.functions.map((f) => f.name));\n let functions: ReadonlySet<string>;\n let declared: ReadonlySet<string>;\n if (aliases) {\n declared = new Set(aliases.keys());\n functions = new Set([...aliases].filter(([, fn]) => inSubset.has(fn)).map(([local]) => local));\n } else {\n functions = inSubset;\n declared = new Set([...inSubset, ...module.outside.map((o) => o.name)]);\n }\n const typeAliases = new Map<string, SubsetType>(\n module.unions.map((u) => [u.name, { kind: \"union\", name: u.name }]),\n );\n const parser = new FunctionParser(\n r,\n records,\n functions,\n new Map(),\n declared,\n aliases,\n typeAliases,\n );\n for (const f of module.functions)\n parser.signatures.set(f.name, { params: f.params, returns: f.returns });\n return { r, parser };\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 const { r, parser } = parserFor(text, module, aliases);\n const e = parser.expression(scope);\n if (r.at < r.tokens.length) r.fail(`unexpected ${r.peek()?.text} after the expression`);\n return e;\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.\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 const { r, parser } = parserFor(arrow.body, module, aliases);\n const e = parser.expression(scope);\n if (r.at < r.tokens.length) r.fail(`unexpected ${r.peek()?.text} after the expression`);\n return parser.narrowed(e, scope);\n }\n const { r, parser } = parserFor(`${arrow.body}}`, module, aliases);\n const e = parser.blockBody(new Map(scope), { kind: \"bool\" });\n if (r.at < r.tokens.length) r.fail(`unexpected ${r.peek()?.text} after the block`);\n return parser.narrowed(e, scope);\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 out.add(e.name);\n return boundNames(e.body, out);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\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): Expr {\n const go = (x: Expr): Expr => renameVars(x, names, taken);\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 \"neg\":\n case \"not\":\n case \"isInteger\":\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 {\n kind: \"record\",\n fields: e.fields.map((f) => ({ name: f.name, value: go(f.value) })),\n };\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());\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])),\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);\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),\n };\n }\n case \"fold\": {\n const { inner, bound, scoped } = bindAll([e.acc, e.item], names, taken);\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),\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): { inner: Map<string, string>; bound: string[]; scoped: Set<string> } {\n const inner = new Map(names);\n const targets = new Set(names.values());\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 return callees(e.body, out);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\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 * Read a module: its record types, every function the subset takes (in\n * source order, so callees come before callers) and, for the others, why\n * not. A function calling one outside the subset is outside it too. The\n * names given are what the caller cares about; one the module does not\n * declare at its top level is reported among the others, not thrown.\n */\nexport function readSubset(source: string, functions?: readonly string[]): SubsetModule {\n // Every JavaScript line terminator counts (LF, CR, CRLF as one, U+2028, U+2029): a return\n // followed by any of them returns undefined.\n const lineOf = (offset: number): number => {\n let line = 1;\n for (let i = 0; i < offset && i < source.length; i++) {\n const c = source[i];\n if (c === \"\\r\") {\n line++;\n if (source[i + 1] === \"\\n\") i++;\n } else if (c === \"\\n\" || c === \"\\u2028\" || c === \"\\u2029\") line++;\n }\n return line;\n };\n let tokens: Token[];\n try {\n tokens = tokenize(source);\n } catch (err) {\n // Source the scanner cannot read is source the reader cannot trust: every name asked for is outside.\n if (!(err instanceof TokenizeError)) throw err;\n return {\n records: [],\n unions: [],\n functions: [],\n outside: (functions ?? []).map((name) => ({\n name,\n line: 0,\n message: `the module could not be tokenized: ${err.message}`,\n })),\n };\n }\n const r = new Reader(tokens, lineOf);\n // Pass 1: record types, and where every function declaration starts.\n const records = new Map<string, RecordType>();\n const unions: UnionType[] = [];\n const typeAliases = new Map<string, SubsetType>();\n const declaredTypes = (): Declared => ({\n records: new Set(records.keys()),\n recordsByName: records,\n aliases: typeAliases,\n });\n const badRecords = new Map<string, string>();\n const declared = new Set<string>();\n const assigned = new Map<string, number>();\n const starts: number[] = [];\n while (r.at < tokens.length) {\n const t = r.peek() as Token;\n if (t.kind === \"ident\" && t.text === \"import\") {\n // An import (type-only or not) declares nothing the subset reads.\n r.at++;\n skipDeclaration(r);\n continue;\n }\n if (\n t.kind === \"ident\" &&\n (t.text === \"interface\" || t.text === \"type\" || t.text === \"export\")\n ) {\n const save = r.at;\n try {\n const decl = declarationAt(r, declaredTypes());\n if (decl) {\n if (decl.kind === \"record\") records.set(decl.record.name, decl.record);\n else if (decl.kind === \"alias\") typeAliases.set(decl.name, decl.type);\n else {\n for (const m of decl.members) records.set(m.name, m);\n // A named member is the module's own record, now also a member of the union.\n for (const m of decl.union.members) {\n const rec = records.get(m.record);\n if (rec && rec.union === undefined)\n records.set(m.record, { ...rec, union: decl.union.name });\n else if (rec && rec.union !== decl.union.name)\n // One datatype per record: a record in two unions would need two constructors.\n badRecords.set(\n decl.union.name,\n `${m.record} is already a member of ${rec.union}; a record belongs to one union`,\n );\n }\n if (!badRecords.has(decl.union.name)) {\n unions.push(decl.union);\n typeAliases.set(decl.union.name, { kind: \"union\", name: decl.union.name });\n }\n }\n continue;\n }\n } catch (err) {\n // A record type the subset does not take: noted, so a function using it says why, and skipped.\n if (!(err instanceof OutsideSubset)) throw err;\n r.at = save;\n if (r.isWord(\"export\")) r.at++;\n r.at++;\n // `export type { A }` and friends name no record; a named one is noted so its users say why.\n if (r.peek()?.kind === \"ident\") badRecords.set(r.ident(), err.message);\n skipDeclaration(r);\n continue;\n }\n r.at = save;\n }\n if (t.kind === \"ident\" && t.text === \"function\" && isDeclaration(tokens, r.at, lineOf)) {\n // `function* f` is a generator: its name is recorded so the signature pass can refuse it by name.\n const name = r.isPunct(\"*\", 1) ? r.peek(2) : r.peek(1);\n if (name?.kind === \"ident\") declared.add(name.text);\n // The declaration starts at its modifiers, which the second pass reads (and refuses, for async).\n let start = r.at;\n if (r.isWord(\"async\", start - r.at - 1)) start--;\n if (r.isWord(\"export\", start - r.at - 1)) start--;\n starts.push(start);\n r.at++;\n continue;\n }\n if (t.kind === \"punct\" && [\"(\", \"[\", \"{\"].includes(t.text)) {\n skipGroup(r);\n continue;\n }\n r.at++;\n }\n // A declared function used as a value anywhere in the module (assigned to, aliased, passed on) may not\n // be what its declaration says when called; such a function, and its callers, are outside.\n for (const [name, line] of valueUses(tokens, lineOf)) assigned.set(name, line);\n const outside = new Map<string, OutsideFunction>();\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 // A direct eval can rebind any declaration of the module without naming it, so any mention of `eval`\n // that is not a property of something else (`globalThis.eval` is indirect, and cannot) puts the whole\n // module outside: `eval(…)`, `(eval)(…)`, inside a template substitution alike.\n const evalLine = mentionsEval(tokens, lineOf);\n if (evalLine !== undefined)\n for (const name of declared)\n outside.set(name, {\n name,\n line: evalLine,\n message: \"the module mentions eval directly, which can rebind any of its declarations\",\n });\n // An identifier escape (`\\u0066` for `f`) spells a name the scans above cannot match: nothing is trusted.\n const escapeLine = firstLine(tokens, lineOf, (t) => t.kind === \"punct\" && t.text === \"\\\\\");\n if (escapeLine !== undefined)\n for (const name of declared)\n if (!outside.has(name))\n outside.set(name, {\n name,\n line: escapeLine,\n message:\n \"the module uses an identifier escape sequence (\\\\u…), so its names cannot be matched by spelling\",\n });\n for (const [name, line] of assigned)\n if (declared.has(name) && !outside.has(name))\n outside.set(name, {\n name,\n line,\n message: `${name} is used as a value in the module (not only called), so what runs under its name may not be its declaration`,\n });\n // Pass 2: signatures, so every function's return type is known before any body is read.\n const parser = new FunctionParser(\n r,\n records,\n declared,\n badRecords,\n declared,\n undefined,\n typeAliases,\n );\n const signatures: Signature[] = [];\n for (const start of starts) {\n r.at = start;\n try {\n const sig = parser.signature();\n // Callers of a reassigned function still type-check against its declaration; they are then outside with it.\n parser.signatures.set(sig.name, { params: sig.params, returns: sig.returns });\n if (!outside.has(sig.name)) signatures.push(sig);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n // The name after `function`, past a generator's `*`.\n const head = tokens.slice(start, start + 5);\n const fnAt = head.findIndex((t) => t.kind === \"ident\" && t.text === \"function\");\n const after = head[fnAt + 1]?.text === \"*\" ? head[fnAt + 2] : head[fnAt + 1];\n const name = after?.kind === \"ident\" ? after.text : undefined;\n if (name) outside.set(name, { name, line: err.line, message: err.message });\n }\n }\n // Pass 3: bodies.\n const read = new Map<string, SubsetFunction>();\n for (const sig of signatures) {\n try {\n read.set(sig.name, parser.declaration(sig));\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n outside.set(sig.name, { name: sig.name, line: err.line, message: err.message });\n }\n }\n // A caller of a function outside the subset is outside it too, however many steps away.\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 // Recursion is not in the subset yet: a function reaching itself through its callees 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 // 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 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 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 // 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 (!placed.has(name) && [...callees(fn.body)].every((c) => c === name || placed.has(c))) {\n ordered.push(fn);\n placed.add(name);\n }\n return {\n records: [...records.values()],\n unions,\n functions: ordered,\n outside: [...outside.values()],\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 return [e.body];\n case \"neg\":\n case \"not\":\n case \"isInteger\":\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 return hasNode(e.body, kinds);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\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 bring. */\n bodies: ReadonlySet<Expr[\"kind\"]> = new Set([\"null\", \"narrow\"]),\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 union the engine models but has dropped goes with it: its sort is the union's.\n // An engine that takes no unions keeps the members as records of their own.\n if (takes({ kind: \"union\", name: u.name }) && badRecords.has(`union:${u.name}`))\n for (const m of u.members)\n if (!badRecords.has(m.record)) {\n badRecords.add(m.record);\n changed = true;\n }\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 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 records: module.records.filter((r) => !badRecords.has(r.name)),\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 name. */\nfunction annotations(e: Expr, out: SubsetType[] = []): SubsetType[] {\n if (e.kind === \"let\" && 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 * 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 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 return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? name : `«${name}»`;\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\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 \"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 typed.\n typeOf(e.operand, scope, env.ctx, fail);\n return \"true\";\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 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 * Running Lean over a process boundary. The engine is pinned to one Lean\n * release: `elan` (Lean's toolchain manager) is asked for it by name, and a\n * `lean` found without `elan` must report that version. Nothing is ever\n * downloaded during a check; a missing toolchain is `unavailable`, with the\n * command that installs it. Diagnostics come back as `file:line:col:\n * severity: message` 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\";\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 = `install elan (https://elan.lean-lang.org) and run: elan toolchain install ${leanToolchain}`;\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: through `elan run <toolchain>`\n * when elan is present (and only when it already has the toolchain, so\n * nothing is downloaded), else a bare `lean` of exactly that version.\n */\nexport async function findLean(): Promise<LeanToolchain | { readonly unavailable: string }> {\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}; run: elan toolchain install ${leanToolchain}`,\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}`,\n };\n }\n return { unavailable: `no Lean toolchain found; ${installHint}` };\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}\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 return {\n file,\n lemmas: lemmas.join(\"\\n\").trim(),\n proofs: new Map([...proofs].map(([k, v]) => [k, v.join(\"\\n\").replace(/\\s+$/, \"\")])),\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 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 { existsSync, readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport type {\n ModuleProofs,\n ProofOutcome,\n PropertyProof,\n Prover,\n ProveInput as ProverInput,\n} from \"@eutaxy/prover\";\nimport {\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 { type Emitted, emitModule } from \"./emit.ts\";\nimport { checkLean, findLean, type LeanDiagnostic, leanVersion } from \"./lean.ts\";\nimport {\n axiomsOf,\n provesExactly,\n readSupplied,\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 the module's own, pure and total; nothing outside the module is modelled\",\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 const module = restrictModule(\n readSubset(\n input.source,\n fns.map((f) => f.name),\n ),\n leanTakes,\n \"nullable types and tagged unions are not in the Lean engine's subset yet\",\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`.\n const proofFile = input.specPath?.replace(/\\.ts$/, \".lean\");\n const supplied =\n proofFile !== undefined && existsSync(proofFile)\n ? readSupplied(basename(proofFile), readFileSync(proofFile, \"utf8\"))\n : undefined;\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\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 return { results, lean, specErrors };\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, 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 return /^[A-Za-z~!@$%^&*_+=<>.?/-][A-Za-z0-9~!@$%^&*_+=<>.?/-]*$/.test(name)\n ? name\n : `|${name.replace(/[|\\\\]/g, \"_\")}|`;\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 that is no union member, or of a union. */\n record: (name: string) => symbol(`R_${name}`),\n constructor: (name: string) => symbol(`mk_${name}`),\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 return ident.record(unionOf(t.name, module) ?? t.name);\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\n/** The union a record is a member of, by the record's name. */\nfunction unionOf(record: string, module: SubsetModule): string | undefined {\n return module.records.find((r) => r.name === record)?.union;\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 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 is already of its union's sort.\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 wrapped in `some` when a nullable is wanted and the value is not one.\n const coerce = (x: Expr, want: SubsetType): string => {\n if (x.kind === \"cond\" || x.kind === \"let\" || x.kind === \"narrow\" || x.kind === \"null\")\n return t(x, want);\n const actual = typed(x);\n const inner = t(x, want);\n if (want.kind === \"nullable\" && actual.kind !== \"nullable\" && actual.kind !== \"null\")\n return `(${ident.some(sortName(want.inner, env.module))} ${inner})`;\n return inner;\n };\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)}))) ${term(e.body, inner, env, expected)})`;\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 \"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.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)} ${obj})`;\n return rest === undefined\n ? read\n : `(ite (${tester(ident.constructor(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 return `(let ((${ident.variable(e.name)} ${value})) ${term(e.body, inner, env, expected)})`;\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 (b.kind === \"cond\" || b.kind === \"let\" || b.kind === \"narrow\" || b.kind === \"null\")\n return term(b, scope, e, f.returns);\n const actual = typeOf(b, scope, e.ctx, fail);\n const inner = term(b, scope, e, f.returns);\n return f.returns.kind === \"nullable\" && actual.kind !== \"nullable\" && actual.kind !== \"null\"\n ? `(${ident.some(sortName(f.returns.inner, module))} ${inner})`\n : inner;\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 that is no union member, 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\n .filter((r) => r.union === undefined)\n .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, an option `none` and `some` over its base sort.\n */\nexport function emitDatatypes(module: SubsetModule): string {\n const plain = module.records.filter((r) => r.union === undefined);\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) => constructorOf(module.records.find((r) => r.name === m.record) as RecordType)).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 union the module declares has 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/** The declared union whose members carry these tags with these fields, if any. */\nfunction findUnion(\n members: readonly Extract<SpecType, { kind: \"record\" }>[],\n module: SubsetModule,\n): UnionType | undefined {\n return module.unions.find((u) => {\n if (u.members.length !== members.length) return false;\n return u.members.every((m) => {\n const rec = module.records.find((r) => r.name === m.record);\n if (!rec) return false;\n return members.some(\n (sm) =>\n sm.fields.length === rec.fields.length &&\n sm.fields.every((f) => rec.fields.some((rf) => rf.name === f.name)) &&\n sm.fields.some(\n (f) => f.name === u.tag && f.type.kind === \"literal\" && f.type.value === m.tag,\n ),\n );\n });\n });\n}\n\n/**\n * What a binder's subset type says that its sort does not: a member record\n * is its own constructor, a union's 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 if (rec.union !== undefined) parts.push(`(${tester(ident.constructor(rec.name))} ${target})`);\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 inner = wellFormed(target, { kind: \"record\", name: m.record }, module);\n return inner ?? `(${tester(ident.constructor(m.record))} ${target})`;\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 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(\n (m) =>\n `(and (${tester(ident.constructor(m.record))} ${a}) (${tester(ident.constructor(m.record))} ${b}) ${equal(a, 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.constructor(m.record) === head);\n if (!member) throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);\n return decode(x, { 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: a `z3` on the PATH (or in Homebrew's and the usual local\n * prefixes) must report that version. Nothing is downloaded during a\n * check; a missing 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\";\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 = `install Z3 ${z3Version} (https://github.com/Z3Prover/z3/releases/tag/z3-${z3Version}; Homebrew: brew install z3) so that z3 is on the PATH`;\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/** Candidates for the `z3` executable: `EUTAXY_Z3`, the PATH, then the prefixes package managers install into. */\nexport function candidates(): string[] {\n const fromEnv = process.env[\"EUTAXY_Z3\"];\n return [\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 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 the module's own, pure and total; nothing outside the module is modelled\",\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 ),\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 /** The scenario sets up Workflows: pass the Worker module's exports, where their classes are. */\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 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 options.workflows\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 = options.workflows ? \"handler: worker.default\" : \"handler\";\n const exports = options.workflows ? \", 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/** The import specifiers by which a spec file may name its module: with the `.ts`, bare, or with `.js`. */\nexport function moduleSpecifiers(modulePath: string): string[] {\n const base = basename(modulePath, \".ts\");\n return [`./${base}.ts`, `./${base}`, `./${base}.js`];\n}\n\n/** Read one module and its spec file. */\nexport function readSpecModule(modulePath: string, specPath: string): ModuleSpecs {\n return readSpecs({\n module: readFileSync(modulePath, \"utf8\"),\n spec: readFileSync(specPath, \"utf8\"),\n moduleSpecifiers: moduleSpecifiers(modulePath),\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): 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 reports.push({\n engine: engine.name,\n proofs: await engine.prove({\n source,\n specs: found.specs,\n functions: withSpecs,\n specPath: found.specPath,\n }),\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 const printed =\n o.provers && o.provers.length > 0\n ? { ...(transport.report as object), specs }\n : transport.report;\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 (verdict.kind === \"VIOLATED\" && !o.noRegression) {\n const outPath = o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`);\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\") ? { workflows: true } : {}),\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 * `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 worker thread 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 module that only loads inside workerd gets `UNKNOWN` until an engine\n * reads it.\n */\n\nimport { registerHooks } from \"node:module\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { isMainThread, parentPort, Worker, workerData } from \"node:worker_threads\";\nimport type { SpecVerdict } from \"@eutaxy/core\";\nimport { checkSpecModule, type Prover } from \"@eutaxy/prover\";\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 readonly json: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\ninterface WorkerInput {\n readonly kind: \"eutaxy-report-module\";\n readonly module: SpecModule;\n readonly seed: string;\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 worker: 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 worker: 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 input = isMainThread ? undefined : (workerData as Partial<WorkerInput> | null);\nif (input?.kind === \"eutaxy-report-module\" && input.module && input.seed !== undefined)\n parentPort?.postMessage(await testHere(input.module, input.seed));\n\n/**\n * One module's verdicts at the `TESTED` rung, from a worker thread. 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 worker = new Worker(new URL(import.meta.url), {\n workerData: { kind: \"eutaxy-report-module\", module: m, seed } satisfies WorkerInput,\n stdout: true,\n stderr: true,\n });\n worker.stdout.on(\"data\", (d: Buffer) => stderr(d.toString()));\n worker.stderr.on(\"data\", (d: Buffer) => stderr(d.toString()));\n let settled = false;\n const finish = (verdicts: SpecVerdict[]) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n void worker.terminate();\n done(verdicts);\n };\n const timer = setTimeout(\n () =>\n finish(\n 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 ),\n budgetMs,\n );\n worker.once(\"message\", (verdicts: SpecVerdict[]) => finish(verdicts));\n worker.once(\"error\", (err) =>\n finish(unknownAll(m, \"unavailable\", `the module's worker failed: ${err.message}`)),\n );\n worker.once(\"exit\", (code) =>\n finish(unknownAll(m, \"unavailable\", `the module's worker exited (${code}) before reporting`)),\n );\n });\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 (modules.length === 0) {\n o.stderr(`no spec files (*.props.ts) under ${root}\\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 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 );\n o.stdout(`${o.json ? renderSpecReportJson(specs) : renderSpecReport(specs)}\\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","import { parseArgs } from \"./args.ts\";\nimport { exitCodes, runCheck } from \"./check.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\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\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.\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 ]);\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\"])\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 === \"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\"].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 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 toJson,\n} from \"@eutaxy/core\";\n\nconst WRITE: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"ambiguous\", \"error\"];\nconst READ: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"error\"];\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(), WRITE),\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(), READ),\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 READ,\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(), READ),\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, WRITE),\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 }, WRITE),\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/** The `ExecutionContext` handed to a handler; `waitUntil` work is collected to run after it returns. */\nexport function executionContext(background: Promise<unknown>[]): ExecutionContext {\n return {\n waitUntil: (promise: Promise<unknown>) => {\n background.push(\n promise.then(\n () => undefined,\n () => undefined,\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 * 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 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 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/** The virtual delay before resend number `resend` (1 for the first), per the drive's caller. */\nexport function retryDelayMs(drive: HttpDrive, resend: number): number {\n const delays = drive.delaysMs ?? [];\n return delays[Math.min(resend, delays.length) - 1] ?? 0;\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/** 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 | {\n readonly kind: \"queue\";\n readonly queue: string;\n readonly messages: readonly QueueMessage[];\n };\n readonly setup?: readonly (D1Setup | DurableObjectSetup | R2Setup | WorkflowSetup)[];\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) `bodyKey` value must appear at least once\n * as `key` in a selected effect: nothing the drive delivered may be lost.\n */\nexport function atLeastOncePerMessage(\n name: string,\n drive: QueueDrive | HttpDrive,\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 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/** 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 if (!(Number.isInteger(drive.retries) && drive.retries >= 0))\n errors.push(\"http drive retries must be a non-negative integer\");\n (drive.delaysMs ?? []).forEach((d, i) => {\n if (!(Number.isInteger(d) && d >= 0))\n errors.push(`http 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(\"http drive deadlineMs must be a positive integer\");\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: QueueDrive | HttpDrive =\n input.drive.kind === \"http\" ? input.drive : queue(input.drive.queue, input.drive.messages);\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 ];\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","/** Inbound HTTP delivery: one invocation per attempt of a request the drive's caller sends. */\n\nimport type {\n DeliveryResult,\n EventRef,\n FaultKind,\n JsonValue,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport { type HttpDrive, type HttpRequestSpec, retryDelayMs } from \"./scenario.ts\";\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/** 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 // Virtual time: when the caller sent this attempt, for its deadline.\n const started = Date.now();\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 deadline = drive.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 redeliveries = event.attempt - 1;\n if (redeliveries < drive.retries && redeliveries < spec.bounds.maxRedeliveries) {\n const resendAt = Math.max(at + retryDelayMs(drive, event.attempt), Date.now());\n hooks.enqueue({\n ...event,\n attempt: event.attempt + 1,\n ...(resendAt > Date.now() ? { at: resendAt } : {}),\n });\n } else {\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target,\n op: \"gave_up\",\n args: { requestId: event.id, attempts: event.attempt },\n allowed: [],\n },\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 let response: Response | undefined;\n const outcome = Promise.resolve()\n .then(() =>\n handler.call(worker.handler, requestFor(req), worker.env, executionContext(background)),\n )\n .then(\n (r) => {\n response = r;\n return \"completed\" as const;\n },\n (err: unknown) => (err instanceof CrashSignal ? (\"crashed\" as const) : (\"errored\" as const)),\n );\n let status = await Promise.race([\n hooks.settle(outcome, invocation),\n inv.crashed.then(() => \"crashed\" as const),\n ]);\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 read = await Promise.race([\n hooks.settle(summarizeResponse(response), invocation).then(\n (s) => s as { status: number; ok: boolean; body: JsonValue },\n (err: unknown) =>\n err instanceof CrashSignal ? (\"crashed\" as const) : (\"errored\" as const),\n ),\n inv.crashed.then(() => \"crashed\" as const),\n ]);\n if (read === \"crashed\" || read === \"errored\") status = read;\n }\n let late = lateAt !== undefined && Date.now() > lateAt;\n const allowed = deadline === undefined ? RESPOND : RESPOND_WITH_DEADLINE;\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 // The caller decides as soon as it has an answer or gives up, before background work ends.\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n const accepted =\n summary !== null && !late && (drive.retryOn === \"5xx\" ? summary.status < 500 : summary.ok);\n if (accepted) decided = true;\n else giveUp(late && lateAt !== undefined ? lateAt : Date.now());\n\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\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 type { DeliveryResult, EventRef, FaultKind, JsonValue, RunHooks } from \"@eutaxy/core\";\nimport { CrashSignal } from \"@eutaxy/engine\";\n\n/** `EventRef.source` of an alarm event. */\nexport const alarmSource = \"durable_object_alarm\";\n\n/** Crash before: the handler never ran. Crash after: it ran and committed, but counts as failed. */\nconst ALARM: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"error\"];\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 = `${event.id}#${event.attempt}`;\n const inv = hooks.startInvocation(invocation);\n const info = { retryCount: a.retryCount, isRetry: a.retryCount > 0 };\n const outcome = hooks\n .effect(\n {\n invocation,\n target: `DO:${d.binding}`,\n op: \"alarm\",\n args: { object: a.object, retryCount: a.retryCount },\n allowed: ALARM,\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 .then(\n () => \"completed\" as const,\n (err: unknown) => (err instanceof CrashSignal ? (\"crashed\" as const) : (\"errored\" as const)),\n );\n const status = await Promise.race([\n hooks.settle(outcome, invocation),\n inv.crashed.then(() => \"crashed\" as const),\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 if (a.retryCount < maxRetries && a.retryCount < maxRedeliveries) {\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({\n ...event,\n attempt: event.attempt + 1,\n data: data as unknown as JsonValue,\n at: retryAt,\n });\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 FaultKind, type JsonValue, toJson } from \"@eutaxy/core\";\nimport { withoutNetwork } from \"@eutaxy/engine\";\nimport { AlarmBook, alarmControl, takenOver, takeOverAlarms } from \"./alarms.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\n\nconst CALL: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"ambiguous\", \"error\"];\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: CALL,\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","/** Queue delivery: one invocation per delivery of a message, redelivered until acked or dead-lettered. */\n\nimport type {\n DeliveryResult,\n EventRef,\n FaultKind,\n JsonValue,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { CrashSignal } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport type { QueueDrive } from \"./scenario.ts\";\n\nconst ACK: readonly FaultKind[] = [\"crash_before\", \"crash_after\"];\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: ACK },\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 const outcome = Promise.resolve()\n .then(() => handler.call(worker.handler, batch, worker.env, execution))\n .then(\n () => \"completed\" as const,\n (err: unknown) => (err instanceof CrashSignal ? (\"crashed\" as const) : (\"errored\" as const)),\n );\n let status = await Promise.race([\n hooks.settle(outcome, invocation),\n inv.crashed.then(() => \"crashed\" as const),\n ]);\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 redeliveries = event.attempt - 1;\n if (event.attempt <= maxRetries && redeliveries < spec.bounds.maxRedeliveries) {\n followUps.push({ ...event, attempt: event.attempt + 1 });\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 * 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 { type EffectPoint, type FaultKind, type JsonValue, toJson } from \"@eutaxy/core\";\nimport type { ProxyContext } from \"./d1.ts\";\n\nconst WRITE: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"ambiguous\", \"error\"];\nconst READ: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"error\"];\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) }, WRITE),\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] }, WRITE),\n () => real.delete(keys),\n () => null,\n ),\n get: (key: string, options?: R2GetOptions) =>\n ctx.hooks.effect(\n point(\"get\", getArgs(key, options), READ),\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 }, READ),\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 ?? {}), READ),\n async () => {\n const listed = await real.list(options);\n const at = Date.now();\n return { ...listed, objects: listed.objects.map((o) => metadata(o, book, at)) };\n },\n (l) => ({\n keys: l.objects.map((o) => o.key),\n truncated: l.truncated,\n delimitedPrefixes: l.delimitedPrefixes,\n }),\n ),\n createMultipartUpload: () => notModelled(\"createMultipartUpload()\"),\n resumeMultipartUpload: () => notModelled(\"resumeMultipartUpload()\"),\n } as unknown as R2Bucket;\n}\n\n/** An object a setup seeds: its text, or its text with metadata. */\nexport type R2Seed =\n | string\n | {\n readonly value: string;\n readonly customMetadata?: Readonly<Record<string, string>>;\n readonly httpMetadata?: Readonly<Record<string, string>>;\n };\n\n/** Every object of the bucket, through all pages of a listing. */\nasync function allObjects(real: R2Bucket): Promise<R2Object[]> {\n const out: R2Object[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page: R2Objects = await real.list({\n include: [\"customMetadata\", \"httpMetadata\"],\n ...(cursor === undefined ? {} : { cursor }),\n });\n out.push(...page.objects);\n if (!page.truncated) return out;\n cursor = page.cursor;\n }\n}\n\n/** Empty the bucket and put its seeds, before a run. */\nexport async function resetR2(\n real: R2Bucket,\n seeds: Readonly<Record<string, R2Seed>>,\n): Promise<void> {\n const keys = (await allObjects(real)).map((o) => o.key);\n for (let i = 0; i < keys.length; i += 1000) await real.delete(keys.slice(i, i + 1000));\n for (const [key, seed] of Object.entries(seeds)) {\n if (typeof seed === \"string\") await real.put(key, seed);\n else\n await real.put(key, seed.value, {\n ...(seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {}),\n ...(seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}),\n });\n }\n}\n\n/** Largest object whose text the snapshot keeps. */\nconst snapshotTextLimit = 4096;\n\n/**\n * The bucket's objects as rows `{ key, size, etag, customMetadata,\n * httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is\n * valid UTF-8. Versions and upload times are left out: they are the store's,\n * not the Worker's.\n */\nexport async function snapshotR2(real: R2Bucket): Promise<JsonValue[]> {\n const rows: JsonValue[] = [];\n const objects = (await allObjects(real)).sort((a, b) =>\n a.key < b.key ? -1 : a.key > b.key ? 1 : 0,\n );\n for (const o of objects) {\n let text: string | undefined;\n if (o.size <= snapshotTextLimit) {\n const body = await real.get(o.key);\n if (body && \"body\" in body) {\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false }).decode(\n await body.arrayBuffer(),\n );\n } catch {\n // not text: the size and etag stand for it\n }\n }\n }\n rows.push(\n toJson({\n key: o.key,\n size: o.size,\n etag: o.etag,\n customMetadata: o.customMetadata ?? {},\n httpMetadata: o.httpMetadata ?? {},\n ...(text === undefined ? {} : { text }),\n }),\n );\n }\n return rows;\n}\n","/**\n * Workflows, modelled: the binding's `create`/`get`, and each instance run\n * as invocations of its class's `run(event, step)` against a model of the\n * engine (persisted step results, retries in virtual time, restarts that\n * re-run `run` from the start). The real local engine is never called: it\n * runs on its own real-time clock and retry loop, which Eutaxy can neither\n * fault nor schedule. See docs/design.md, \"Workflows\".\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n type FaultKind,\n type JsonValue,\n type RunHooks,\n toJson,\n} from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\n\n/** The `EventRef.source` of a Workflow instance's run. */\nexport const workflowSource = \"workflow\";\n\n/** `create` is a call to the engine: it may never arrive, or arrive with its answer lost. */\nconst CREATE: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"ambiguous\", \"error\"];\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/** A persisted step result; a failure is kept as the engine keeps it, serialised (built-in types survive). */\ntype Outcome =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown };\n\nexport interface Instance {\n readonly id: string;\n readonly params: unknown;\n readonly createdAt: number;\n status: \"queued\" | \"running\" | \"complete\" | \"errored\";\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): boolean {\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: () => unsupported(\"sendEvent()\"),\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 allowed: CREATE,\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 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/** Sets `ctx` and `env` as `WorkflowEntrypoint` does, 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 `WorkflowEntrypoint` subclass outside the runtime. workerd's\n * base constructor accepts only a native ExecutionContext, so for this one\n * synchronous `new` the class that extends it directly extends a stand-in\n * instead; its own constructor and field initialisers run as written, and\n * the base is put back before anything else can run.\n */\nexport function constructWorkflow(cls: unknown, ctx: unknown, env: unknown): 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 WorkflowEntrypoint`);\n if ((parent as { name: string }).name === \"WorkflowEntrypoint\") break;\n direct = parent;\n }\n const base = 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, base);\n }\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 = `${event.id}#${event.attempt}`;\n const inv = hooks.startInvocation(invocation);\n const target = `Workflow:${d.binding}`;\n const instance = d.instance;\n instance.status = \"running\";\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 throw structuredClone(o.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 (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 let kept: unknown;\n try {\n kept = structuredClone(thrown);\n } catch {\n kept = new Error(String(thrown));\n }\n instance.persisted.set(k, { ok: false, error: kept });\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: () => {\n hooks.unsupported(`Workflow ${d.binding}: step.waitForEvent is not modelled`);\n throw new Error(\"eutaxy: step.waitForEvent is not modelled\");\n },\n };\n async function sleepStep(k: string, name: string, ms: number, until?: number): Promise<void> {\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 outcome = Promise.resolve()\n .then(() => {\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 .then(\n (value) => {\n // The engine keeps the result serialised: one it cannot keep fails the instance.\n try {\n return { status: \"completed\" as const, 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\" as const,\n error: new Error(\"run() returned a value that is not structured-cloneable\"),\n };\n }\n },\n (error: unknown) =>\n error instanceof CrashSignal\n ? { status: \"crashed\" as const }\n : { status: \"errored\" as const, error },\n );\n const result = await Promise.race([\n hooks.settle(outcome, invocation),\n inv.crashed.then(() => ({ status: \"crashed\" as const })),\n ]);\n let status = result.status;\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 * 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 type {\n DeliveryResult,\n EventRef,\n JsonValue,\n Platform,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { alarmSource, deliverAlarm } from \"./alarms.ts\";\nimport type { RunningWorker } from \"./background.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 { deliverRequest } from \"./http.ts\";\nimport { deliverMessage } from \"./queues.ts\";\nimport { isR2, proxyR2, resetR2, snapshotR2, VersionBook } from \"./r2.ts\";\nimport {\n type DurableObjectSetup,\n defaultAlarmsPerObject,\n type HttpDrive,\n type QueueDrive,\n type R2Setup,\n type WorkflowSetup,\n} from \"./scenario.ts\";\nimport {\n deliverWorkflow,\n isWorkflowBinding,\n proxyWorkflow,\n WorkflowRegistry,\n workflowSource,\n} from \"./workflows.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}\n\nexport interface CloudflarePlatformOptions {\n /** The bindings from `cloudflare:workers`. */\n readonly env: object;\n /** The Worker's default export. */\n readonly handler: WorkerHandler;\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 and Workflow bindings are proxied; touching any other binding makes the run UNSUPPORTED\",\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];\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 const d1Proxies = new Map<string, D1Database>();\n const doProxies = new Map<string, DurableObjectNamespace>();\n /** The Durable Object bindings the current scenario's setup resets before each run. */\n let resetBindings = new Set<string>();\n /** Per binding, what the current run knows about its objects. */\n const bindingStates = new Map<string, BindingState>();\n const stateFor = (binding: string): BindingState => {\n let state = bindingStates.get(binding);\n if (!state) {\n state = new BindingState();\n bindingStates.set(binding, state);\n }\n return state;\n };\n /** Per binding, alarm firings allowed per object in the current run. */\n let alarmLimits = new Map<string, number>();\n /** The Workflow bindings the current scenario sets up, with the class each runs. */\n let workflowClasses = 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 workflowProxies = new Map<string, object>();\n /** The R2 buckets the current scenario sets up, and their proxies' version stand-ins. */\n let r2Bindings = new Set<string>();\n const r2Proxies = new Map<string, R2Bucket>();\n const versions = new VersionBook();\n const namespace = (binding: string): DurableObjectNamespace => {\n const real = env[binding];\n if (!isDurableObjectNamespace(real))\n throw new Error(`env.${binding} is not a Durable Object namespace`);\n return real;\n };\n const helpers = (): DurableObjectTestHelpers => {\n if (!options.durableObjects)\n throw new Error(\n 'Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })',\n );\n return options.durableObjects;\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 if (isD1(value)) {\n let p = d1Proxies.get(prop);\n if (!p) {\n p = proxyD1(value, prop, ctx);\n d1Proxies.set(prop, p);\n }\n return p;\n }\n if (isDurableObjectNamespace(value)) {\n let p = doProxies.get(prop);\n if (!p) {\n p = proxyNamespace(value, prop, ctx, stateFor(prop), options.durableObjects, () =>\n resetBindings.has(prop),\n );\n doProxies.set(prop, p);\n }\n return p;\n }\n if (isR2(value)) {\n if (!r2Bindings.has(prop))\n ctx.hooks.unsupported(\n `R2 binding ${prop} needs an r2Bucket() setup step, which empties it before each run`,\n );\n let p = r2Proxies.get(prop);\n if (!p) {\n p = proxyR2(value, prop, ctx, versions);\n r2Proxies.set(prop, p);\n }\n return p;\n }\n if (isWorkflowBinding(value)) {\n if (!workflowClasses.has(prop)) {\n ctx.hooks.unsupported(\n `Workflow binding ${prop} 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(prop, ctx, new WorkflowRegistry());\n }\n let p = workflowProxies.get(prop);\n if (!p) {\n p = proxyWorkflow(prop, ctx, registryFor(prop));\n workflowProxies.set(prop, p);\n }\n return p;\n }\n if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);\n return value;\n },\n });\n const worker: RunningWorker = { handler: options.handler, env: proxiedEnv };\n\n return {\n name: \"cloudflare\",\n assumptions,\n concurrent: true,\n\n async reset(spec: ScenarioSpec): Promise<void> {\n resetBindings = new Set();\n alarmLimits = new Map();\n workflowClasses = new Map();\n r2Bindings = new Set();\n versions.clear();\n for (const state of bindingStates.values()) state.clear();\n for (const registry of registries.values()) registry.clear();\n for (const step of spec.setup) {\n if (step.kind === \"workflow\") {\n const setup = step as WorkflowSetup;\n workflowClasses.set(setup.binding, setup);\n continue;\n }\n if (step.kind === \"r2\") {\n const setup = step as R2Setup;\n const real = env[setup.binding];\n if (!isR2(real)) throw new Error(`env.${setup.binding} is not an R2 bucket`);\n r2Bindings.add(setup.binding);\n await resetR2(real, setup.objects);\n continue;\n }\n if (step.kind === \"durable_object\") {\n const setup = step as DurableObjectSetup;\n resetBindings.add(setup.binding);\n alarmLimits.set(setup.binding, setup.alarmsPerObject ?? defaultAlarmsPerObject);\n await resetNamespace(\n namespace(setup.binding),\n helpers(),\n stateFor(setup.binding).names,\n setup.objects,\n );\n continue;\n }\n if (step.kind !== \"d1\") continue;\n const binding = String(step[\"binding\"]);\n const schema = options.schemas[binding];\n if (schema === undefined) throw new Error(`no schema provided for D1 binding ${binding}`);\n const real = env[binding];\n if (!isD1(real)) throw new Error(`env.${binding} is not a D1 binding`);\n await resetD1(real, schema);\n }\n },\n\n restrictEvents(spec: ScenarioSpec, keepIds: readonly string[]): ScenarioSpec {\n const drive = spec.drive as QueueDrive | HttpDrive;\n if (drive.kind === \"http\") {\n return {\n ...spec,\n drive: { ...drive, requests: drive.requests.filter((r) => keepIds.includes(r.id)) },\n };\n }\n return {\n ...spec,\n drive: { ...drive, messages: drive.messages.filter((m) => keepIds.includes(m.id)) },\n };\n },\n\n async finish(spec: ScenarioSpec, hooks: RunHooks): Promise<void> {\n for (const step of spec.setup) {\n if (step.kind === \"r2\") {\n const binding = (step as R2Setup).binding;\n const real = env[binding];\n if (isR2(real))\n hooks.snapshot(hooks.bookkeeping(), `R2:${binding}`, {\n tables: { objects: await snapshotR2(real) },\n });\n continue;\n }\n if (step.kind === \"workflow\") {\n const binding = (step as WorkflowSetup).binding;\n hooks.snapshot(hooks.bookkeeping(), `Workflow:${binding}`, {\n tables: { instances: registryFor(binding).rows() },\n });\n continue;\n }\n if (step.kind === \"durable_object\") {\n const setup = step as DurableObjectSetup;\n const binding = setup.binding;\n const tables = await snapshotNamespace(\n namespace(binding),\n helpers(),\n stateFor(binding).names,\n stateFor(binding).touched,\n setup.objects,\n (object) =>\n hooks.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 (reason) => hooks.unsupported(reason),\n );\n hooks.snapshot(hooks.bookkeeping(), `DO:${binding}`, { tables });\n continue;\n }\n if (step.kind !== \"d1\") continue;\n const binding = String(step[\"binding\"]);\n const real = env[binding];\n if (!isD1(real)) continue;\n const tables = await snapshotD1(real);\n hooks.snapshot(hooks.bookkeeping(), `D1:${binding}`, { tables });\n }\n },\n\n initialEvents(spec: ScenarioSpec): readonly EventRef[] {\n const drive = spec.drive as QueueDrive | HttpDrive;\n if (drive.kind === \"http\") {\n return drive.requests.map((r) => ({\n id: r.id,\n attempt: 1,\n data: r as unknown as JsonValue,\n }));\n }\n return drive.messages.map((m) => ({ id: m.id, attempt: 1, data: m.body }));\n },\n\n async deliver(event: EventRef, hooks: RunHooks, spec: ScenarioSpec): Promise<DeliveryResult> {\n const drive = spec.drive as QueueDrive | HttpDrive;\n const invocation = `${event.id}#${event.attempt}`;\n hooksRef = hooks;\n if (event.source === workflowSource) {\n const { binding, id } = event.data as { binding: string; id: string };\n const setup = workflowClasses.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 = options.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: proxiedEnv,\n maxFaultsPerRun: spec.bounds.maxFaultsPerRun,\n maxRedeliveries: spec.bounds.maxRedeliveries,\n });\n }\n if (event.source === alarmSource) {\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(\n namespace(binding),\n binding,\n ctx,\n options.durableObjects,\n stateFor(binding),\n ),\n abort: (id) => stateFor(binding).abort(id),\n mayPark: (id) => stateFor(binding).mayPark(id),\n evict: (id) => evictObject(namespace(binding), options.durableObjects, 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 return drive.kind === \"http\"\n ? await deliverRequest(event, hooks, spec, drive, invocation, worker)\n : await deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries);\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 by hand on the raw side. 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; what it does not share is any proxy code.\n */\n\nimport { type EventRef, getPath, type JsonValue, type ScenarioSpec } 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 { isD1, resetD1, snapshotD1 } from \"./d1.ts\";\nimport { requestFor } from \"./http.ts\";\nimport { type CloudflarePlatformOptions, createCloudflarePlatform } from \"./platform.ts\";\nimport { isR2, resetR2, snapshotR2 } from \"./r2.ts\";\nimport type { HttpDrive, HttpRequestSpec, QueueDrive, R2Setup } from \"./scenario.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. */\n readonly decision: \"ack\" | \"retry\" | null;\n /** HTTP drive: the response status the caller saw (500 for an uncaught exception). */\n readonly response?: number;\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\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 step of spec.setup) {\n if (step.kind === \"r2\") {\n const binding = (step as R2Setup).binding;\n const real = env[binding];\n if (isR2(real)) out[binding] = { objects: await snapshotR2(real) };\n continue;\n }\n if (step.kind !== \"d1\") continue;\n const binding = String(step[\"binding\"]);\n const real = env[binding];\n if (isD1(real)) out[binding] = await snapshotD1(real);\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 = `${event.id}#${event.attempt}`;\n const mine = entries.filter((e) => e.invocation === invocation);\n const decision = 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 return {\n event: event.id,\n attempt: event.attempt,\n status: result.status === \"completed\" ? \"completed\" : \"errored\",\n decision: decision ?? null,\n ...(response ? { response: getPath(response.payload, \"result.status\") as number } : {}),\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 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 QueueDrive | HttpDrive;\n const maxRetries = options.maxRetries ?? 3;\n for (const step of spec.setup) {\n if (step.kind === \"r2\") {\n const setup = step as R2Setup;\n const real = env[setup.binding];\n if (isR2(real)) await resetR2(real, setup.objects);\n continue;\n }\n if (step.kind !== \"d1\") continue;\n const binding = String(step[\"binding\"]);\n const schema = options.schemas[binding];\n const real = env[binding];\n if (schema !== undefined && isD1(real)) await resetD1(real, schema);\n }\n const attempts: AttemptRecord[] = [];\n const pending: EventRef[] =\n drive.kind === \"http\"\n ? drive.requests.map((r) => ({ id: r.id, attempt: 1, data: r as unknown as JsonValue }))\n : drive.messages.map((m) => ({ id: m.id, attempt: 1, data: m.body }));\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 if (drive.kind === \"http\") {\n const handler = options.handler.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n while (pending.length > 0) {\n const event = pending.shift() as EventRef;\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(\n options.handler,\n requestFor(req),\n countedEnv,\n executionContext(background),\n ),\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 if (\n !accepted &&\n event.attempt - 1 < drive.retries &&\n event.attempt - 1 < spec.bounds.maxRedeliveries\n ) {\n pending.push({ ...event, attempt: event.attempt + 1 });\n }\n }\n } else {\n const handler = options.handler.queue;\n if (!handler) throw new Error(\"the Worker has no queue() handler\");\n while (pending.length > 0) {\n const event = pending.shift() as EventRef;\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(options.handler, 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 if (\n decision !== \"ack\" &&\n event.attempt <= maxRetries &&\n event.attempt - 1 < spec.bounds.maxRedeliveries\n ) {\n pending.push({ ...event, attempt: event.attempt + 1 });\n }\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 (spec.drive.kind === \"http\" && (\"delaysMs\" in spec.drive || \"deadlineMs\" in spec.drive)) {\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 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 };\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;;ACbA,MAAM,cAAc;CAClB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAC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