snapback2 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +127 -0
  2. package/bin/snapback2.mjs +36 -0
  3. package/dist/api.d.ts +20 -0
  4. package/dist/assets.d.ts +34 -0
  5. package/dist/client-assets.d.ts +26 -0
  6. package/dist/client-offline.d.ts +94 -0
  7. package/dist/client-outbox.d.ts +58 -0
  8. package/dist/client-upload.d.ts +41 -0
  9. package/dist/client-wire.d.ts +41 -0
  10. package/dist/client.d.ts +12 -0
  11. package/dist/client.mjs +5 -0
  12. package/dist/client.mjs.map +7 -0
  13. package/dist/compiler-core.mjs +60 -0
  14. package/dist/compiler-core.mjs.map +7 -0
  15. package/dist/compiler-lib.d.ts +71 -0
  16. package/dist/compiler.mjs +5 -0
  17. package/dist/compiler.mjs.map +7 -0
  18. package/dist/drain.d.ts +33 -0
  19. package/dist/expo/files.d.ts +3 -0
  20. package/dist/expo/index.d.ts +16 -0
  21. package/dist/expo/token-store.d.ts +7 -0
  22. package/dist/expo/witness.d.ts +28 -0
  23. package/dist/expo/witness.mjs +2 -0
  24. package/dist/expo/witness.mjs.map +7 -0
  25. package/dist/expo.d.ts +4 -0
  26. package/dist/expo.mjs +9 -0
  27. package/dist/expo.mjs.map +7 -0
  28. package/dist/guide/auth.md +89 -0
  29. package/dist/guide/effects.md +52 -0
  30. package/dist/guide/families.json +446 -0
  31. package/dist/guide/grammar.md +52 -0
  32. package/dist/guide/live-query.md +27 -0
  33. package/dist/guide/offline.md +75 -0
  34. package/dist/guide/personas.md +15 -0
  35. package/dist/guide/quarry.md +297 -0
  36. package/dist/guide/testing.md +57 -0
  37. package/dist/index.d.ts +362 -0
  38. package/dist/index.mjs +2 -0
  39. package/dist/index.mjs.map +7 -0
  40. package/dist/offline-protocol.d.ts +180 -0
  41. package/dist/offline-schema.d.ts +1 -0
  42. package/dist/offline.d.ts +177 -0
  43. package/dist/react-core.d.ts +91 -0
  44. package/dist/react-core.mjs +2 -0
  45. package/dist/react-core.mjs.map +7 -0
  46. package/dist/react-native/components.d.ts +23 -0
  47. package/dist/react-native/files.d.ts +43 -0
  48. package/dist/react-native/source.d.ts +16 -0
  49. package/dist/react-native.d.ts +4 -0
  50. package/dist/react-native.mjs +2 -0
  51. package/dist/react-native.mjs.map +7 -0
  52. package/dist/react.d.ts +19 -0
  53. package/dist/react.mjs +2 -0
  54. package/dist/react.mjs.map +7 -0
  55. package/dist/sqlite-test.mjs +1720 -0
  56. package/dist/sqlite-test.mjs.map +7 -0
  57. package/dist/sse.d.ts +44 -0
  58. package/dist/store/byte-cache.d.ts +162 -0
  59. package/dist/store/canonical.d.ts +2 -0
  60. package/dist/store/indexeddb.d.ts +23 -0
  61. package/dist/store/locks.d.ts +11 -0
  62. package/dist/store/outbox.d.ts +113 -0
  63. package/dist/store/overlay-retirement.d.ts +17 -0
  64. package/dist/store/projection.d.ts +11 -0
  65. package/dist/store/range-store.d.ts +388 -0
  66. package/dist/store/sqlite-driver.conformance.d.ts +7 -0
  67. package/dist/store/sqlite-driver.d.ts +16 -0
  68. package/dist/store/sqlite-expo.d.ts +3 -0
  69. package/dist/store/sqlite.d.ts +31 -0
  70. package/dist/templates/chat/expo/App.tsx +29 -0
  71. package/dist/templates/chat/expo/app.json +11 -0
  72. package/dist/templates/chat/expo/index.js +3 -0
  73. package/dist/templates/chat/expo/shared/log.js +92 -0
  74. package/dist/templates/chat/expo/shared/log.ts +130 -0
  75. package/dist/templates/chat/expo/shared/offline.js +8 -0
  76. package/dist/templates/chat/expo/shared/offline.ts +9 -0
  77. package/dist/templates/chat/expo/src/Chat.tsx +23 -0
  78. package/dist/templates/chat/expo/src/Composer.tsx +23 -0
  79. package/dist/templates/chat/expo/src/MediaView.tsx +29 -0
  80. package/dist/templates/chat/expo/src/Witness.tsx +131 -0
  81. package/dist/templates/chat/expo/src/screens/Inbox.tsx +9 -0
  82. package/dist/templates/chat/expo/src/screens/Search.tsx +10 -0
  83. package/dist/templates/chat/expo/src/screens/Thread.tsx +22 -0
  84. package/dist/templates/chat/expo/src/witness-state.ts +68 -0
  85. package/dist/templates/chat/expo/tsconfig.json +5 -0
  86. package/dist/templates/chat/react/index.html +5 -0
  87. package/dist/templates/chat/react/shared/log.js +92 -0
  88. package/dist/templates/chat/react/shared/log.ts +130 -0
  89. package/dist/templates/chat/react/shared/offline.js +8 -0
  90. package/dist/templates/chat/react/shared/offline.ts +9 -0
  91. package/dist/templates/chat/react/src/App.tsx +36 -0
  92. package/dist/templates/chat/react/src/Composer.tsx +45 -0
  93. package/dist/templates/chat/react/src/Inbox.tsx +24 -0
  94. package/dist/templates/chat/react/src/Search.tsx +26 -0
  95. package/dist/templates/chat/react/src/Thread.tsx +126 -0
  96. package/dist/templates/chat/react/src/env.d.ts +1 -0
  97. package/dist/templates/chat/react/src/main.tsx +20 -0
  98. package/dist/templates/chat/shared/log.js +92 -0
  99. package/dist/templates/chat/shared/log.ts +130 -0
  100. package/dist/templates/chat/shared/offline.js +8 -0
  101. package/dist/templates/chat/shared/offline.ts +9 -0
  102. package/dist/templates/chat/snapback/deliveries.q +33 -0
  103. package/dist/templates/chat/snapback/delivery.ts +30 -0
  104. package/dist/templates/chat/snapback/feeds.q +14 -0
  105. package/dist/templates/chat/snapback/follows.q +11 -0
  106. package/dist/templates/chat/snapback/groups.q +40 -0
  107. package/dist/templates/chat/snapback/messages.q +32 -0
  108. package/dist/templates/chat/snapback/notifications.q +7 -0
  109. package/dist/templates/chat/snapback/posts.q +4 -0
  110. package/dist/templates/chat/snapback/profiles.q +17 -0
  111. package/dist/templates/chat/snapback/schema.q +136 -0
  112. package/dist/templates/chat/snapback/seed.ts +45 -0
  113. package/dist/templates/chat/snapback/tests/chat.test.ts +759 -0
  114. package/dist/templates/react/index.html +5 -0
  115. package/dist/templates/react/src/App.tsx +5 -0
  116. package/dist/templates/react/src/main.tsx +18 -0
  117. package/dist/templates/todos/snapback/schema.q +11 -0
  118. package/dist/templates/todos/snapback/seed.ts +10 -0
  119. package/dist/templates/todos/snapback/tests/todos.test.ts +13 -0
  120. package/dist/templates/todos/snapback/todos.q +6 -0
  121. package/dist/test-runner.mjs +8541 -0
  122. package/dist/test-runner.mjs.map +7 -0
  123. package/dist/test.d.ts +28 -0
  124. package/dist/test.mjs +8541 -0
  125. package/dist/test.mjs.map +7 -0
  126. package/dist/token-store.d.ts +3 -0
  127. package/dist/twin-hydrate.d.ts +43 -0
  128. package/dist/twin.d.ts +70 -0
  129. package/dist/types.d.ts +410 -0
  130. package/dist/witness-test.mjs +2 -0
  131. package/dist/witness-test.mjs.map +7 -0
  132. package/package.json +117 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../compiler/src/project.ts", "../../compiler/src/compiler.ts", "../../compiler/src/args.ts", "../../compiler/src/syntax.ts", "../../compiler/src/diagnostics.ts", "../../compiler/src/lower/expr.ts", "../../compiler/src/lower/provenance.ts", "../../compiler/src/lower/recursion.ts", "../../compiler/src/lower/collection-origins.ts", "../../compiler/src/lower/helper-expansion.ts", "../../compiler/src/lower/operation-context.ts", "../../compiler/src/lower/object-shape.ts", "../../compiler/src/lower/binding-bound.ts", "../../compiler/src/lower/collection-facts.ts", "../../compiler/src/lower/cursor.ts", "../../compiler/src/authored-types.ts", "../../compiler/src/lower/branch-bindings.ts", "../../compiler/src/lower/loop-mutations.ts", "../../compiler/src/lower/merge.ts", "../../compiler/src/lower/collections.ts", "../../compiler/src/lower/write-identity.ts", "../../compiler/src/policy.ts", "../../compiler/src/type-analysis.ts", "../../compiler/src/typecheck.ts", "../../compiler/src/type-diagnostic-site.ts", "../../compiler/src/lower/static.ts", "../../compiler/src/lower/schema.ts", "../../../crates/snapback2-core/ir-contract.json", "../../compiler/src/ir.ts", "../../compiler/src/lower/rule-types.ts", "../../compiler/src/handler-bindings.ts", "../../compiler/src/lower/module.ts", "../../compiler/src/operation-diagnostics.ts", "../../compiler/src/result-page.ts", "../../compiler/src/lower/effects.ts", "../../compiler/src/quarry/index.ts", "../../compiler/src/quarry/diagnostics.ts", "../../compiler/src/quarry/catalog.ts", "../../compiler/src/quarry/expand.ts", "../../compiler/src/quarry/lexer.ts", "../../compiler/src/quarry/narrowing.ts", "../../compiler/src/quarry/schema.ts", "../../compiler/src/quarry/program.ts", "../../compiler/src/quarry/parser.ts", "../../compiler/src/quarry/where-repair.ts", "../../compiler/src/project-program.ts", "../../compiler/src/project-seed.ts", "../../compiler/src/project-sort.ts", "../../compiler/src/project-authoring.ts", "../../compiler/src/project-api-types.ts"],
4
+ "sourcesContent": ["import { existsSync, readFileSync } from \"node:fs\";\nimport { lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport ts from \"typescript\";\nimport type { TableInfo } from \"./authored-types\";\nimport { lowerSource } from \"./compiler\";\nimport { boundedDiagnostics, diagnostic, typeDiagnostic } from \"./diagnostics\";\nimport { type FrontendDiagnostic, type Program, type ProjectResult, type SourceSite } from \"./ir\";\nimport { effectBindings, collectEffectCatalog, lowerEffects, type OperationDecl, type SourceModule } from \"./lower/effects\";\nimport { lowerSchema } from \"./lower/schema\";\nimport { boundOperationDiagnostics } from \"./operation-diagnostics\";\nimport { callLeaf, moduleJsonConstants, objectOf, property, staticJson } from \"./lower/static\";\nimport { hasExport, propertyName, unwrapCall, walk } from \"./syntax\";\nimport { typeDiagnosticSite } from \"./type-diagnostic-site\";\nimport { compileQuarry, quarryInspection, remapVirtualDiagnostic, remapVirtualSource, type QuarryInput, type QuarryVirtualModule } from \"./quarry/index\";\nimport { createProjectProgram, projectTypeDiagnostics } from \"./project-program\";\nimport { moduleSeedJsonConstants, staticSeedJson, validateSeedRow } from \"./project-seed\";\nimport { sortSerdeMaps } from \"./project-sort\";\nimport { quarryOnlyDiagnostics, type LowerProjectOptions } from \"./project-authoring\";\nimport { apiRowName, generateApiDts } from \"./project-api-types\";\n// @ref LLP 1002#3-the-compiler-worker-and-the-project-json \u2014 one lowering pass owns the ProjectJson, sources, API types, and aggregate refusals.\n\nexport async function lowerProject(root: string, options: LowerProjectOptions = {}): Promise<ProjectResult> {\n const started = performance.now();\n const projectRoot = resolve(root);\n const authoredRoot = join(projectRoot, \"snapback\");\n const tsSchemaPath = join(authoredRoot, \"schema.ts\");\n const qSchemaPath = join(authoredRoot, \"schema.q\");\n const hasTsSchema = existsSync(tsSchemaPath);\n const hasQuarrySchema = existsSync(qSchemaPath);\n if (!hasTsSchema && !hasQuarrySchema) {\n return {\n ok: false,\n diagnostics: [typeDiagnostic(\"E_SCHEMA_DEFAULT_EXPORT\", \"schema\", \"snapback/schema.q\", 1, 1,\n \"missing snapback/schema.q\", \"create snapback/schema.q with table declarations\", \"schema/project\")],\n ms: elapsed(started),\n };\n }\n const discoveredModulePaths = await discoverModulePaths(authoredRoot);\n const tsModulePaths = discoveredModulePaths.filter((path) => path.endsWith(\".ts\")).sort();\n if (options.authoring !== \"any\") {\n const authored = await quarryOnlyDiagnostics(projectRoot, hasTsSchema, tsModulePaths);\n if (authored.length > 0) return { ok: false, diagnostics: authored, ms: elapsed(started) };\n }\n if (hasTsSchema && hasQuarrySchema) {\n return {\n ok: false,\n diagnostics: [typeDiagnostic(\"E_QUARRY_PLACEMENT\", \"quarry\", \"snapback/schema.q\", 1, 1,\n \"snapback/schema.q and snapback/schema.ts cannot coexist; exactly one schema is allowed\",\n \"-- remove snapback/schema.ts or snapback/schema.q\", \"quarry/projects\")],\n ms: elapsed(started),\n };\n }\n\n const quarryPaths = discoveredModulePaths.filter((path) => path.endsWith(\".q\")).sort();\n if (!hasQuarrySchema && quarryPaths.length > 0) {\n const path = quarryPaths[0]!;\n return {\n ok: false,\n diagnostics: [typeDiagnostic(\"E_QUARRY_PLACEMENT\", \"quarry\", relativeSite(projectRoot, path), 1, 1,\n `Quarry module ${relativeSite(projectRoot, path)} requires snapback/schema.q; this project has snapback/schema.ts`,\n \"-- move the schema to snapback/schema.q\", \"quarry/projects\")],\n ms: elapsed(started),\n };\n }\n\n let schemaPath = tsSchemaPath;\n let schemaSource = hasTsSchema ? await readFile(tsSchemaPath, \"utf8\") : \"\";\n let virtualModules: QuarryVirtualModule[] = [];\n if (hasQuarrySchema) {\n const inputs: QuarryInput[] = await Promise.all(quarryPaths.map(async (path) => ({\n path,\n fileName: relativeSite(projectRoot, path),\n source: await readFile(path, \"utf8\"),\n })));\n const compiled = compileQuarry(inputs);\n if (!compiled.ok) return { ok: false, diagnostics: boundedDiagnostics(compiled.diagnostics, 50, \"Quarry refusals\"), ms: elapsed(started) };\n schemaPath = compiled.schema.path;\n schemaSource = compiled.schema.source;\n virtualModules = [compiled.schema, ...compiled.modules];\n }\n const virtualByFile = new Map(virtualModules.map((module) => [relativeSite(projectRoot, module.path), module]));\n const diskModuleSources = await Promise.all(tsModulePaths.map(async (path) => [path, await readFile(path, \"utf8\")] as const));\n const virtualModuleSources = virtualModules.filter((module) => module !== virtualModules[0]).map((module) => [module.path, module.source] as const);\n const moduleSources = [...diskModuleSources, ...virtualModuleSources].sort(([left], [right]) => left.localeCompare(right));\n const modules: SourceModule[] = moduleSources.map(([path, source]) => ({\n moduleName: moduleName(path),\n fileName: relativeSite(projectRoot, path),\n source,\n sourceFile: ts.createSourceFile(path, source, ts.ScriptTarget.ES2022, true),\n }));\n const schemaFileName = relativeSite(projectRoot, schemaPath);\n const schema = lowerSchema(schemaSource, schemaFileName);\n const programPaths = [...tsModulePaths, ...quarryPaths.filter((path) => basename(path) !== \"schema.q\")];\n const diagnostics = [\n ...schema.diagnostics,\n ...nestedModuleDiagnostics(discoveredModulePaths, authoredRoot, projectRoot),\n ...duplicateModuleBasenameDiagnostics(programPaths, projectRoot),\n ...rowAliasDiagnostics(schema.tables, schemaFileName),\n ];\n if (modules.length === 0) {\n diagnostics.push(typeDiagnostic(\n \"E_OP_NONE\",\n \"op\",\n schemaFileName,\n 1,\n 1,\n \"module exports no query/mutation/effect\",\n \"query operation():\\n return null\",\n \"programs/operations\",\n ));\n }\n\n const libText = loadCompilerLib();\n const checked = createProjectProgram(schemaPath, schemaSource, moduleSources, libText);\n diagnostics.push(...projectTypeDiagnostics(checked.program, projectRoot).map((item) => remapDiagnostic(item, virtualByFile, true)));\n\n const operations = collectOperations(modules);\n diagnostics.push(...reservedApiPathDiagnostics(operations, schemaSource, schemaFileName));\n const catalog = collectEffectCatalog(modules);\n const loweredEffects = lowerEffects(catalog, operations);\n diagnostics.push(...loweredEffects.diagnostics);\n\n const programs: Program[] = [];\n const sources: Record<string, SourceSite> = Object.create(null);\n const bindingsByModule = new Map<string, Map<string, TableInfo>>();\n for (const module of modules) {\n const tables = tableBindings(module, schema.tables, diagnostics);\n bindingsByModule.set(module.moduleName, tables);\n const effects = effectBindings(module, catalog);\n const lowered = lowerSource(module.source, module.fileName, undefined, {\n tables,\n effects,\n operationPrefix: module.moduleName,\n });\n if (lowered.ok) {\n programs.push(...lowered.programs.map(sortSerdeMaps));\n for (const declaration of operations.values()) {\n if (declaration.moduleName !== module.moduleName) continue;\n const position = declaration.module.sourceFile.getLineAndCharacterOfPosition(declaration.call.getStart());\n sources[declaration.name] = { file: module.fileName, line: position.line + 1, col: position.character + 1 };\n }\n } else {\n diagnostics.push(...lowered.diagnostics);\n }\n }\n\n const operationBounded = boundProjectOperationDiagnostics(diagnostics, modules, operations)\n .map((item) => remapDiagnostic(item, virtualByFile, false));\n if (operationBounded.length > 0) {\n return { ok: false, diagnostics: boundedDiagnostics(operationBounded, 50, \"project refusals\"), ms: elapsed(started) };\n }\n\n schema.schema.effects = loweredEffects.effects.map((item) => item.name);\n programs.sort((left, right) => left.name.localeCompare(right.name));\n const apiDts = generateApiDts(operations, checked.program, checked.checker, schema.tables, bindingsByModule);\n return {\n ok: true,\n project: { schema: schema.schema, programs, effects: loweredEffects.effects },\n sources: Object.fromEntries(Object.entries(sources).map(([name, site]) => {\n const virtual = virtualByFile.get(site.file);\n return [name, virtual ? remapVirtualSource(site, virtual) : site] as [string, SourceSite];\n }).sort(([left], [right]) => left.localeCompare(right))),\n apiDts,\n quarry: quarryInspection(virtualModules),\n ms: elapsed(started),\n };\n}\n\nasync function discoverModulePaths(directory: string, root = directory): Promise<string[]> {\n const paths: string[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const path = join(directory, entry.name);\n if (entry.isDirectory()) {\n if (directory === root && entry.name === \"tests\") continue;\n paths.push(...await discoverModulePaths(path, root));\n } else if (entry.isFile() && (entry.name.endsWith(\".ts\") || entry.name.endsWith(\".q\"))\n && !(directory === root && [\"schema.ts\", \"seed.ts\"].includes(entry.name))) {\n paths.push(path);\n }\n }\n return paths;\n}\n\nfunction duplicateModuleBasenameDiagnostics(paths: string[], projectRoot: string): FrontendDiagnostic[] {\n const grouped = new Map<string, string[]>();\n for (const path of paths) {\n const name = moduleName(path);\n const group = grouped.get(name) ?? [];\n group.push(path);\n grouped.set(name, group);\n }\n const diagnostics: FrontendDiagnostic[] = [];\n for (const [name, group] of grouped) {\n if (group.length < 2) continue;\n for (const path of group.sort()) {\n const site = relativeSite(projectRoot, path);\n diagnostics.push(typeDiagnostic(\n \"E_OP_MODULE_BASENAME\",\n \"op\",\n site,\n 1,\n 1,\n `module basename ${name} is duplicated; read-site identity requires one flat module per basename`,\n `rename ${site} so every snapback module has a unique basename`,\n \"programs/module-basename\",\n ));\n }\n }\n return diagnostics;\n}\n\nfunction nestedModuleDiagnostics(paths: string[], authoredRoot: string, projectRoot: string): FrontendDiagnostic[] {\n return paths.filter((path) => dirname(path) !== authoredRoot).sort().map((path) => {\n const site = relativeSite(projectRoot, path);\n return typeDiagnostic(\n \"E_OP_INVALID\",\n \"op\",\n site,\n 1,\n 1,\n `nested operation module ${site} is unsupported; operation modules must be direct children of snapback`,\n `move ${site} directly under snapback/`,\n \"programs/operations\",\n );\n });\n}\n\nfunction rowAliasDiagnostics(tables: Map<string, TableInfo>, schemaFileName: string): FrontendDiagnostic[] {\n const names = new Map<string, string[]>();\n for (const table of tables.values()) {\n const alias = apiRowName(table.name);\n names.set(alias, [...(names.get(alias) ?? []), table.name]);\n }\n return [...names].filter(([, tables]) => tables.length > 1).map(([alias, tables]) => typeDiagnostic(\n \"E_SCHEMA_INVALID\",\n \"schema\",\n schemaFileName,\n 1,\n 1,\n `tables ${tables.join(\" and \")} generate the same row alias ${alias}`,\n \"rename one table so generated row type names are unique\",\n \"schema/project\",\n ));\n}\n\nexport async function lowerSeed(root: string): Promise<\n | { ok: true; seed: { personas: string[]; rows: Record<string, unknown[]> } }\n | { ok: false; diagnostics: FrontendDiagnostic[] }\n> {\n const projectRoot = resolve(root);\n const path = join(projectRoot, \"snapback\", \"seed.ts\");\n if (!existsSync(path)) return { ok: true, seed: { personas: [], rows: {} } };\n const source = await readFile(path, \"utf8\");\n const fileName = relativeSite(projectRoot, path);\n const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.ES2022, true);\n let expression: ts.Expression | undefined;\n for (const statement of sourceFile.statements) {\n if (ts.isExportAssignment(statement) && !statement.isExportEquals) expression = statement.expression;\n }\n const call = expression && unwrapCall(expression);\n if (call && callLeaf(call) === \"seed\") expression = call.arguments[0];\n const object = expression && objectOf(expression);\n const constants = moduleJsonConstants(sourceFile);\n const seedConstants = moduleSeedJsonConstants(sourceFile);\n const value = object && staticSeedJson(object, seedConstants);\n const record = value && typeof value === \"object\" ? value as Record<string, unknown> : undefined;\n const module = { sourceFile, source, fileName };\n const invalidSpread = object && firstInvalidStaticSpread(object, constants);\n if (!record && invalidSpread) {\n return {\n ok: false,\n diagnostics: [diagnostic(module, \"E_SEED_SHAPE\", invalidSpread, `seed object spread ${invalidSpread.expression.getText(sourceFile)} is not statically JSON`,\n \"replace the spread with a JSON object constant or spell its fields explicitly\")],\n };\n }\n if (!record || !Array.isArray(record.personas) || typeof record.rows !== \"object\" || record.rows === null || Array.isArray(record.rows)) {\n return {\n ok: false,\n diagnostics: [diagnostic(module, \"E_SEED_INVALID\", expression ?? sourceFile, \"seed.ts must default-export seed({ personas, rows })\", source)],\n };\n }\n const diagnostics: FrontendDiagnostic[] = [];\n const personas = record.personas as unknown[];\n const personaNames = personas.filter((item): item is string => typeof item === \"string\" && item.length > 0);\n if (personaNames.length !== personas.length || new Set(personaNames).size !== personaNames.length) {\n diagnostics.push(diagnostic(module, \"E_SEED_PERSONA\", expression ?? sourceFile, \"seed personas must be unique, non-empty strings\", source));\n }\n\n let schemaSource: string;\n try {\n schemaSource = await readFile(join(projectRoot, \"snapback\", \"schema.ts\"), \"utf8\");\n } catch {\n const authoredRoot = join(projectRoot, \"snapback\");\n const paths = (await discoverModulePaths(authoredRoot)).filter((item) => item.endsWith(\".q\"));\n const inputs: QuarryInput[] = await Promise.all(paths.map(async (item) => ({\n path: item,\n fileName: relativeSite(projectRoot, item),\n source: await readFile(item, \"utf8\"),\n })));\n const compiled = compileQuarry(inputs);\n if (!compiled.ok) return { ok: false, diagnostics: compiled.diagnostics };\n schemaSource = compiled.schema.source;\n }\n const loweredSchema = lowerSchema(schemaSource, \"snapback/schema.ts\");\n if (loweredSchema.diagnostics.length > 0) return { ok: false, diagnostics: loweredSchema.diagnostics };\n const tables = loweredSchema.schema.tables as Record<string, { columns?: Record<string, unknown> }>;\n const rows = record.rows as Record<string, unknown>;\n for (const [table, seeded] of Object.entries(rows)) {\n if (!Object.hasOwn(tables, table)) {\n diagnostics.push(diagnostic(module, \"E_SEED_TABLE\", expression ?? sourceFile, `seed rows name unknown table ${table}`, source));\n continue;\n }\n if (!Array.isArray(seeded)) {\n diagnostics.push(diagnostic(module, \"E_SEED_ROW\", expression ?? sourceFile, `seed rows.${table} must be an array`, source));\n continue;\n }\n const columns = tables[table]?.columns ?? {};\n for (const [index, row] of seeded.entries()) {\n validateSeedRow(module, expression ?? sourceFile, table, index, row, columns, diagnostics);\n }\n }\n return diagnostics.length > 0\n ? { ok: false, diagnostics: boundedDiagnostics(diagnostics, 50, \"seed refusals\") }\n : { ok: true, seed: { personas: personaNames, rows: rows as Record<string, unknown[]> } };\n}\n\nexport async function listJourneys(root: string): Promise<string[]> {\n const projectRoot = resolve(root);\n const tests = join(projectRoot, \"snapback\", \"tests\");\n if (!existsSync(tests)) return [];\n const entries = await readdir(tests, { withFileTypes: true });\n return entries\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".test.ts\"))\n .map((entry) => relativeSite(projectRoot, join(tests, entry.name)))\n .sort();\n}\n\nexport async function compileJourneys(\n root: string,\n apiDts: string,\n): Promise<\n | { ok: true; files: string[] }\n | { ok: false; diagnostics: FrontendDiagnostic[] }\n> {\n const projectRoot = resolve(root);\n const sourceFiles = (await listJourneys(projectRoot)).map((file) => join(projectRoot, file));\n const buildRoot = join(projectRoot, \".snapback\", \"build\");\n const outputRoot = join(buildRoot, \"tests\");\n const unsafeOutput = await journeyOutputDiagnostic(projectRoot, [join(projectRoot, \".snapback\"), buildRoot, outputRoot]);\n if (unsafeOutput) return { ok: false, diagnostics: [unsafeOutput] };\n await mkdir(buildRoot, { recursive: true });\n const stagedOutput = await mkdtemp(join(buildRoot, \".tests-\"));\n if (sourceFiles.length === 0) {\n await replaceDirectoryAtomically(outputRoot, stagedOutput);\n return { ok: true, files: [] };\n }\n\n const packageDist = compilerPackageDist();\n const clientDts = join(packageDist, \"client.d.ts\");\n const testDts = join(packageDist, \"test.d.ts\");\n const stagedApi = join(buildRoot, `.api-${process.pid}-${Date.now()}.d.ts`);\n await writeFile(stagedApi, apiDts);\n const options: ts.CompilerOptions = {\n baseUrl: projectRoot,\n jsx: ts.JsxEmit.ReactJSX,\n lib: [\"lib.es2022.d.ts\", \"lib.dom.d.ts\", \"lib.dom.iterable.d.ts\"],\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n noEmit: true,\n paths: {\n \"snapback2/client\": [clientDts],\n \"snapback2/test\": [testDts],\n },\n skipLibCheck: true,\n strict: true,\n target: ts.ScriptTarget.ES2022,\n types: [],\n };\n const program = ts.createProgram({ rootNames: [...sourceFiles, stagedApi], options });\n const sourceSet = new Set(sourceFiles.map((file) => resolve(file)));\n const diagnostics = ts.getPreEmitDiagnostics(program).flatMap((item) => {\n if (!item.file || !sourceSet.has(resolve(item.file.fileName))) return [];\n const position = item.start === undefined\n ? { line: 0, character: 0 }\n : item.file.getLineAndCharacterOfPosition(item.start);\n return [typeDiagnostic(\n \"E_OP_INVALID\",\n \"op\",\n relativeSite(projectRoot, item.file.fileName),\n position.line + 1,\n position.character + 1,\n ts.flattenDiagnosticMessageText(item.messageText, \"\\n\"),\n \"fix the journey TypeScript error and rerun snapback2 check\",\n \"testing/journeys\",\n )];\n });\n await rm(stagedApi, { force: true });\n if (diagnostics.length > 0) {\n await rm(stagedOutput, { recursive: true, force: true });\n return { ok: false, diagnostics: boundedDiagnostics(diagnostics, 50, \"journey refusals\") };\n }\n\n const clientModule = pathToFileURL(join(packageDist, \"client.mjs\")).href;\n const testModule = pathToFileURL(join(packageDist, \"test.mjs\")).href;\n const files: string[] = [];\n for (const sourcePath of sourceFiles) {\n const source = await readFile(sourcePath, \"utf8\");\n const transpiled = ts.transpileModule(source, {\n fileName: sourcePath,\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2022,\n },\n }).outputText;\n const rewritten = rewriteModuleSpecifiers(transpiled, new Map([\n [\"snapback2/client\", clientModule],\n [\"snapback2/test\", testModule],\n ]));\n const sourceName = basename(sourcePath);\n const outputName = `${sourceName.slice(0, -\".test.ts\".length)}.mjs`;\n const outputPath = join(stagedOutput, outputName);\n await writeFile(outputPath, rewritten);\n files.push(relativeSite(projectRoot, outputPath));\n }\n const racedOutput = await journeyOutputDiagnostic(projectRoot, [join(projectRoot, \".snapback\"), buildRoot, outputRoot]);\n if (racedOutput) {\n await rm(stagedOutput, { recursive: true, force: true });\n return { ok: false, diagnostics: [racedOutput] };\n }\n await replaceDirectoryAtomically(outputRoot, stagedOutput);\n for (let index = 0; index < files.length; index += 1) {\n files[index] = relativeSite(projectRoot, join(outputRoot, basename(files[index]!)));\n }\n return { ok: true, files };\n}\n\nasync function replaceDirectoryAtomically(target: string, staged: string): Promise<void> {\n const backup = `${target}.replaced-${process.pid}-${Date.now()}`;\n try {\n await rename(target, backup);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n try {\n await rename(staged, target);\n } catch (error) {\n try {\n await rename(backup, target);\n } catch {\n // Preserve the original replacement failure; the staged directory remains inspectable.\n }\n throw error;\n }\n await rm(backup, { recursive: true, force: true });\n}\n\nasync function journeyOutputDiagnostic(\n projectRoot: string,\n components: string[],\n): Promise<FrontendDiagnostic | undefined> {\n const canonicalRoot = await realpath(projectRoot);\n for (const component of components) {\n try {\n const status = await lstat(component);\n if (status.isSymbolicLink()) {\n return typeDiagnostic(\"E_OP_INVALID\", \"op\", relativeSite(projectRoot, component), 1, 1,\n `journey output component ${relativeSite(projectRoot, component)} is a symlink`,\n \"replace the symlink with a project-owned directory\", \"testing/journeys\");\n }\n const canonical = await realpath(component);\n const fromRoot = relative(canonicalRoot, canonical);\n if (fromRoot === \"..\" || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {\n return typeDiagnostic(\"E_OP_INVALID\", \"op\", relativeSite(projectRoot, component), 1, 1,\n `journey output component ${relativeSite(projectRoot, component)} escapes the project`,\n \"use a project-owned output directory\", \"testing/journeys\");\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n }\n return undefined;\n}\n\nfunction rewriteModuleSpecifiers(source: string, replacements: Map<string, string>): string {\n const file = ts.createSourceFile(\"journey.mjs\", source, ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);\n const edits: Array<{ start: number; end: number; value: string }> = [];\n const add = (node: ts.Expression | undefined) => {\n if (!node || !ts.isStringLiteralLike(node)) return;\n const replacement = replacements.get(node.text);\n if (replacement) edits.push({ start: node.getStart(file), end: node.getEnd(), value: JSON.stringify(replacement) });\n };\n walk(file, (node) => {\n if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) add(node.moduleSpecifier);\n if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) add(node.arguments[0]);\n });\n return edits.sort((left, right) => right.start - left.start)\n .reduce((text, edit) => `${text.slice(0, edit.start)}${edit.value}${text.slice(edit.end)}`, source);\n}\n\nfunction compilerPackageDist(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n return basename(here) === \"dist\" ? here : resolve(here, \"../../snapback2/dist\");\n}\n\nfunction collectOperations(modules: SourceModule[]): Map<string, OperationDecl & { module: SourceModule }> {\n const operations = new Map<string, OperationDecl & { module: SourceModule }>();\n for (const module of modules) {\n for (const statement of module.sourceFile.statements) {\n if (!ts.isVariableStatement(statement) || !hasExport(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const call = unwrapCall(declaration.initializer);\n const kind = call && callLeaf(call);\n if (!call || (kind !== \"query\" && kind !== \"mutation\")) continue;\n const name = `${module.moduleName}.${declaration.name.text}`;\n operations.set(name, { name, moduleName: module.moduleName, exportName: declaration.name.text, kind, call, module });\n }\n }\n }\n return operations;\n}\n\nfunction reservedApiPathDiagnostics(\n operations: Map<string, OperationDecl & { module: SourceModule }>,\n schemaSource: string,\n schemaFileName: string,\n): FrontendDiagnostic[] {\n const diagnostics: FrontendDiagnostic[] = [];\n for (const operation of operations.values()) {\n if (operation.moduleName === \"then\") {\n diagnostics.push(diagnostic(\n operation.module,\n \"E_OP_RESERVED\",\n operation.call,\n `operation ${operation.name} uses reserved API path segment then`,\n `rename snapback/then.ts to snapback/${operation.exportName === \"then\" ? \"operations\" : operation.exportName}.ts`,\n ));\n }\n if (operation.exportName === \"then\") {\n diagnostics.push(diagnostic(\n operation.module,\n \"E_OP_RESERVED\",\n operation.call,\n `operation ${operation.name} uses reserved API property then`,\n operation.module.source.replace(/\\bthen\\b/, \"thenOperation\"),\n ));\n }\n }\n\n const sourceFile = ts.createSourceFile(schemaFileName, schemaSource, ts.ScriptTarget.ES2022, true);\n const schemaModule = { sourceFile, source: schemaSource, fileName: schemaFileName };\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement) || !hasExport(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || declaration.name.text !== \"then\" || !declaration.initializer) continue;\n const call = unwrapCall(declaration.initializer);\n if (!call || callLeaf(call) !== \"channel\") continue;\n diagnostics.push(diagnostic(\n schemaModule,\n \"E_OP_RESERVED\",\n declaration.name,\n \"channel then uses a reserved API property\",\n schemaSource.replace(/\\bthen\\b/g, \"thenChannel\"),\n ));\n }\n }\n return diagnostics;\n}\n\nfunction boundProjectOperationDiagnostics(\n diagnostics: FrontendDiagnostic[],\n modules: SourceModule[],\n operations: Map<string, OperationDecl>,\n): FrontendDiagnostic[] {\n let remaining = diagnostics;\n const result: FrontendDiagnostic[] = [];\n for (const module of modules) {\n const local = remaining.filter((item) => item.site.startsWith(`${module.fileName}:`));\n remaining = remaining.filter((item) => !item.site.startsWith(`${module.fileName}:`));\n const spans = [...operations.values()]\n .filter((item) => item.moduleName === module.moduleName)\n .map((item) => ({ name: item.name, call: item.call }));\n result.push(...boundOperationDiagnostics(local, spans, module));\n }\n return [...result, ...remaining];\n}\n\nfunction tableBindings(\n module: SourceModule,\n declared: Map<string, TableInfo>,\n diagnostics: FrontendDiagnostic[],\n): Map<string, TableInfo> {\n const bindings = new Map<string, TableInfo>();\n for (const statement of module.sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)\n || !/^\\.\\/schema(?:\\.ts)?$/.test(statement.moduleSpecifier.text)) continue;\n const imports = statement.importClause?.namedBindings;\n if (!imports) continue;\n if (ts.isNamespaceImport(imports)) {\n for (const [exported, table] of declared) bindings.set(`${imports.name.text}.${exported}`, table);\n continue;\n }\n for (const item of imports.elements) {\n const exported = item.propertyName?.text ?? item.name.text;\n const table = declared.get(exported);\n if (table) bindings.set(item.name.text, table);\n else diagnostics.push(diagnostic(module, \"E_SCHEMA_UNKNOWN_TABLE\", item, `schema has no exported table ${exported}`, module.source));\n }\n }\n return bindings;\n}\n\nfunction firstInvalidStaticSpread(node: ts.Node, constants: Map<string, unknown>): ts.SpreadAssignment | undefined {\n let invalid: ts.SpreadAssignment | undefined;\n walk(node, (item) => {\n if (invalid || !ts.isSpreadAssignment(item)) return;\n const value = staticJson(item.expression, constants);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) invalid = item;\n });\n return invalid;\n}\n\nfunction loadCompilerLib(): string {\n const moduleCandidates = [\n fileURLToPath(new URL(\"../lib.d.ts\", import.meta.url)),\n fileURLToPath(new URL(\"./index.d.ts\", import.meta.url)),\n ];\n const subsetCandidates = [\n fileURLToPath(new URL(\"../subset-lib.d.ts\", import.meta.url)),\n fileURLToPath(new URL(\"./compiler-lib.d.ts\", import.meta.url)),\n ];\n const modulePath = moduleCandidates.find(existsSync);\n const subsetPath = subsetCandidates.find(existsSync);\n if (!modulePath || !subsetPath) throw new Error(\"snapback2 compiler: checker declarations are missing beside the compiler bundle\");\n return `${readFileSync(subsetPath, \"utf8\")}\\n${readFileSync(modulePath, \"utf8\")}`;\n}\n\nfunction moduleName(path: string): string {\n return path.split(sep).at(-1)!.replace(/\\.(?:q|ts)$/, \"\");\n}\n\nfunction remapDiagnostic(\n diagnostic: FrontendDiagnostic,\n virtualByFile: Map<string, QuarryVirtualModule>,\n generatedTypeError: boolean,\n): FrontendDiagnostic {\n const file = diagnostic.site.replace(/:\\d+:\\d+$/, \"\");\n const virtual = virtualByFile.get(file);\n return virtual ? remapVirtualDiagnostic(diagnostic, virtual, generatedTypeError) : diagnostic;\n}\n\nfunction relativeSite(root: string, path: string): string {\n return relative(root, isAbsolute(path) ? path : resolve(path)).split(sep).join(\"/\");\n}\n\nfunction quoteProperty(value: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(value) ? value : JSON.stringify(value);\n}\n\nfunction elapsed(started: number): number {\n return Math.round((performance.now() - started) * 100) / 100;\n}\n", "import ts from \"typescript\";\nimport type { TableInfo } from \"./authored-types\";\nimport { argumentSpreadRewrite, expandArgumentObject } from \"./args\";\nimport { boundedDiagnostics, diagnostic, refuse, Refusal } from \"./diagnostics\";\nimport {\n allocateReadSite, cloneEnvironment, containsRead, enterLexicalScope,\n loopDomainMaximum, lowerArrayMethod, lowerCollectionDomain,\n lowerDomain, lowerExpr, lowerKey, lowerOptionalPropertyChain, lowerPatch, lowerPropertyValue,\n lowerSortExpression, reserveWriteSite, tableReference,\n} from \"./lower/expr\";\nimport { knownObjectFields, nullableReadSpread, nullableSpreadRefusal, rowCollectionFields } from \"./lower/object-shape\";\nimport { derivedBound, staticBound } from \"./lower/binding-bound\";\nimport { collectionElementBinding, collectionOriginsBinding, combinedProvenanceBinding, isRowCollectionExpression, isRowExpression, provenanceBinding, readProvenance } from \"./lower/provenance\";\nimport { appendCollectionFacts, collectionFactsFor, collectionMutationIncrement, maintainCollectionFacts,\n mergeAssignedCollectionFacts } from \"./lower/collection-facts\";\nimport { forkBranchEnvironment, mergeBranchEnvironments } from \"./lower/branch-bindings\";\nimport { lowerLoopBodyWithMutationPlan } from \"./lower/loop-mutations\";\nimport { lowerMergeByIndex } from \"./lower/merge\";\nimport { lowerCollectionConstructor, lowerCollectionLookup, lowerMapAssignment, requirePrimitiveCollectionIdentity } from \"./lower/collections\";\nimport { upsertIdentityMatches } from \"./lower/write-identity\";\nimport { findPolicyRefusals, mechanicalBoundRewrite } from \"./policy\";\nimport { analyzeOperationTypes, type TypePlan } from \"./type-analysis\";\nimport { formatTypeDiagnostic, typecheckSource } from \"./typecheck\";\nimport { typeDiagnosticSite } from \"./type-diagnostic-site\";\nimport { invalidNativeDescriptorRefusal, lowerArgDescriptor, lowerLegacyArgDescriptor } from \"./lower/schema\";\nimport { duplicateHandlerBinding, duplicateHandlerBindingRewrite,\n nestedHandlerBinding, nestedHandlerDestructuringRewrite } from \"./handler-bindings\";\nimport { inspectModule, type ModuleInfo } from \"./lower/module\";\nimport type {\n CollectionEscapeSite, Environment, FunctionLike, LoweredValue, LowerSourceOptions, ProvenanceOrigin, Substitution, VariableInfo,\n} from \"./lower/environment\";\nimport { assignedBindings, collectionSharingSites, isLocallyCreatedCollection,\n isOperationCompositeBinding, moduleBasename, operationCompositeBindings, recordAssignmentOrigin,\n requireCollectionMutation, withDirectRewrite } from \"./lower/operation-context\";\nimport { boundOperationDiagnostics, localConstructorShadow, refuseReservedAuthCode } from \"./operation-diagnostics\";\nimport {\n binaryOperator,\n collectionConstructor,\n findNarrowestNode,\n hasExport,\n isDb,\n isDbInsertCall,\n isNullableDbGet,\n isDbWriteCall,\n isFunctionLike,\n literal,\n memberName,\n nonNullIdentifier,\n propertyName,\n replaceNode,\n singular,\n snapbackCallName,\n staticMemberPath,\n stringArgument,\n syntheticIdentifier,\n temporary,\n unwrapCall,\n unwrapExpression,\n} from \"./syntax\";\nimport type { Expr, FrontendDiagnostic, LowerResult, Program, Stmt } from \"./ir\";\nimport { attachResultPageSite } from \"./result-page\";\nexport type { TableInfo } from \"./authored-types\";\nexport type {\n CollectionEscapeSite, CollectionMutationCounts, Environment, FunctionLike, LoweredValue, LowerSourceOptions, ProvenanceOrigin, Substitution, VariableInfo,\n} from \"./lower/environment\";\nexport { typecheckSource } from \"./typecheck\";\nexport { mechanicalBoundRewrite } from \"./policy\";\nexport async function lowerProject(root: string) { return (await import(\"./project\")).lowerProject(root, { authoring: \"any\" }); }\nfunction captureRefusal(diagnostics: FrontendDiagnostic[], error: unknown): void {\n if (error instanceof Refusal) diagnostics.push(error.diagnostic); else throw error;\n}\nexport function lowerSource(\n source: string,\n fileName = \"input.ts\",\n libText?: string,\n options: LowerSourceOptions = {},\n): LowerResult {\n const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.ES2022, true);\n const module = inspectModule(sourceFile, source, fileName, options);\n const diagnostics = findPolicyRefusals(module, Number.MAX_SAFE_INTEGER);\n const operationSpans: Array<{ name: string; call: ts.CallExpression }> = [];\n if (libText !== undefined) {\n const typed = typecheckSource(source, fileName, libText);\n for (const item of typed) {\n const node = item.file && item.start !== undefined\n ? findNarrowestNode(item.file, item.start)\n : sourceFile;\n const siteKind = typeDiagnosticSite(node, fileName);\n const schemaLabelRewrite = source.replace(/\\bschema\\s+\\([^\\n:]+\\):/g, \"schema:\");\n diagnostics.push(diagnostic(module, siteKind.code, node, formatTypeDiagnostic(item), schemaLabelRewrite));\n }\n }\n let recognizableExports = 0;\n const programs: Program[] = [];\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement) || !hasExport(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!declaration.initializer) continue;\n const call = unwrapCall(declaration.initializer);\n const kind = call && snapbackCallName(call, sourceFile);\n if (kind === \"effect\") {\n recognizableExports += 1;\n continue;\n }\n if (!call || (kind !== \"query\" && kind !== \"mutation\")) continue;\n recognizableExports += 1;\n const name = options.operationPrefix\n ? `${options.operationPrefix}.${ts.isIdentifier(declaration.name) ? declaration.name.text : \"operation\"}`\n : ts.isIdentifier(declaration.name) ? declaration.name.text : \"operation\";\n operationSpans.push({ name, call });\n const handler = call.arguments[1];\n const duplicateBinding = handler && isFunctionLike(handler) ? duplicateHandlerBinding(handler) : undefined;\n if (duplicateBinding && handler && isFunctionLike(handler)) {\n diagnostics.push(diagnostic(\n module,\n \"E_OPAQUE\",\n duplicateBinding.elements[1]!,\n `handler property ${duplicateBinding.property} is destructured more than once; bind it once and alias locally`,\n duplicateHandlerBindingRewrite(module, handler, duplicateBinding),\n ));\n continue;\n }\n const nestedBinding = handler && isFunctionLike(handler) ? nestedHandlerBinding(handler) : undefined;\n if (nestedBinding && handler && isFunctionLike(handler)) {\n diagnostics.push(diagnostic(\n module,\n \"E_OPAQUE\",\n nestedBinding,\n \"nested handler destructuring is not lowerable; bind each operation composite to an identifier and access its fields explicitly\",\n nestedHandlerDestructuringRewrite(module, handler),\n ));\n continue;\n }\n const plan = analyzeOperationTypes(module, call);\n diagnostics.push(...plan.diagnostics);\n if (plan.analysisLimitReached) continue;\n if (!ts.isIdentifier(declaration.name)) continue;\n try {\n programs.push(lowerOperation(module, name, declaration.name.text, kind, call, plan, diagnostics));\n } catch (error) {\n captureRefusal(diagnostics, error);\n }\n }\n }\n if (recognizableExports === 0) {\n const shadow = localConstructorShadow(sourceFile);\n diagnostics.push(diagnostic(\n module,\n \"E_OP_NONE\",\n shadow?.node ?? sourceFile,\n shadow\n ? `module exports no query/mutation/effect; local declaration ${shadow.name} shadows the Snapback constructor`\n : \"module exports no query/mutation/effect\",\n \"export const operation = query({}, ({ args }) => args);\",\n ));\n }\n const bounded = boundOperationDiagnostics(diagnostics, operationSpans, module);\n return bounded.length > 0 ? { ok: false, diagnostics: boundedDiagnostics(bounded, 50, \"refusals in this module\") } : { ok: true, programs };\n}\nfunction lowerOperation(\n module: ModuleInfo,\n name: string,\n exportName: string,\n kindName: \"query\" | \"mutation\",\n call: ts.CallExpression,\n typePlan?: TypePlan,\n diagnostics: FrontendDiagnostic[] = [],\n): Program {\n const argObject = call.arguments[0];\n const handler = call.arguments[1];\n if (!argObject || !ts.isObjectLiteralExpression(argObject) || !handler || !isFunctionLike(handler)) {\n refuse(module, \"E_OPAQUE\", call, \"query/mutation requires an argument object and inline handler\");\n }\n const offending = nestedHandlerBinding(handler);\n if (offending) {\n refuse(\n module,\n \"E_OPAQUE\",\n offending,\n \"nested handler destructuring is not lowerable; bind each operation composite to an identifier and access its fields explicitly\",\n nestedHandlerDestructuringRewrite(module, handler),\n );\n }\n const args: Program[\"args\"] = Object.create(null);\n const expandedArgs = expandArgumentObject(argObject);\n if (expandedArgs.invalidSpread) {\n refuse(module, \"E_ARGS_SPREAD\", expandedArgs.invalidSpread, \"argument object spread is not a module-level constant object; spell out every argument field\",\n argumentSpreadRewrite(module.source, expandedArgs.invalidSpread));\n }\n if (expandedArgs.invalidProperty) refuse(module, \"E_ARGS_TYPE\", expandedArgs.invalidProperty, \"argument members must use name: descriptor syntax\");\n for (const property of expandedArgs.entries) {\n const argName = property.name;\n const loweredDescriptor = lowerArgDescriptor(property.value, module.tables);\n const invalid = loweredDescriptor === undefined ? invalidNativeDescriptorRefusal(property.value) : undefined;\n if (invalid) refuse(module, \"E_ARGS_DESCRIPTOR\", invalid.node, `invalid argument descriptor ${argName}; ${invalid.message}`, invalid.rewrite);\n const lowered = (loweredDescriptor ?? lowerLegacyArgDescriptor(property.value)) as Program[\"args\"][string] | undefined;\n if (!lowered) refuse(module, \"E_ARGS_TYPE\", property.node, `invalid argument descriptor ${argName}`);\n args[argName] = lowered;\n }\n const variables = new Map<string, VariableInfo>();\n for (const [argName, type] of Object.entries(args)) {\n const info: VariableInfo = {\n provenance: \"Arg\",\n operationArgument: argName,\n };\n if (typeof type !== \"string\" && \"List\" in type) {\n info.collectionIdentity = {};\n maintainCollectionFacts(info, {\n max: type.List.max,\n boundSource: `arg ${argName} max`,\n elementOrigins: [{ binding: { provenance: \"Arg\", operationArgument: argName }, candidate: argName }],\n });\n }\n variables.set(argName, info);\n }\n const handlerBindings = operationCompositeBindings(handler);\n const collectionSharing = collectionSharingSites(handler);\n if (handlerBindings.args) {\n variables.set(handlerBindings.args, {\n provenance: Object.keys(args).length === 0 ? \"Const\" : \"Arg\",\n operationComposite: \"args\",\n objectFields: Object.keys(args),\n });\n }\n if (handlerBindings.ctx) {\n variables.set(handlerBindings.ctx, {\n provenance: \"Viewer\",\n operationComposite: \"ctx\",\n objectFields: [\"viewer\"],\n });\n }\n if (handlerBindings.db) {\n variables.set(handlerBindings.db, { provenance: \"Const\", operationComposite: \"db\" });\n }\n const environment: Environment = {\n ...module,\n programName: name,\n siteBase: `${moduleBasename(module.fileName)}.${exportName}`,\n kind: kindName === \"query\" ? \"Query\" : \"Mutation\",\n args,\n variables,\n substitutions: new Map(),\n helperStack: [],\n mutableBindings: assignedBindings(handler),\n deferredCollectionMutations: new Set(),\n collectionAliasSites: collectionSharing.aliases,\n collectionEscapeSites: collectionSharing.escapes,\n accessOrdinal: { value: 0 },\n temp: { value: 0 },\n literalValues: typePlan?.literalValues ?? new Map(),\n expressionTypes: typePlan?.expressionTypes ?? new Map(),\n literalContext: \"operation\",\n diagnostics,\n recursion: { depth: 0, active: new Map() },\n };\n let body: Stmt[];\n if (ts.isBlock(handler.body)) {\n body = lowerStatements(handler.body.statements, environment);\n } else if (isDbWriteCall(handler.body, (binding) => isOperationCompositeBinding(binding, \"db\", environment))) {\n body = lowerExpressionStatement(handler.body, environment);\n } else {\n const lowered = lowerValue(handler.body, environment, `${name}.result`);\n body = [...lowered.statements, { Return: lowered.expression }];\n }\n return attachResultPageSite({\n name,\n kind: environment.kind,\n args,\n read_time_granularity_ms: environment.kind === \"Query\" && JSON.stringify(body).includes('\"Input\":\"ReadTime\"') ? 1 : null,\n body,\n });\n}\n\nfunction lowerStatements(nodes: ts.NodeArray<ts.Statement> | readonly ts.Statement[], env: Environment): Stmt[] {\n const result: Stmt[] = [];\n for (const statement of nodes) {\n try {\n result.push(...lowerStatement(statement, env));\n } catch (error) {\n captureRefusal(env.diagnostics, error);\n }\n }\n return result;\n}\nfunction lowerStatement(statement: ts.Statement, env: Environment): Stmt[] {\n if (ts.isVariableStatement(statement)) {\n const out: Stmt[] = [];\n for (const declaration of statement.declarationList.declarations) {\n try {\n if (!declaration.initializer) {\n refuse(env, \"E_OPAQUE\", declaration, \"destructuring declarations are not yet lowerable\");\n }\n if (ts.isArrayBindingPattern(declaration.name)) {\n const call = unwrapCall(declaration.initializer);\n if (!call || !ts.isIdentifier(call.expression) || call.expression.text !== \"orderedPair\"\n || declaration.name.elements.length !== 2 || call.arguments.length !== 2) {\n refuse(env, \"E_OPAQUE\", declaration, \"array destructuring is admitted only for orderedPair\");\n }\n const defaulted = declaration.name.elements.find((element) => ts.isBindingElement(element) && element.initializer);\n if (defaulted) {\n refuse(\n env,\n \"E_OPAQUE\",\n defaulted,\n \"orderedPair destructuring defaults have authored runtime semantics; normalize each input before orderedPair\",\n );\n }\n const identifiers = declaration.name.elements.map((element) => ts.isBindingElement(element) && ts.isIdentifier(element.name)\n ? element.name\n : undefined);\n if (!identifiers[0] || !identifiers[1]) refuse(env, \"E_OPAQUE\", declaration.name, \"orderedPair bindings must be identifiers\");\n const args = call.arguments.map((argument) => lowerValue(argument, env));\n out.push(...args.flatMap((argument) => argument.statements));\n const values = args.map((argument, index) => {\n const name = temporary(env, `ordered${index}`);\n out.push({ Let: { name, value: argument.expression } });\n return { Variable: name } satisfies Expr;\n });\n out.push({ Let: { name: identifiers[0].text, value: { Builtin: { builtin: \"Min\", args: values } } } });\n out.push({ Let: { name: identifiers[1].text, value: { Builtin: { builtin: \"Max\", args: values } } } });\n const origin = withDirectRewrite(combinedProvenanceBinding(call.arguments, env), declaration.initializer, env);\n for (const identifier of identifiers as [ts.Identifier, ts.Identifier]) {\n env.variables.set(identifier.text, { ...origin });\n }\n continue;\n }\n if (!ts.isIdentifier(declaration.name)) refuse(env, \"E_OPAQUE\", declaration.name, \"binding pattern is unsupported\");\n const name = declaration.name.text;\n const lowered = lowerValue(declaration.initializer, env, `${env.programName}.${name}`);\n const collection = collectionConstructor(declaration.initializer);\n const isConst = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0;\n const stableBinding = !env.mutableBindings.has(declaration.name);\n const loweredBinding = \"Variable\" in lowered.expression ? env.variables.get(lowered.expression.Variable) : undefined;\n const rowCollection = loweredBinding?.rowCollection === true || isRowCollectionExpression(declaration.initializer, env);\n const objectFields = stableBinding\n ? knownObjectFields(declaration.initializer, env) ?? (rowCollection ? rowCollectionFields(declaration.initializer, env) : undefined)\n : undefined;\n const classified = provenanceBinding(declaration.initializer, env);\n const origin = withDirectRewrite(classified, declaration.initializer, env);\n const bindTime = cloneEnvironment(env);\n const bound = derivedBound(declaration.initializer, env);\n const facts = collectionFactsFor(declaration.initializer, env, bound.max, bound.boundSource);\n if (facts.elementOrigins === undefined && loweredBinding?.elementOrigins !== undefined) {\n facts.elementOrigins = loweredBinding.elementOrigins;\n }\n const info = maintainCollectionFacts({\n ...origin,\n ...(collection || facts.max !== undefined || facts.elementOrigins !== undefined\n ? { collectionIdentity: {} }\n : {}),\n collectionDeclaration: declaration.name,\n locallyCreatedCollection: isLocallyCreatedCollection(declaration.initializer),\n ...(collection ? { collection } : {}),\n ...(objectFields ? { objectFields } : {}),\n ...(stableBinding ? { identityExpression: lowered.expression } : {}),\n immutableOrigin: { expression: declaration.initializer, environment: bindTime },\n ...(isRowExpression(declaration.initializer, env) ? { rowBinding: true } : {}),\n ...(rowCollection ? { rowCollection: true } : {}),\n ...(isNullableDbGet(declaration.initializer,\n (binding) => isOperationCompositeBinding(binding, \"db\", env)) ? { nullableRead: true } : {}),\n }, facts);\n env.variables.set(name, info);\n out.push(...lowered.statements);\n out.push(isConst && !collection\n ? { Const: { name, value: lowered.expression } }\n : { Let: { name, value: lowered.expression } });\n } catch (error) {\n captureRefusal(env.diagnostics, error);\n }\n }\n return out;\n }\n if (ts.isExpressionStatement(statement)) return lowerExpressionStatement(statement.expression, env);\n if (ts.isReturnStatement(statement)) {\n if (!statement.expression) return [{ Return: literal(null) }];\n const lowered = lowerValue(statement.expression, env, `${env.programName}.result`);\n return [...lowered.statements, { Return: lowered.expression }];\n }\n if (ts.isIfStatement(statement)) {\n const condition = lowerValue(statement.expression, env);\n const thenBranch = forkBranchEnvironment(env);\n const elseBranch = forkBranchEnvironment(env);\n const thenEnv = thenBranch.environment;\n const narrowed = nonNullIdentifier(statement.expression);\n if (narrowed && thenEnv.variables.has(narrowed)) thenEnv.variables.get(narrowed)!.nullableRead = false;\n const thenBody = lowerControlled(statement.thenStatement, thenEnv);\n const elseBody = statement.elseStatement\n ? lowerControlled(statement.elseStatement, elseBranch.environment)\n : [];\n mergeBranchEnvironments(env, [thenBranch, elseBranch], statement);\n return [...condition.statements, {\n If: {\n condition: condition.expression,\n then_body: thenBody,\n else_body: elseBody,\n },\n }];\n }\n if (ts.isForOfStatement(statement)) {\n if (!ts.isVariableDeclarationList(statement.initializer)\n || statement.initializer.declarations.length !== 1\n || !ts.isIdentifier(statement.initializer.declarations[0]!.name)) {\n refuse(env, \"E_OPAQUE\", statement.initializer, \"for-of binding must be one identifier\");\n }\n const binding = statement.initializer.declarations[0].name.text;\n const loopEnv = enterLexicalScope(env);\n const { statements, domain, bindingInfo } = lowerCollectionDomain(statement.expression, loopEnv, binding, lowerValue);\n loopEnv.variables.set(binding, bindingInfo);\n const iterations = loopDomainMaximum(domain);\n const domainIdentity = \"DerivedArray\" in domain && \"Variable\" in domain.DerivedArray.value\n ? loopEnv.variables.get(domain.DerivedArray.value.Variable)?.collectionIdentity\n : undefined;\n // @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 lowering-order analysis reserves inherited collections to their proven end-of-loop facts before nested domains are emitted.\n const body = lowerLoopBodyWithMutationPlan(statement, loopEnv, iterations, domainIdentity, lowerControlled);\n return [...statements, { For: { binding, domain, body } }];\n }\n if (statement.kind === ts.SyntaxKind.BreakStatement) return [\"Break\"];\n if (statement.kind === ts.SyntaxKind.ContinueStatement) return [\"Continue\"];\n // @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 lexical bindings classify authored facts and cannot escape their block.\n if (ts.isBlock(statement)) return lowerStatements(statement.statements, enterLexicalScope(env));\n if (ts.isEmptyStatement(statement)) return [];\n refuse(env, \"E_OPAQUE\", statement, `statement ${ts.SyntaxKind[statement.kind]} is outside the subset`);\n}\n\nfunction lowerControlled(statement: ts.Statement, env: Environment): Stmt[] {\n if (ts.isBlock(statement)) return lowerStatements(statement.statements, env);\n try {\n return lowerStatement(statement, env);\n } catch (error) {\n captureRefusal(env.diagnostics, error);\n return [];\n }\n}\n\nfunction lowerExpressionStatement(expression: ts.Expression, env: Environment): Stmt[] {\n if (ts.isCallExpression(expression)) {\n if (snapbackCallName(expression, env.sourceFile) === \"emit\") {\n // @ref LLP 1001#8-emit-and-the-outbox \u2014 Emit is IR, never an authoring-process side effect.\n if (env.kind === \"Query\") {\n refuse(env, \"E_EMIT_IN_QUERY\", expression, \"emit is available only in mutations\");\n }\n const effectNode = expression.arguments[0];\n const payloadNode = expression.arguments[1];\n if (!effectNode || !payloadNode) {\n refuse(env, \"E_EFFECT_UNKNOWN\", expression, \"emit requires an imported effect and a JSON payload\");\n }\n const effectPath = staticMemberPath(effectNode);\n const effect = effectPath && env.effects.get(effectPath);\n if (!effect) {\n refuse(env, \"E_EFFECT_UNKNOWN\", effectNode, `effect ${effectNode.getText(env.sourceFile)} is not declared in this project`);\n }\n reserveWriteSite(env);\n const payload = lowerValue(payloadNode, env, `${env.programName}.emit`);\n return [...payload.statements, { Emit: { effect, payload: payload.expression } }];\n }\n if (ts.isPropertyAccessExpression(expression.expression)) {\n const owner = expression.expression.expression;\n const method = expression.expression.name.text;\n if (ts.isIdentifier(owner) && env.variables.has(owner.text) && method === \"push\") {\n if (expression.arguments.length === 0) refuse(env, \"E_OPAQUE\", expression, \"push requires at least one value\");\n requireCollectionMutation(owner, expression, env);\n return expression.arguments.flatMap((value) => {\n const info = env.variables.get(owner.text)!;\n appendCollectionFacts(info, value, env,\n collectionMutationIncrement(info, owner.text, env), collectionOriginsBinding);\n const lowered = lowerValue(value, env, `${env.programName}.${owner.text}`);\n return [...lowered.statements, { Push: { target: owner.text, value: lowered.expression } } satisfies Stmt];\n });\n }\n if (ts.isIdentifier(owner) && env.variables.get(owner.text)?.collection === \"Map\" && method === \"set\") {\n requireCollectionMutation(owner, expression, env);\n const key = expression.arguments[0];\n const value = expression.arguments[1];\n if (!key || !value) refuse(env, \"E_OPAQUE\", expression, \"Map.set requires key and value\");\n requirePrimitiveCollectionIdentity(key, env, \"Map keys\");\n const loweredKey = lowerValue(key, env);\n const loweredValue = lowerValue(value, env);\n const info = env.variables.get(owner.text)!;\n const priorMax = info.max;\n const increment = collectionMutationIncrement(info, owner.text, env);\n appendCollectionFacts(info, value, env, increment, collectionOriginsBinding);\n if (info.max === undefined && priorMax !== undefined) {\n info.max = priorMax + increment;\n info.boundSource = `${value.getText(env.sourceFile)} Map.set bound`;\n }\n return [\n ...lowerMapAssignment(owner.text, loweredKey, loweredValue, info.max ?? 0, info.boundSource, env),\n ];\n }\n if (ts.isIdentifier(owner) && env.variables.get(owner.text)?.collection === \"Set\" && method === \"add\") {\n requireCollectionMutation(owner, expression, env);\n const value = expression.arguments[0];\n if (!value) refuse(env, \"E_OPAQUE\", expression, \"Set.add requires a value\");\n requirePrimitiveCollectionIdentity(value, env, \"Set values\");\n const loweredValue = lowerValue(value, env);\n const valueName = temporary(env, \"setValue\");\n const found = lowerCollectionLookup(owner, { Variable: valueName }, env, \"SetHas\");\n const info = env.variables.get(owner.text)!;\n const priorMax = info.max;\n const increment = collectionMutationIncrement(info, owner.text, env);\n appendCollectionFacts(info, value, env, increment, collectionOriginsBinding);\n if (info.max === undefined && priorMax !== undefined) {\n info.max = priorMax + increment;\n info.boundSource = `${value.getText(env.sourceFile)} Set.add bound`;\n }\n return [\n ...loweredValue.statements,\n { Let: { name: valueName, value: loweredValue.expression } },\n ...found.statements,\n { If: {\n condition: { Unary: { op: \"Not\", value: found.expression } },\n then_body: [{ Push: { target: owner.text, value: { Variable: valueName } } }],\n else_body: [],\n } },\n ];\n }\n if (isDb(owner, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n return lowerDbStatement(method, expression, env);\n }\n }\n }\n if (ts.isPostfixUnaryExpression(expression) || ts.isPrefixUnaryExpression(expression)) {\n if ((expression.operator === ts.SyntaxKind.PlusPlusToken || expression.operator === ts.SyntaxKind.MinusMinusToken)\n && ts.isIdentifier(expression.operand)) {\n return [{ Assign: {\n name: expression.operand.text,\n value: {\n Binary: {\n op: expression.operator === ts.SyntaxKind.PlusPlusToken ? \"Add\" : \"Sub\",\n left: { Variable: expression.operand.text },\n right: literal(1),\n },\n },\n } }];\n }\n }\n if (ts.isBinaryExpression(expression)\n && expression.operatorToken.kind === ts.SyntaxKind.EqualsToken\n && ts.isIdentifier(expression.left)) {\n const info = env.variables.get(expression.left.text);\n recordAssignmentOrigin(info, expression.right, env);\n const bound = derivedBound(expression.right, env);\n if (info) mergeAssignedCollectionFacts(info, expression.right, env, bound.max, bound.boundSource);\n return [{ Assign: { name: expression.left.text, value: lowerExpr(expression.right, env) } }];\n }\n if (ts.isConditionalExpression(expression)) {\n const condition = lowerValue(expression.condition, env);\n const thenBranch = forkBranchEnvironment(env);\n const elseBranch = forkBranchEnvironment(env);\n const thenBody = lowerExpressionStatement(expression.whenTrue, thenBranch.environment);\n const elseBody = lowerExpressionStatement(expression.whenFalse, elseBranch.environment);\n mergeBranchEnvironments(env, [thenBranch, elseBranch], expression);\n return [...condition.statements, { If: {\n condition: condition.expression,\n then_body: thenBody,\n else_body: elseBody,\n } }];\n }\n refuse(env, \"E_OPAQUE\", expression, \"expression statement does not lower to a data operation\");\n}\n\nfunction lowerDbStatement(method: string, call: ts.CallExpression, env: Environment): Stmt[] {\n if (method === \"require\" || method === \"assert\") {\n const condition = call.arguments[0];\n if (!condition) refuse(env, \"E_OPAQUE\", call, `${method} requires a condition`);\n const codeNode = call.arguments[1];\n const code = stringArgument(codeNode) ?? (method === \"assert\" ? \"ASSERTION_FAILED\" : \"REQUIRE_FAILED\");\n refuseReservedAuthCode(env, codeNode, code);\n const lowered = lowerValue(condition, env);\n const narrowed = nonNullIdentifier(condition);\n if (narrowed) {\n const info = env.variables.get(narrowed);\n if (info) info.nullableRead = false;\n }\n return [...lowered.statements, { Require: {\n condition: lowered.expression,\n code,\n } }];\n }\n const target = call.arguments[0];\n const table = target && tableReference(target, env).table;\n if (!table) refuse(env, \"E_OPAQUE\", call, `${method} requires a static table`);\n if (method === \"insert\") {\n const row = call.arguments[1];\n if (!row) refuse(env, \"E_OPAQUE\", call, \"insert requires a row\");\n reserveWriteSite(env);\n const lowered = lowerValue(row, env);\n return [...lowered.statements, { Insert: { table, row: lowered.expression } }];\n }\n if (method === \"delete\") {\n const key = call.arguments[1];\n if (!key) refuse(env, \"E_OPAQUE\", call, \"delete requires a key\");\n reserveWriteSite(env);\n return [{ Delete: { table, key: lowerExpr(key, env) } }];\n }\n if (method === \"update\" || method === \"upsert\") {\n const key = call.arguments[1];\n const row = call.arguments[2];\n if (!key || !row) refuse(env, \"E_OPAQUE\", call, `${method} requires key and row/patch`);\n if (ts.isArrayLiteralExpression(unwrapExpression(key))) {\n refuse(\n env,\n \"E_OPAQUE\",\n key,\n `${method} with a composite identity cannot be represented by S1's scalar write key`,\n );\n }\n if (isFunctionLike(row)) return lowerCallbackWrite(method, target!, table, key, row, env);\n if (method === \"update\" && knownObjectFields(row, env)?.includes(\"id\")) {\n refuse(env, \"E_SCHEMA_ID_RESERVED\", row, \"update patches cannot contain id\", \"remove id from the update patch\");\n }\n reserveWriteSite(env);\n // The write call itself owns the first ordinal; its operands then lower in\n // authored order (key before patch/row), including any nested reads.\n const loweredKey = lowerExpr(key, env);\n const lowered = lowerPatch(row, env);\n if (method === \"upsert\" && upsertIdentityMatches(\n loweredKey,\n lowered,\n (name) => env.variables.get(name)?.identityExpression,\n ) === false) {\n refuse(\n env,\n \"E_SCHEMA_ID_RESERVED\",\n row,\n \"upsert key and row id must be one identity\",\n \"const rowId = ctx.newId(); db.upsert(table, rowId, { ...row, id: rowId })\",\n );\n }\n return method === \"update\"\n ? [{ Update: { table, key: loweredKey, patch: lowered } }]\n : [{ Upsert: { table, key: loweredKey, row: lowered } }];\n }\n refuse(env, \"E_OPAQUE\", call, `db.${method} is not part of the S1 IR`);\n}\nfunction lowerCallbackWrite(\n method: \"update\" | \"upsert\",\n target: ts.Expression,\n table: string,\n key: ts.Expression,\n callback: ts.ArrowFunction | ts.FunctionExpression,\n env: Environment,\n): Stmt[] {\n if (callback.parameters.length !== 1 || !ts.isIdentifier(callback.parameters[0]!.name)) {\n refuse(env, \"E_OPAQUE\", callback, \"write callback must have one identifier parameter\");\n }\n if (ts.isBlock(callback.body) && !env.source.startsWith(\"// GENERATED by the Snapback 2 Quarry front end from \")) {\n refuse(env, \"E_OPAQUE\", callback.body, \"write callback body must be an expression\");\n }\n const callbackResult = ts.isBlock(callback.body) ? finalCallbackReturn(callback.body, env) : callback.body;\n if (method === \"update\" && knownObjectFields(callbackResult, env)?.includes(\"id\")) {\n refuse(env, \"E_SCHEMA_ID_RESERVED\", callbackResult, \"update patches cannot contain id\", \"remove id from the update patch\");\n }\n const ref = tableReference(target, env);\n if (method === \"upsert\" && ref.index !== \"byId\") {\n refuse(env, \"E_OPAQUE\", target, \"upsert callbacks require a table primary key\");\n }\n const site = allocateReadSite(env);\n reserveWriteSite(env);\n // A callback write performs one synthetic current-row read and one write at\n // the authored call site. Lower each authored operand once after those sites,\n // in source order, so a nested key read precedes callback-body reads.\n const loweredKey = lowerKey(key, env);\n const authoredKey = loweredKey[0]!;\n const keyTemporary = containsRead(authoredKey) ? temporary(env, `${singular(table)}WriteKey`) : undefined;\n const scalarKey: Expr = keyTemporary ? { Variable: keyTemporary } : authoredKey;\n const current = temporary(env, `${singular(table)}Current`);\n const callbackEnv = cloneEnvironment(env);\n callbackEnv.substitutions.set(\n callback.parameters[0].name.text,\n { expression: syntheticIdentifier(env.sourceFile, current), environment: callbackEnv },\n );\n callbackEnv.variables.set(current, { provenance: \"Shape\", rowBinding: true });\n const lowered = ts.isBlock(callback.body)\n ? lowerBlockCallback(callback.body, callbackEnv, `${env.programName}.${singular(table)}Write`)\n : lowerValue(callback.body, callbackEnv, `${env.programName}.${singular(table)}Write`);\n if (method === \"upsert\" && upsertIdentityMatches(\n scalarKey,\n lowered.expression,\n (name) => env.variables.get(name)?.identityExpression,\n ) === false) {\n refuse(\n env,\n \"E_SCHEMA_ID_RESERVED\",\n callbackResult,\n \"upsert key and row id must be one identity\",\n \"bind the identity once and use that binding for both the upsert key and row id\",\n );\n }\n const statements: Stmt[] = keyTemporary ? [{ Let: { name: keyTemporary, value: authoredKey } }] : [];\n statements.push({ Let: {\n name: current,\n value: { Get: {\n site,\n table: ref.table,\n index: ref.index,\n key: [scalarKey],\n provenance: readProvenance(key, env),\n } },\n } });\n if (method === \"update\") {\n statements.push({ Require: {\n condition: { Binary: { op: \"Ne\", left: { Variable: current }, right: literal(null) } },\n code: \"NOT_FOUND\",\n } });\n }\n statements.push(...lowered.statements);\n if (method === \"update\") {\n statements.push({ Update: { table, key: scalarKey, patch: lowered.expression } });\n } else {\n // @ref LLP 1001#1-store-storers \u2014 retain addressed Upsert IR so both physical branches enforce key = row.id.\n statements.push({ Upsert: { table, key: scalarKey, row: lowered.expression } });\n }\n return statements;\n}\nfunction finalCallbackReturn(body: ts.Block, env: Environment): ts.Expression {\n const final = body.statements.at(-1);\n if (!final || !ts.isReturnStatement(final) || !final.expression) {\n refuse(env, \"E_OPAQUE\", body, \"write callback block must end with a returned patch expression\");\n }\n return final.expression;\n}\nfunction lowerBlockCallback(body: ts.Block, env: Environment, hint: string): LoweredValue {\n const expression = finalCallbackReturn(body, env);\n const statements = lowerStatements(body.statements.slice(0, -1), env);\n const returned = lowerValue(expression, env, hint);\n return { statements: [...statements, ...returned.statements], expression: returned.expression };\n}\nfunction lowerValue(node: ts.Expression, env: Environment, hint?: string): LoweredValue {\n const value = unwrapExpression(node);\n if (ts.isConditionalExpression(value)) {\n const name = temporary(env, \"conditional\");\n const condition = lowerValue(value.condition, env);\n const whenTrue = lowerValue(value.whenTrue, cloneEnvironment(env), hint);\n const whenFalse = lowerValue(value.whenFalse, cloneEnvironment(env), hint);\n return {\n statements: [\n ...condition.statements,\n { Let: { name, value: literal(null) } },\n { If: {\n condition: condition.expression,\n then_body: [...whenTrue.statements, { Assign: { name, value: whenTrue.expression } }],\n else_body: [...whenFalse.statements, { Assign: { name, value: whenFalse.expression } }],\n } },\n ],\n expression: { Variable: name },\n };\n }\n if (ts.isBinaryExpression(value)) {\n const op = binaryOperator(value.operatorToken.kind);\n const nullish = value.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken;\n if (!op && !nullish) return { statements: [], expression: lowerExpr(value, env, hint) };\n const left = lowerValue(value.left, env, hint);\n const right = lowerValue(value.right, env, hint);\n if (op === \"And\" || op === \"Or\" || nullish) {\n const leftName = temporary(env, \"logicalLeft\");\n const result = temporary(env, \"logicalResult\");\n const condition = nullish\n ? { Binary: { op: \"Eq\" as const, left: { Variable: leftName } satisfies Expr, right: literal(null) } }\n : op === \"And\"\n ? { Variable: leftName }\n : { Unary: { op: \"Not\" as const, value: { Variable: leftName } } };\n return {\n statements: [\n ...left.statements,\n { Let: { name: leftName, value: left.expression } },\n { Let: { name: result, value: { Variable: leftName } } },\n { If: {\n condition,\n then_body: [...right.statements, { Assign: { name: result, value: right.expression } }],\n else_body: [],\n } },\n ],\n expression: { Variable: result },\n };\n }\n return {\n statements: [...left.statements, ...right.statements],\n expression: { Binary: { op: op!, left: left.expression, right: right.expression } },\n };\n }\n if (ts.isPrefixUnaryExpression(value)\n && (value.operator === ts.SyntaxKind.ExclamationToken || value.operator === ts.SyntaxKind.MinusToken)) {\n const operand = lowerValue(value.operand, env, hint);\n return {\n statements: operand.statements,\n expression: {\n Unary: {\n op: value.operator === ts.SyntaxKind.ExclamationToken ? \"Not\" : \"Neg\",\n value: operand.expression,\n },\n },\n };\n }\n if (ts.isPropertyAccessExpression(value)) {\n if (ts.isIdentifier(value.expression)\n && env.variables.get(value.expression.text)?.operationComposite) {\n return { statements: [], expression: lowerExpr(value, env, hint) };\n }\n if (ts.isPropertyAccessChain(value)) return lowerOptionalPropertyChain(value, env, lowerValue, hint);\n const base = lowerValue(value.expression, env, hint);\n return {\n statements: base.statements,\n expression: lowerPropertyValue(value, base.expression, env),\n };\n }\n if (ts.isObjectLiteralExpression(value)) {\n const statements: Stmt[] = [];\n const object: Record<string, Expr> = Object.create(null);\n for (const property of value.properties) {\n try {\n if (ts.isSpreadAssignment(property)) {\n const nullable = nullableReadSpread(property.expression, env);\n if (nullable) nullableSpreadRefusal(property, env, nullable);\n const fields = knownObjectFields(property.expression, env);\n if (!fields) {\n const spread = property.expression.getText(env.sourceFile);\n refuse(env, \"E_OPAQUE\", property, \"object spread requires a statically known object shape; spell its fields explicitly\",\n replaceNode(env.source, property, `field: ${spread}.field`));\n }\n if (ts.isIdentifier(property.expression)\n && env.variables.get(property.expression.text)?.operationComposite === \"args\") {\n for (const field of fields) object[field] = { Variable: field };\n continue;\n }\n const lowered = lowerValue(property.expression, env, hint);\n statements.push(...lowered.statements);\n if (\"Object\" in lowered.expression) {\n for (const [field, expression] of Object.entries(lowered.expression.Object)) object[field] = expression;\n continue;\n }\n let base = lowered.expression;\n if (fields.length > 1 && !(\"Variable\" in base)) {\n const name = temporary(env, \"spread\");\n statements.push({ Let: { name, value: base } });\n base = { Variable: name };\n }\n for (const field of fields) object[field] = { Field: { base, name: field } };\n continue;\n }\n if (ts.isShorthandPropertyAssignment(property)) {\n object[property.name.text] = lowerExpr(property.name, env);\n continue;\n }\n if (!ts.isPropertyAssignment(property)) refuse(env, \"E_OPAQUE\", property, \"object member is outside the subset\");\n const name = propertyName(property.name);\n if (!name) refuse(env, \"E_OPAQUE\", property.name, \"computed object keys are unsupported\");\n const lowered = lowerValue(property.initializer, env, hint ? `${hint}.${name}` : name);\n statements.push(...lowered.statements);\n object[name] = lowered.expression;\n } catch (error) {\n captureRefusal(env.diagnostics, error);\n }\n }\n return { statements, expression: { Object: object } };\n }\n if (ts.isArrayLiteralExpression(value)) {\n const statements: Stmt[] = [];\n const segments: Expr[] = [];\n let plain: Expr[] = [];\n const flush = () => {\n if (plain.length) segments.push({ Array: plain });\n plain = [];\n };\n for (const element of value.elements) {\n try {\n if (ts.isSpreadElement(element)) {\n if (staticBound(element.expression, env) === undefined) {\n const spread = element.expression.getText(env.sourceFile);\n refuse(env, \"E_OPAQUE\", element, \"array spread requires a statically bounded array; spell its elements explicitly\",\n replaceNode(env.source, element, `${spread}[0], ${spread}[1]`));\n }\n flush();\n const lowered = lowerValue(element.expression, env, hint);\n statements.push(...lowered.statements);\n segments.push(lowered.expression);\n } else {\n const lowered = lowerValue(element, env, hint);\n statements.push(...lowered.statements);\n plain.push(lowered.expression);\n }\n } catch (error) {\n captureRefusal(env.diagnostics, error);\n }\n }\n flush();\n return {\n statements,\n expression: segments.length === 0\n ? { Array: [] }\n : segments.length === 1\n ? segments[0]!\n : concatExpressions(segments),\n };\n }\n if (ts.isNewExpression(value)) return lowerCollectionConstructor(value, env, lowerValue, hint);\n if (ts.isCallExpression(value)) {\n const method = memberName(value.expression);\n if (method && ts.isPropertyAccessExpression(value.expression)\n && ts.isIdentifier(value.expression.expression)) {\n const owner = value.expression.expression;\n const info = env.variables.get(owner.text);\n const key = value.arguments[0];\n if (info?.collection === \"Map\" && (method === \"get\" || method === \"has\") && key) {\n requirePrimitiveCollectionIdentity(key, env, \"Map keys\");\n const loweredKey = lowerValue(key, env, hint);\n const found = lowerCollectionLookup(owner, loweredKey.expression, env, method === \"get\" ? \"MapGet\" : \"MapHas\");\n return { statements: [...loweredKey.statements, ...found.statements], expression: found.expression };\n }\n if (info?.collection === \"Set\" && method === \"has\" && key) {\n requirePrimitiveCollectionIdentity(key, env, \"Set values\");\n const loweredKey = lowerValue(key, env, hint);\n const found = lowerCollectionLookup(owner, loweredKey.expression, env, \"SetHas\");\n return { statements: [...loweredKey.statements, ...found.statements], expression: found.expression };\n }\n }\n if (method === \"slice\" && ts.isPropertyAccessExpression(value.expression)) {\n if (value.arguments.length !== 2) refuse(env, \"E_OPAQUE\", value, \"slice requires start and end arguments\");\n const owner = lowerValue(value.expression.expression, env, hint);\n const args = value.arguments.map((argument) => lowerValue(argument, env));\n return {\n statements: [...owner.statements, ...args.flatMap((argument) => argument.statements)],\n expression: { Builtin: {\n builtin: \"Slice\",\n args: [owner.expression, ...args.map((argument) => argument.expression)],\n } },\n };\n }\n if (method === \"sort\" && ts.isPropertyAccessExpression(value.expression)) {\n const owner = lowerValue(value.expression.expression, env, hint);\n return {\n statements: owner.statements,\n expression: lowerSortExpression(owner.expression, value.arguments[0], env),\n };\n }\n if (method && [\"map\", \"flatMap\", \"filter\", \"reduce\", \"some\"].includes(method)\n && ts.isPropertyAccessExpression(value.expression)) {\n return lowerArrayMethod(method, value.expression.expression, value, env, lowerValue, hint);\n }\n if (method === \"require\" && ts.isPropertyAccessExpression(value.expression)) {\n const base = lowerValue(value.expression.expression, env, hint);\n const name = temporary(env, \"required\");\n return {\n statements: [\n ...base.statements,\n { Let: { name, value: base.expression } },\n { Require: {\n condition: { Binary: { op: \"Ne\", left: { Variable: name }, right: literal(null) } },\n code: \"REQUIRED_ROW_MISSING\",\n } },\n ],\n expression: { Variable: name },\n };\n }\n if (isDbInsertCall(value, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n const target = value.arguments[0];\n const row = value.arguments[1];\n if (!target || !row) refuse(env, \"E_OPAQUE\", value, \"insert requires table and row\");\n reserveWriteSite(env);\n const loweredRow = lowerValue(row, env, hint);\n const rowName = temporary(env, \"insertRow\"); // @ref LLP 1007#3-finding-where-check-is-green-and-the-runtime-is-red \u2014 evaluate impure row members once for storage and return.\n return { statements: [\n ...loweredRow.statements, { Let: { name: rowName, value: loweredRow.expression } },\n { Insert: { table: tableReference(target, env).table, row: { Variable: rowName } } },\n ], expression: { Variable: rowName } };\n }\n if (ts.isIdentifier(value.expression) && value.expression.text === \"mergeByIndex\") {\n return lowerMergeByIndex(value, env, hint, lowerValue, lowerExpr);\n }\n if (ts.isIdentifier(value.expression) && [\"top\", \"mergeByTime\", \"intersectById\"].includes(value.expression.text)) {\n return lowerCollectionBuiltin(value.expression.text, value, env, hint);\n }\n }\n return { statements: [], expression: lowerExpr(value, env, hint) };\n}\nfunction concatExpressions(expressions: Expr[]): Expr {\n return expressions.slice(1).reduce<Expr>(\n (left, right) => ({ Builtin: { builtin: \"Concat\", args: [left, right] } }),\n expressions[0]!,\n );\n}\nfunction lowerCollectionBuiltin(name: string, call: ts.CallExpression, env: Environment, hint?: string): LoweredValue {\n const valueNode = name === \"top\" ? call.arguments[1] : call.arguments[0];\n if (!valueNode) refuse(env, \"E_OPAQUE\", call, `${name} requires a bounded collection`);\n const lowered = lowerValue(valueNode, env, hint);\n let expression = lowered.expression;\n if (name === \"mergeByTime\") {\n const inputs = \"Array\" in expression ? expression.Array : [expression];\n expression = inputs.length === 0 ? { Array: [] } : concatExpressions(inputs);\n }\n if (name !== \"intersectById\") {\n expression = { Builtin: {\n builtin: { Sort: { keys: [{ field: \"at\", order: \"Desc\" }] } },\n args: [expression],\n } };\n }\n const limitNode = name === \"top\" ? call.arguments[0] : call.arguments[1];\n if (limitNode) expression = { Builtin: { builtin: \"Slice\", args: [expression, literal(0), lowerExpr(limitNode, env)] } };\n return { statements: lowered.statements, expression };\n}\n", "import ts from \"typescript\";\nimport { propertyName, replaceNode, unwrapExpression } from \"./syntax\";\n\nexport type ArgumentEntry = {\n name: string;\n value: ts.Expression;\n node: ts.PropertyAssignment;\n};\n\nexport type ExpandedArguments = {\n entries: ArgumentEntry[];\n invalidSpread?: ts.SpreadAssignment;\n invalidProperty?: ts.ObjectLiteralElementLike;\n};\n\nexport function expandArgumentObject(object: ts.ObjectLiteralExpression): ExpandedArguments {\n const constants = moduleArgumentObjects(object.getSourceFile());\n const entries = new Map<string, ArgumentEntry>();\n const active = new Set<ts.ObjectLiteralExpression>();\n let invalidSpread: ts.SpreadAssignment | undefined;\n let invalidProperty: ts.ObjectLiteralElementLike | undefined;\n\n const expand = (value: ts.ObjectLiteralExpression): void => {\n if (active.has(value)) return;\n active.add(value);\n for (const property of value.properties) {\n if (invalidSpread || invalidProperty) break;\n if (ts.isSpreadAssignment(property)) {\n const spread = unwrapExpression(property.expression);\n const target = ts.isIdentifier(spread) ? constants.get(spread.text) : undefined;\n if (!target || active.has(target)) invalidSpread = property;\n else expand(target);\n continue;\n }\n if (!ts.isPropertyAssignment(property)) {\n invalidProperty = property;\n continue;\n }\n const name = propertyName(property.name);\n if (!name) {\n invalidProperty = property;\n continue;\n }\n entries.delete(name);\n entries.set(name, { name, value: property.initializer, node: property });\n }\n active.delete(value);\n };\n\n expand(object);\n return { entries: [...entries.values()], invalidSpread, invalidProperty };\n}\n\nexport function argumentSpreadRewrite(source: string, spread: ts.SpreadAssignment): string {\n const value = spread.expression.getText(spread.getSourceFile());\n return replaceNode(source, spread, `field: ${value}.field`);\n}\n\nfunction moduleArgumentObjects(sourceFile: ts.SourceFile): Map<string, ts.ObjectLiteralExpression> {\n const objects = new Map<string, ts.ObjectLiteralExpression>();\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const value = unwrapExpression(declaration.initializer);\n if (ts.isObjectLiteralExpression(value)) objects.set(declaration.name.text, value);\n }\n }\n return objects;\n}\n", "import ts from \"typescript\";\nimport type { Expr, Value } from \"./ir\";\n\nexport type SnapbackSymbol = \"query\" | \"mutation\" | \"effect\" | \"channel\" | \"table\" | \"schema\" | \"seed\" | \"emit\";\n\nconst snapbackSymbols = new Set<SnapbackSymbol>([\n \"query\", \"mutation\", \"effect\", \"channel\", \"table\", \"schema\", \"seed\", \"emit\",\n]);\n\nexport function snapbackCallName(call: ts.CallExpression, sourceFile = call.getSourceFile()): SnapbackSymbol | undefined {\n const named = new Map<string, SnapbackSymbol>();\n const namespaces = new Set<string>();\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)\n || statement.moduleSpecifier.text !== \"snapback2\") continue;\n const bindings = statement.importClause?.namedBindings;\n if (bindings && ts.isNamedImports(bindings)) {\n for (const item of bindings.elements) {\n const imported = item.propertyName?.text ?? item.name.text;\n if (snapbackSymbols.has(imported as SnapbackSymbol)) named.set(item.name.text, imported as SnapbackSymbol);\n }\n } else if (bindings && ts.isNamespaceImport(bindings)) {\n namespaces.add(bindings.name.text);\n }\n }\n if (ts.isIdentifier(call.expression)) {\n return named.get(call.expression.text);\n }\n if (ts.isPropertyAccessExpression(call.expression) && ts.isIdentifier(call.expression.expression)\n && namespaces.has(call.expression.expression.text)\n && snapbackSymbols.has(call.expression.name.text as SnapbackSymbol)) {\n return call.expression.name.text as SnapbackSymbol;\n }\n return undefined;\n}\n\nexport function findAncestor<T extends ts.Node>(node: ts.Node, predicate: (node: ts.Node) => node is T): T | undefined {\n let parent = node.parent;\n while (parent) {\n if (predicate(parent)) return parent;\n parent = parent.parent;\n }\n return undefined;\n}\n\nexport function replaceNode(source: string, node: ts.Node, replacement: string): string {\n return source.slice(0, node.getStart()) + replacement + source.slice(node.getEnd());\n}\n\nexport function applyEdits(source: string, edits: Array<{ start: number; end: number; text: string }>): string {\n return edits\n .sort((a, b) => b.start - a.start)\n .reduce((text, edit) => text.slice(0, edit.start) + edit.text + text.slice(edit.end), source);\n}\n\nexport function containsIncrement(node: ts.Node): boolean {\n let found = false;\n walk(node, (child) => {\n if ((ts.isPostfixUnaryExpression(child) || ts.isPrefixUnaryExpression(child))\n && (child.operator === ts.SyntaxKind.PlusPlusToken || child.operator === ts.SyntaxKind.MinusMinusToken)) found = true;\n });\n return found;\n}\n\nexport function containsCall(node: ts.Node, suffix: string): boolean {\n let found = false;\n walk(node, (child) => {\n if (ts.isCallExpression(child) && callName(child).endsWith(suffix)) found = true;\n });\n return found;\n}\n\nexport function firstDescendantCall(node: ts.Node, suffix: string): ts.CallExpression | undefined {\n let found: ts.CallExpression | undefined;\n walk(node, (child) => {\n if (!found && ts.isCallExpression(child) && callName(child).endsWith(suffix)) found = child;\n });\n return found;\n}\n\nexport function findNarrowestNode(sourceFile: ts.SourceFile, position: number): ts.Node {\n let best: ts.Node = sourceFile;\n const visit = (node: ts.Node) => {\n if (node.getFullStart() <= position && position < node.getEnd()) {\n best = node;\n ts.forEachChild(node, visit);\n }\n };\n visit(sourceFile);\n return best;\n}\n\nexport function previousStatement(sourceFile: ts.SourceFile, node: ts.Statement): ts.Statement | undefined {\n const statements = statementSiblings(sourceFile, node);\n const index = statements?.indexOf(node) ?? -1;\n return index > 0 ? statements![index - 1] : undefined;\n}\n\nexport function nextStatement(sourceFile: ts.SourceFile, node: ts.Statement): ts.Statement | undefined {\n const statements = statementSiblings(sourceFile, node);\n const index = statements?.indexOf(node) ?? -1;\n return index >= 0 ? statements![index + 1] : undefined;\n}\n\nfunction statementSiblings(sourceFile: ts.SourceFile, node: ts.Statement): readonly ts.Statement[] | undefined {\n if (node.parent === sourceFile) return sourceFile.statements;\n if (ts.isBlock(node.parent)) return node.parent.statements;\n return undefined;\n}\n\nexport function walk(node: ts.Node, visit: (node: ts.Node) => void): void {\n visit(node);\n ts.forEachChild(node, (child) => walk(child, visit));\n}\n\nexport function hasExport(node: ts.Node): boolean {\n return ts.canHaveModifiers(node)\n && !!ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);\n}\n\nexport function hasAsyncModifier(node: ts.Node): boolean {\n return !!ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword);\n}\n\nexport function isFunctionLike(node: ts.Node): node is ts.ArrowFunction | ts.FunctionExpression {\n return ts.isArrowFunction(node) || ts.isFunctionExpression(node);\n}\n\nexport function isEffectFunction(node: ts.Node): boolean {\n let current: ts.Node | undefined = node.parent;\n while (current && !ts.isSourceFile(current)) {\n if (ts.isCallExpression(current) && snapbackCallName(current) === \"effect\") return true;\n if (ts.isVariableStatement(current)) return false;\n current = current.parent;\n }\n return false;\n}\n\nexport function unwrapCall(node: ts.Expression): ts.CallExpression | undefined {\n const value = unwrapExpression(node);\n return ts.isCallExpression(value) ? value : undefined;\n}\n\nexport function unwrapExpression(node: ts.Expression): ts.Expression {\n let value = node;\n while (ts.isParenthesizedExpression(value) || ts.isAsExpression(value) || ts.isNonNullExpression(value)) value = value.expression;\n return value;\n}\n\nexport function staticMemberPath(node: ts.Expression): string | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) return value.text;\n if (!ts.isPropertyAccessExpression(value)) return undefined;\n const base = staticMemberPath(value.expression);\n return base ? `${base}.${value.name.text}` : undefined;\n}\n\nexport function callName(call: ts.CallExpression): string {\n return call.expression.getText();\n}\n\nexport function descriptorName(call: ts.CallExpression): string | undefined {\n if (ts.isIdentifier(call.expression)) return call.expression.text;\n return ts.isPropertyAccessExpression(call.expression) ? call.expression.name.text : undefined;\n}\n\nexport function memberName(node: ts.LeftHandSideExpression): string | undefined {\n return ts.isPropertyAccessExpression(node) ? node.name.text : undefined;\n}\n\nexport function collectionConstructor(node: ts.Expression): \"Map\" | \"Set\" | undefined {\n const value = unwrapExpression(node);\n if (!ts.isNewExpression(value) || !ts.isIdentifier(value.expression)) return undefined;\n return value.expression.text === \"Map\" || value.expression.text === \"Set\" ? value.expression.text : undefined;\n}\n\ntype DbBinding = (name: string) => boolean;\n\nexport function isDb(node: ts.Expression, binding: DbBinding): boolean {\n return ts.isIdentifier(node) && binding(node.text);\n}\n\nexport function isDbMember(node: ts.LeftHandSideExpression, binding: DbBinding): boolean {\n return ts.isPropertyAccessExpression(node) && isDb(node.expression, binding);\n}\n\nexport function isDbWriteCall(node: ts.Expression, binding: DbBinding): node is ts.CallExpression {\n const call = unwrapCall(node);\n return !!call && ts.isPropertyAccessExpression(call.expression) && isDb(call.expression.expression, binding)\n && [\"insert\", \"update\", \"upsert\", \"delete\", \"require\", \"assert\"].includes(call.expression.name.text);\n}\n\nexport function isDbInsertCall(node: ts.Expression, binding: DbBinding): boolean {\n const call = unwrapCall(node);\n return !!call && ts.isPropertyAccessExpression(call.expression) && isDb(call.expression.expression, binding)\n && call.expression.name.text === \"insert\";\n}\n\nexport function isNullableDbGet(node: ts.Expression, binding: DbBinding): boolean {\n const call = unwrapCall(node);\n return !!call && ts.isPropertyAccessExpression(call.expression)\n && isDb(call.expression.expression, binding) && call.expression.name.text === \"get\";\n}\n\nexport function nonNullIdentifier(node: ts.Expression): string | undefined {\n const value = unwrapExpression(node);\n if (!ts.isBinaryExpression(value) || ![\n ts.SyntaxKind.ExclamationEqualsToken,\n ts.SyntaxKind.ExclamationEqualsEqualsToken,\n ].includes(value.operatorToken.kind)) return undefined;\n if (ts.isIdentifier(value.left) && value.right.kind === ts.SyntaxKind.NullKeyword) return value.left.text;\n return ts.isIdentifier(value.right) && value.left.kind === ts.SyntaxKind.NullKeyword ? value.right.text : undefined;\n}\n\nexport function temporary(holder: { temp: { value: number } } | { value: number }, label: string): string {\n const temp = \"temp\" in holder ? holder.temp : holder;\n const value = temp.value++;\n return `__${label}${value}`;\n}\n\nexport function syntheticIdentifier(_sourceFile: ts.SourceFile, name: string): ts.Identifier {\n return ts.factory.createIdentifier(name);\n}\n\nexport function propertyName(name: ts.PropertyName): string | undefined {\n return ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : undefined;\n}\n\nexport function expressionProperty(object: ts.ObjectLiteralExpression, name: string): ts.Expression | undefined {\n const property = object.properties.find((item): item is ts.PropertyAssignment =>\n ts.isPropertyAssignment(item) && propertyName(item.name) === name);\n return property?.initializer;\n}\n\nexport function numberProperty(object: ts.ObjectLiteralExpression, name: string): number | undefined {\n return numericLiteral(expressionProperty(object, name));\n}\n\nexport function numericLiteral(node: ts.Expression | undefined): number | undefined {\n return node && ts.isNumericLiteral(unwrapExpression(node)) ? Number((unwrapExpression(node) as ts.NumericLiteral).text) : undefined;\n}\n\nexport function expandedNumericLiteral(text: string): { whole: string; fraction: string } | undefined {\n const match = text.replaceAll(\"_\", \"\").match(/^(?:(\\d+)(?:\\.(\\d*))?|\\.(\\d+))(?:e([+-]?\\d+))?$/i);\n if (!match) return undefined;\n const integer = match[1] ?? \"0\";\n const authoredFraction = match[2] ?? match[3] ?? \"\";\n const exponent = Number(match[4] ?? 0);\n const digits = `${integer}${authoredFraction}`;\n const point = integer.length + exponent;\n const whole = (point <= 0 ? \"0\" : point >= digits.length ? digits.padEnd(point, \"0\") : digits.slice(0, point))\n .replace(/^0+(?=\\d)/, \"\");\n const fraction = (point <= 0 ? `${\"0\".repeat(-point)}${digits}` : point >= digits.length ? \"\" : digits.slice(point))\n .replace(/0+$/, \"\");\n return { whole: whole || \"0\", fraction };\n}\n\nexport function stringLiteral(node: ts.Expression | undefined): string | undefined {\n const value = node && unwrapExpression(node);\n return value && ts.isStringLiteralLike(value) ? value.text : undefined;\n}\n\nexport function stringArgument(node: ts.Expression | undefined): string | undefined {\n return stringLiteral(node);\n}\n\nexport function isZero(node: ts.Expression | undefined): boolean {\n return numericLiteral(node) === 0;\n}\n\nexport function literal(value: null | boolean | number | string): Expr {\n let encoded: Value;\n if (value === null) encoded = \"Null\";\n else if (typeof value === \"boolean\") encoded = { Bool: value };\n else if (typeof value === \"number\") encoded = { Int: value };\n else encoded = { String: value };\n return { Literal: encoded };\n}\n\nexport function binaryOperator(kind: ts.SyntaxKind): string | undefined {\n return new Map<ts.SyntaxKind, string>([\n [ts.SyntaxKind.EqualsEqualsEqualsToken, \"Eq\"],\n [ts.SyntaxKind.EqualsEqualsToken, \"Eq\"],\n [ts.SyntaxKind.ExclamationEqualsEqualsToken, \"Ne\"],\n [ts.SyntaxKind.ExclamationEqualsToken, \"Ne\"],\n [ts.SyntaxKind.LessThanToken, \"Lt\"],\n [ts.SyntaxKind.LessThanEqualsToken, \"Lte\"],\n [ts.SyntaxKind.GreaterThanToken, \"Gt\"],\n [ts.SyntaxKind.GreaterThanEqualsToken, \"Gte\"],\n [ts.SyntaxKind.PlusToken, \"Add\"],\n [ts.SyntaxKind.MinusToken, \"Sub\"],\n [ts.SyntaxKind.AsteriskToken, \"Mul\"],\n [ts.SyntaxKind.AmpersandAmpersandToken, \"And\"],\n [ts.SyntaxKind.BarBarToken, \"Or\"],\n ]).get(kind);\n}\n\nexport function singular(table: string): string {\n return table.endsWith(\"ies\") ? `${table.slice(0, -3)}y` : table.endsWith(\"s\") ? table.slice(0, -1) : table;\n}\n\nexport function lowerFirst(value: string): string {\n return value ? value[0]!.toLowerCase() + value.slice(1) : value;\n}\n\nexport function identifierFromArgsOrLocal(\n node: ts.Expression,\n isOperationArgs: (name: string) => boolean,\n): string | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) return value.text;\n if (ts.isPropertyAccessExpression(value)) {\n const base = unwrapExpression(value.expression);\n if (ts.isIdentifier(base) && isOperationArgs(base.text)) return value.name.text;\n }\n return undefined;\n}\n\nexport function expansionContext(parent: string, node: ts.Node, sourceFile: ts.SourceFile): string {\n return `${parent}/${node.getStart(sourceFile)}`;\n}\n\nexport function contextualNodeKey(context: string, node: ts.Node, sourceFile: ts.SourceFile): string {\n return `${context}:${node.getStart(sourceFile)}:${node.getEnd()}:${node.kind}`;\n}\n", "import ts from \"typescript\";\nimport type { DiagnosticCode, FrontendDiagnostic, Span } from \"./ir\";\n\nexport type DiagnosticModule = {\n sourceFile: ts.SourceFile;\n source: string;\n fileName: string;\n};\n\nexport class Refusal extends Error {\n constructor(readonly diagnostic: FrontendDiagnostic) {\n super(diagnostic.message);\n }\n}\n\nexport function diagnostic(\n module: Pick<DiagnosticModule, \"sourceFile\" | \"fileName\">,\n code: DiagnosticCode,\n node: ts.Node,\n message: string,\n rewrite: string,\n): FrontendDiagnostic {\n const location = span(module, node);\n return {\n code,\n family: diagnosticFamily(code),\n message,\n site: `${location.file}:${location.line}:${location.column}`,\n rule: diagnosticRule(code),\n rewrite,\n guide: diagnosticGuide(code),\n };\n}\n\nexport function refusal(\n module: DiagnosticModule,\n code: DiagnosticCode,\n node: ts.Node,\n message: string,\n rewrite = module.source,\n): FrontendDiagnostic {\n return diagnostic(module, code, node, message, rewrite);\n}\n\nexport function refuse(\n module: DiagnosticModule,\n code: DiagnosticCode,\n node: ts.Node,\n message: string,\n rewrite = module.source,\n): never {\n throw new Refusal(diagnostic(module, code, node, message, rewrite));\n}\n\nexport function typeDiagnostic(\n code: DiagnosticCode,\n family: FrontendDiagnostic[\"family\"],\n file: string,\n line: number,\n col: number,\n message: string,\n rewrite: string,\n guide: string,\n): FrontendDiagnostic {\n return { code, family, message, site: `${file}:${line}:${col}`, rule: diagnosticRule(code), rewrite, guide };\n}\n\nexport function boundedDiagnostics(\n values: FrontendDiagnostic[],\n limit: number,\n scope: string,\n): FrontendDiagnostic[] {\n const seen = new Set<string>();\n const unique = values.filter((item) => {\n const key = `${item.code}\\0${item.site}\\0${item.message}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n }).sort((left, right) => left.site.localeCompare(right.site) || left.code.localeCompare(right.code));\n if (unique.length <= limit) return unique;\n const kept = unique.slice(0, limit - 1);\n const exemplar = unique[limit - 1]!;\n const more = unique.slice(limit - 1).reduce((total, item) => {\n const represented = item.code === \"E_DIAG_TRUNCATED\" && item.message.match(/^\u2026and (\\d+) more/);\n return total + (represented ? Number(represented[1]) : 1);\n }, 0);\n kept.push({\n ...exemplar,\n code: \"E_DIAG_TRUNCATED\",\n family: \"opaque\",\n message: `\u2026and ${more} more ${scope}`,\n rule: undefined,\n rewrite: `${exemplar.rewrite}\\n// Fix the remaining diagnostics and run snapback2 check again.`,\n guide: \"opaque/subset\",\n });\n return kept;\n}\n\nfunction span(module: Pick<DiagnosticModule, \"sourceFile\" | \"fileName\">, node: ts.Node): Span {\n const start = node.getStart(module.sourceFile);\n const position = module.sourceFile.getLineAndCharacterOfPosition(start);\n return {\n file: module.fileName,\n start,\n end: node.getEnd(),\n line: position.line + 1,\n column: position.character + 1,\n };\n}\n\nfunction diagnosticFamily(code: DiagnosticCode): FrontendDiagnostic[\"family\"] {\n if (code.startsWith(\"E_QUARRY_\")) return \"quarry\";\n if (code.startsWith(\"E_SCHEMA_\")) return \"schema\";\n if (code.startsWith(\"E_RULE_\")) return \"rule\";\n if (code.startsWith(\"E_SEED_\")) return \"input\";\n if (code.startsWith(\"E_EFFECT_\") || code === \"E_EMIT_IN_QUERY\") return \"effect\";\n if (code.startsWith(\"E_ARGS_\") || code === \"E_DECIMAL_SCALE\" || code === \"E_ENUM_VARIANT\") return \"args\";\n if (code.startsWith(\"E_OP_\")) return \"op\";\n if ([\"E_UNBOUND_SCAN\", \"E_UNBOUND_LOOP\", \"E_UNBOUND_COUNT\", \"E_STRUCTURAL_COUNT\", \"E_BOUND\"].includes(code)) {\n return \"bound\";\n }\n return \"opaque\";\n}\n\nfunction diagnosticGuide(code: DiagnosticCode): string {\n if (code === \"E_QUARRY_SYNTAX\") return \"quarry/grammar\";\n if (code === \"E_QUARRY_AMBIGUOUS\") return \"quarry/indexes\";\n if (code === \"E_QUARRY_UNSUPPORTED\") return \"quarry/refusals\";\n if (code === \"E_QUARRY_PLACEMENT\") return \"quarry/projects\";\n if (code === \"E_QUARRY_RETAIN\") return \"quarry/grammar\";\n if (code === \"E_QUARRY_ONLY\") return \"quarry/projects\";\n if (code === \"E_QUARRY_UNKNOWN\") return \"quarry/names\";\n if (code === \"E_UNBOUND_SCAN\") return \"bound/scan\";\n if (code === \"E_UNBOUND_LOOP\") return \"bound/loop\";\n if (code === \"E_UNBOUND_COUNT\" || code === \"E_STRUCTURAL_COUNT\") return \"bound/count\";\n if (code === \"E_BOUND\") return \"bound/ceiling\";\n if (code === \"E_AMBIENT_TIME\") return \"opaque/time\";\n if (code === \"E_PROVENANCE_AMBIGUOUS\") return \"opaque/provenance\";\n if (code === \"E_OP_MODULE_BASENAME\") return \"programs/module-basename\";\n if (code.startsWith(\"E_SCHEMA_\")) return \"schema/project\";\n if (code.startsWith(\"E_RULE_\")) return \"schema/rules\";\n if (code.startsWith(\"E_SEED_\")) return \"schema/seed\";\n if (code.startsWith(\"E_EFFECT_\") || code === \"E_EMIT_IN_QUERY\") return \"effects/authoring\";\n if (code.startsWith(\"E_ARGS_\") || code === \"E_DECIMAL_SCALE\" || code === \"E_ENUM_VARIANT\") return \"programs/types\";\n if (code.startsWith(\"E_OP_\")) return \"programs/operations\";\n return \"opaque/subset\";\n}\n\nfunction diagnosticRule(code: DiagnosticCode): string | undefined {\n const rules: Partial<Record<DiagnosticCode, string>> = {\n E_UNBOUND_SCAN: \"every scan names take\",\n E_UNBOUND_LOOP: \"every loop has a static maximum\",\n E_UNBOUND_COUNT: \"growing populations do not expose exact counts\",\n E_STRUCTURAL_COUNT: \"rules do not leak hidden population structure\",\n E_AMBIENT_TIME: \"programs use ctx.now()\",\n E_PROVENANCE_AMBIGUOUS: \"read keys have one unambiguous origin\",\n E_OP_MODULE_BASENAME: \"module basenames are unique\",\n E_BOUND: \"the certified ceiling is finite\",\n E_EMIT_IN_QUERY: \"only mutations emit effects\",\n };\n return rules[code];\n}\n", "import ts from \"typescript\";\nimport type { Environment, LoweredValue, ProvenanceOrigin, VariableInfo } from \"../compiler\";\nimport { refuse, Refusal } from \"../diagnostics\";\nimport type { Expr, LoopDomain, Scan, Stmt } from \"../ir\";\nimport {\n collectionElementBinding,\n combineProvenance,\n isRowCollectionExpression,\n isRowExpression,\n provenanceBinding,\n readProvenance,\n} from \"./provenance\";\nimport { expandHelper } from \"./helper-expansion\";\nimport {\n arraySpreadRewrite,\n knownObjectFields,\n nullableReadSpread,\n nullableSpreadRefusal,\n objectSpreadRewrite,\n rowCollectionFields,\n} from \"./object-shape\";\nimport {\n binaryOperator,\n callName,\n collectionConstructor,\n contextualNodeKey,\n expressionProperty,\n expandedNumericLiteral,\n identifierFromArgsOrLocal,\n isDbMember,\n isFunctionLike,\n literal,\n numberProperty,\n numericLiteral,\n propertyName,\n replaceNode,\n staticMemberPath,\n stringLiteral,\n syntheticIdentifier,\n temporary,\n unwrapCall,\n unwrapExpression,\n} from \"../syntax\";\nimport { isOperationCompositeBinding, withDirectRewrite } from \"./operation-context\";\nimport { guardedWalk, MAX_RECURSION_DEPTH } from \"./recursion\";\nimport { derivedBound, operationArgumentList, staticBound } from \"./binding-bound\";\nimport { maintainCollectionFacts } from \"./collection-facts\";\nimport { checkScanPrefix, checkTupleCursor } from \"./cursor\";\nimport { isIdType } from \"../authored-types\";\nfunction concatExpressions(expressions: Expr[]): Expr {\n return expressions.slice(1).reduce<Expr>(\n (left, right) => ({ Builtin: { builtin: \"Concat\", args: [left, right] } }),\n expressions[0]!,\n );\n}\nfunction rowFields(target: ts.Expression | undefined, env: Environment): string[] | undefined {\n if (!target) return undefined;\n const value = unwrapExpression(target);\n const binding = ts.isIdentifier(value)\n ? value.text\n : ts.isPropertyAccessExpression(value) && ts.isIdentifier(value.expression)\n ? value.expression.text\n : undefined;\n const columns = binding && env.tables.get(binding)?.columns;\n if (!columns) return undefined;\n return [...new Set([\"id\", ...Object.keys(columns)])];\n}\n\nfunction isKnownRowOrObject(expression: ts.Expression, env: Environment): boolean {\n const value = unwrapExpression(expression);\n if (ts.isIdentifier(value) && env.variables.get(value.text)?.rowCollection) return false;\n return knownObjectFields(expression, env) !== undefined || isRowExpression(expression, env);\n}\n\nexport function lowerPropertyValue(value: ts.PropertyAccessExpression, base: Expr, env: Environment): Expr {\n const collection = ts.isIdentifier(value.expression)\n ? env.variables.get(value.expression.text)?.collection\n : undefined;\n if ((value.name.text === \"length\" && !isKnownRowOrObject(value.expression, env))\n || (value.name.text === \"size\" && collection)) {\n return { Builtin: { builtin: \"Len\", args: [base] } };\n }\n return { Field: { base, name: value.name.text } };\n}\n\nexport function lowerOptionalPropertyChain(\n value: ts.PropertyAccessChain,\n env: Environment,\n lowerValue: (node: ts.Expression, env: Environment, hint?: string) => LoweredValue,\n hint?: string,\n): LoweredValue {\n const segments: ts.PropertyAccessExpression[] = [];\n let baseNode: ts.Expression = value;\n while (ts.isPropertyAccessChain(baseNode)) {\n segments.unshift(baseNode);\n baseNode = baseNode.expression;\n }\n const base = lowerValue(baseNode, env, hint);\n const baseName = temporary(env, \"optionalBase\");\n const result = temporary(env, \"optionalValue\");\n const lowerSegments = (index: number, current: Expr): Stmt[] => {\n const segment = segments[index]!;\n const accessed = lowerPropertyValue(segment, current, env);\n const body = index === segments.length - 1\n ? [{ Assign: { name: result, value: accessed } } satisfies Stmt]\n : (() => {\n const next = temporary(env, \"optionalStep\");\n return [\n { Let: { name: next, value: accessed } } satisfies Stmt,\n ...lowerSegments(index + 1, { Variable: next }),\n ];\n })();\n return segment.questionDotToken\n ? [{ If: {\n condition: { Binary: { op: \"Ne\", left: current, right: literal(null) } },\n then_body: body,\n else_body: [],\n } }]\n : body;\n };\n return {\n statements: [\n ...base.statements,\n { Let: { name: baseName, value: base.expression } },\n { Let: { name: result, value: literal(null) } },\n ...lowerSegments(0, { Variable: baseName }),\n ],\n expression: { Variable: result },\n };\n}\n\nexport function loopDomainMaximum(domain: LoopDomain): number {\n if (\"Page\" in domain) {\n return \"Literal\" in domain.Page.take ? domain.Page.take.Literal : domain.Page.take.Arg.max;\n }\n if (\"LiteralRange\" in domain) {\n return Math.max(0, domain.LiteralRange.end_exclusive - domain.LiteralRange.start);\n }\n if (\"ArgList\" in domain) return domain.ArgList.max;\n if (\"DerivedArray\" in domain) return domain.DerivedArray.max;\n const recurse = domain.Recurse;\n if (recurse.fanout === 0) return 1;\n if (recurse.fanout === 1) return recurse.depth + 1;\n const total = (recurse.fanout ** (recurse.depth + 1) - 1) / (recurse.fanout - 1);\n return Number.isSafeInteger(total) ? total : Number.MAX_SAFE_INTEGER;\n}\n\nexport function lowerCoalesce(\n node: ts.BinaryExpression,\n env: Environment,\n hint: string | undefined,\n lowerValue: (node: ts.Expression, env: Environment, hint?: string) => LoweredValue,\n): LoweredValue {\n const name = temporary(env, \"coalesce\");\n if (ts.isPropertyAccessExpression(node.left) && node.left.questionDotToken) {\n const base = lowerValue(node.left.expression, env, hint);\n const right = lowerValue(node.right, env, hint);\n const baseName = temporary(env, \"optional\");\n return {\n statements: [\n ...base.statements,\n { Let: { name: baseName, value: base.expression } },\n ...right.statements,\n { Let: { name, value: right.expression } },\n { If: {\n condition: { Binary: { op: \"Ne\", left: { Variable: baseName }, right: literal(null) } },\n then_body: [{ Assign: { name, value: { Field: { base: { Variable: baseName }, name: node.left.name.text } } } }],\n else_body: [],\n } },\n ],\n expression: { Variable: name },\n };\n }\n const left = lowerValue(node.left, env, hint);\n const right = lowerValue(node.right, env, hint);\n const leftName = temporary(env, \"optional\");\n return {\n statements: [\n ...left.statements,\n { Let: { name: leftName, value: left.expression } },\n ...right.statements,\n { Let: { name, value: right.expression } },\n { If: {\n condition: { Binary: { op: \"Ne\", left: { Variable: leftName }, right: literal(null) } },\n then_body: [{ Assign: { name, value: { Variable: leftName } } }],\n else_body: [],\n } },\n ],\n expression: { Variable: name },\n };\n}\nexport function lowerPatch(node: ts.Expression, env: Environment): Expr {\n if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {\n if (node.parameters.length !== 1 || !ts.isIdentifier(node.parameters[0]!.name)) {\n refuse(env, \"E_OPAQUE\", node, \"write callback must have one identifier parameter\");\n }\n if (ts.isBlock(node.body)) refuse(env, \"E_OPAQUE\", node.body, \"write callback body must be an expression\");\n const callbackEnv = cloneEnvironment(env);\n const name = node.parameters[0].name.text;\n callbackEnv.variables.set(name, { provenance: \"Shape\", rowBinding: true });\n return lowerExpr(node.body, callbackEnv);\n }\n return lowerExpr(node, env);\n}\n\nexport function lowerDomain(\n expression: ts.Expression,\n env: Environment,\n binding: string,\n hint?: string,\n): { domain: LoopDomain; bindingInfo: VariableInfo } {\n return guardedWalk(env, expression, \"loop domain\", () => lowerDomainInner(expression, env, binding, hint));\n}\nfunction lowerDomainInner(\n expression: ts.Expression,\n env: Environment,\n binding: string,\n hint?: string,\n): { domain: LoopDomain; bindingInfo: VariableInfo } {\n const expanded = expandHelper(expression, env);\n if (expanded) return lowerDomain(expanded.expression, expanded.environment, binding, hint);\n const call = unwrapCall(expression);\n if (call && callName(call).endsWith(\".scan\")) {\n const reference = tableReference(call.arguments[0]!, env);\n return {\n domain: { Page: lowerScan(call, env, hint ?? `${env.programName}.${reference.table}`) },\n bindingInfo: { provenance: \"Shape\", objectFields: rowFields(call.arguments[0], env), rowBinding: true, rowTable: reference.table },\n };\n }\n if (call && ts.isIdentifier(call.expression) && call.expression.text === \"range\") {\n const start = numericLiteral(call.arguments[0]);\n const end = numericLiteral(call.arguments[1]);\n if (start === undefined || end === undefined) refuse(env, \"E_UNBOUND_LOOP\", call, \"literal range requires literal endpoints\");\n return { domain: { LiteralRange: { start, end_exclusive: end } }, bindingInfo: { provenance: \"Const\" } };\n }\n if (call && ts.isIdentifier(call.expression) && call.expression.text === \"mentionTokens\") {\n const value = call.arguments[0];\n if (!value) refuse(env, \"E_OPAQUE\", call, \"mentionTokens requires text\");\n return {\n domain: { DerivedArray: {\n value: { Builtin: { builtin: \"MentionTokens\", args: [lowerExpr(value, env)] } },\n max: 85,\n bound_source: \"messages.body max 256 / min whitespace mention 3\",\n } },\n bindingInfo: { provenance: \"Computed\" },\n };\n }\n if (call && ts.isIdentifier(call.expression) && call.expression.text === \"recurse\") {\n return lowerRecurse(call, env);\n }\n const operationList = operationArgumentList(expression, env);\n if (operationList?.max !== undefined) {\n return {\n domain: { ArgList: { name: operationList.name, max: operationList.max } },\n bindingInfo: collectionElementBinding(expression, env),\n };\n }\n const identifier = operationList ? undefined : identifierFromArgsOrLocal(expression, (name) => env.variables.get(name)?.operationComposite === \"args\");\n if (identifier) {\n const info = env.variables.get(identifier);\n if (info?.max !== undefined) {\n if (info.operationArgument && env.args[info.operationArgument]\n && typeof env.args[info.operationArgument] !== \"string\") {\n return {\n domain: { ArgList: { name: info.operationArgument, max: info.max } },\n bindingInfo: collectionElementBinding(expression, env),\n };\n }\n return {\n domain: { DerivedArray: {\n value: { Variable: identifier },\n max: info.max,\n bound_source: info.boundSource ?? `${identifier} declared max`,\n } },\n bindingInfo: {\n provenance: info.provenance,\n ...(info.provenanceAmbiguity ? { provenanceAmbiguity: { ...info.provenanceAmbiguity } } : {}),\n ...(info.rowCollection ? { rowBinding: true, objectFields: info.objectFields } : {}),\n ...(info.elementOrigins ? { alternativeOrigins: info.elementOrigins } : {}),\n },\n };\n }\n }\n const maximum = staticBound(expression, env);\n if (maximum !== undefined) return {\n domain: { DerivedArray: { value: lowerExpr(expression, env), max: maximum,\n bound_source: `${expression.getText(env.sourceFile)} static bound` } },\n bindingInfo: collectionElementBinding(expression, env),\n };\n refuse(env, \"E_UNBOUND_LOOP\", expression, \"loop domain has no static cardinality\");\n}\n\nfunction lowerRecurse(call: ts.CallExpression, env: Environment): { domain: LoopDomain; bindingInfo: VariableInfo } {\n const seed = call.arguments[0];\n const step = call.arguments[1];\n const options = call.arguments[2];\n if (!seed || !step || !isFunctionLike(step) || !options || !ts.isObjectLiteralExpression(options)) {\n refuse(env, \"E_OPAQUE\", call, \"recurse requires seed, inline step, depth, and fanout\");\n }\n const depth = numberProperty(options, \"depth\");\n const fanout = numberProperty(options, \"fanout\");\n if (depth === undefined || fanout === undefined) refuse(env, \"E_UNBOUND_LOOP\", options, \"recurse bounds must be literals\");\n if (depth > 10_000) refuse(env, \"E_UNBOUND_LOOP\", options, \"recurse depth must be at most 10000\");\n if (step.parameters.length !== 1 || !ts.isIdentifier(step.parameters[0]!.name)) {\n refuse(env, \"E_OPAQUE\", step, \"recurse step requires exactly one row parameter\");\n }\n const row = step.parameters[0].name.text;\n const body = ts.isBlock(step.body)\n && step.body.statements.length === 1\n && ts.isReturnStatement(step.body.statements[0])\n ? step.body.statements[0].expression\n : ts.isBlock(step.body) ? undefined : step.body;\n const get = body && unwrapCall(body);\n if (!get || !callName(get).endsWith(\".get\")\n || !isDbMember(get.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n refuse(env, \"E_OPAQUE\", step, \"recurse step must be exactly one get through the operation db binding\");\n }\n const ref = tableReference(get.arguments[0]!, env);\n const key = get.arguments[1];\n if (!key || !ts.isPropertyAccessExpression(key)\n || !ts.isIdentifier(key.expression) || key.expression.text !== row) {\n refuse(env, \"E_OPAQUE\", get, \"recurse step key must be a field of its bound row parameter\");\n }\n return {\n domain: { Recurse: {\n site: allocateReadSite(env),\n table: ref.table,\n index: ref.index,\n seed: lowerExpr(seed, env),\n next_field: key.name.text,\n depth,\n fanout,\n provenance: \"Shape\",\n } },\n bindingInfo: { provenance: \"Shape\", rowBinding: true, rowTable: ref.table },\n };\n}\n\nexport function lowerExpr(node: ts.Expression, env: Environment, hint?: string): Expr {\n return guardedWalk(env, node, \"expression\", () => lowerExprInner(node, env, hint));\n}\n\nfunction lowerExprInner(node: ts.Expression, env: Environment, hint?: string): Expr {\n const substituted = ts.isIdentifier(node) ? env.substitutions.get(node.text) : undefined;\n if (substituted) return lowerExpr(substituted.expression, substituted.environment, hint);\n const unwrapped = unwrapExpression(node);\n if (unwrapped !== node) return lowerExpr(unwrapped, env, hint);\n\n if (node.kind === ts.SyntaxKind.NullKeyword) return literal(null);\n if (node.kind === ts.SyntaxKind.TrueKeyword) return literal(true);\n if (node.kind === ts.SyntaxKind.FalseKeyword) return literal(false);\n if (ts.isNumericLiteral(node)) {\n const scaled = env.literalValues.get(contextualNodeKey(env.literalContext, node, env.sourceFile));\n const expanded = expandedNumericLiteral(node.text);\n const fractional = !Number.isInteger(Number(node.text)) || (expanded?.fraction.length ?? 0) > 0;\n if (fractional && scaled === undefined) {\n const scale = Math.max(1, expanded?.fraction.length ?? 0);\n refuse(\n env,\n \"E_DECIMAL_SCALE\",\n node,\n `fractional literal ${node.text} has no known Decimal scale`,\n replaceNode(env.source, node, `decimal(${node.text}, ${scale})`),\n );\n }\n if (!fractional && scaled === undefined && expanded\n && BigInt(expanded.whole) > 9_007_199_254_740_991n) {\n refuse(\n env,\n \"E_OPAQUE\",\n node,\n `integer literal ${node.text} is outside the safe integer range`,\n replaceNode(env.source, node, \"9007199254740991\"),\n );\n }\n return literal(scaled ?? Number(node.text));\n }\n if (ts.isStringLiteralLike(node)) {\n const authored = env.expressionTypes.get(contextualNodeKey(env.literalContext, node, env.sourceFile));\n return isIdType(authored) && !ts.isVariableDeclaration(node.parent)\n ? { Literal: { Id: node.text } }\n : literal(node.text);\n }\n if (ts.isIdentifier(node)) {\n const info = env.variables.get(node.text);\n const authored = env.expressionTypes.get(contextualNodeKey(env.literalContext, node, env.sourceFile));\n if (isIdType(authored)\n && info?.identityExpression\n && \"Literal\" in info.identityExpression\n && typeof info.identityExpression.Literal === \"object\"\n && info.identityExpression.Literal !== null\n && \"String\" in info.identityExpression.Literal) {\n return { Literal: { Id: info.identityExpression.Literal.String } };\n }\n if (info?.operationComposite === \"args\") {\n return { Object: Object.fromEntries(Object.keys(env.args).map((name) => [name, { Variable: name } satisfies Expr])) };\n }\n if (info?.operationComposite === \"ctx\") return { Object: { viewer: { Input: \"Viewer\" } } };\n return { Variable: node.text };\n }\n if (ts.isArrayLiteralExpression(node)) {\n const segments: Expr[] = [];\n let plain: Expr[] = [];\n const flush = () => {\n if (plain.length > 0) segments.push({ Array: plain });\n plain = [];\n };\n for (const element of node.elements) {\n try {\n if (ts.isSpreadElement(element)) {\n if (staticBound(element.expression, env) === undefined) {\n refuse(\n env,\n \"E_OPAQUE\",\n element,\n \"array spread requires a statically bounded array; spell its elements explicitly\",\n arraySpreadRewrite(env, element),\n );\n }\n flush();\n segments.push(lowerExpr(element.expression, env));\n } else {\n plain.push(lowerExpr(element, env));\n }\n } catch (error) {\n captureRefusal(env, error);\n }\n }\n flush();\n return segments.length === 0 ? { Array: [] } : segments.length === 1 ? segments[0]! : concatExpressions(segments);\n }\n if (ts.isObjectLiteralExpression(node)) {\n const object: Record<string, Expr> = Object.create(null);\n for (const property of node.properties) {\n try {\n if (ts.isSpreadAssignment(property)) {\n const nullable = nullableReadSpread(property.expression, env);\n if (nullable) nullableSpreadRefusal(property, env, nullable);\n const fields = knownObjectFields(property.expression, env);\n if (!fields) {\n refuse(\n env,\n \"E_OPAQUE\",\n property,\n \"object spread requires a statically known object shape; spell its fields explicitly\",\n objectSpreadRewrite(env, property),\n );\n }\n if (ts.isIdentifier(property.expression)\n && env.variables.get(property.expression.text)?.operationComposite === \"args\") {\n for (const field of fields) object[field] = { Variable: field };\n } else {\n const base = lowerExpr(property.expression, env);\n if (\"Object\" in base) {\n for (const [field, expression] of Object.entries(base.Object)) object[field] = expression;\n } else {\n for (const field of fields) object[field] = { Field: { base, name: field } };\n }\n }\n continue;\n }\n if (ts.isShorthandPropertyAssignment(property)) {\n object[property.name.text] = lowerExpr(property.name, env);\n continue;\n }\n if (!ts.isPropertyAssignment(property)) refuse(env, \"E_OPAQUE\", property, \"object method/property form is unsupported\");\n const name = propertyName(property.name);\n if (!name) refuse(env, \"E_OPAQUE\", property.name, \"computed object keys are unsupported\");\n object[name] = lowerExpr(property.initializer, env, hint ? `${hint}.${name}` : name);\n } catch (error) {\n captureRefusal(env, error);\n }\n }\n return { Object: object };\n }\n if (ts.isPropertyAccessExpression(node)) {\n if (node.questionDotToken) {\n refuse(env, \"E_OPAQUE\", node, \"optional property access must be lowered in a statement-aware expression position\");\n }\n if (ts.isIdentifier(node.expression)) {\n const composite = env.variables.get(node.expression.text)?.operationComposite;\n if (composite === \"args\") return { Variable: node.name.text };\n if (composite === \"ctx\") {\n if (node.name.text === \"viewer\") return { Input: \"Viewer\" };\n if (node.name.text === \"readTime\") return { Input: \"ReadTime\" };\n if (node.name.text === \"commitTime\") return { Input: \"Now\" };\n }\n }\n if (node.name.text === \"length\" && !isKnownRowOrObject(node.expression, env)) {\n return { Builtin: { builtin: \"Len\", args: [lowerExpr(node.expression, env)] } };\n }\n const base = lowerExpr(node.expression, env);\n if (\"Object\" in base && base.Object[node.name.text]) return base.Object[node.name.text]!;\n return { Field: { base, name: node.name.text } };\n }\n if (ts.isBinaryExpression(node)) {\n const op = binaryOperator(node.operatorToken.kind);\n if (!op) refuse(env, \"E_OPAQUE\", node.operatorToken, `operator ${node.operatorToken.getText()} is outside the IR`);\n return { Binary: { op, left: lowerExpr(node.left, env), right: lowerExpr(node.right, env) } };\n }\n if (ts.isPrefixUnaryExpression(node)) {\n if (node.operator === ts.SyntaxKind.ExclamationToken) return { Unary: { op: \"Not\", value: lowerExpr(node.operand, env) } };\n if (node.operator === ts.SyntaxKind.MinusToken) return { Unary: { op: \"Neg\", value: lowerExpr(node.operand, env) } };\n }\n if (ts.isNoSubstitutionTemplateLiteral(node)) return literal(node.text);\n if (ts.isTemplateExpression(node)) {\n const parts: Expr[] = [];\n if (node.head.text) parts.push(literal(node.head.text));\n for (const span of node.templateSpans) {\n parts.push(lowerExpr(span.expression, env));\n if (span.literal.text) parts.push(literal(span.literal.text));\n }\n if (parts.length === 1) return concatExpressions([literal(\"\"), parts[0]!]);\n return concatExpressions(parts);\n }\n if (ts.isCallExpression(node)) return lowerCall(node, env, hint);\n refuse(env, \"E_OPAQUE\", node, `expression ${ts.SyntaxKind[node.kind]} is outside the S1 IR`);\n}\n\nfunction captureRefusal(env: Environment, error: unknown): void {\n if (error instanceof Refusal) env.diagnostics.push(error.diagnostic);\n else throw error;\n}\n\nfunction lowerCall(call: ts.CallExpression, env: Environment, hint?: string): Expr {\n const expanded = expandHelper(call, env);\n if (expanded) return lowerExpr(expanded.expression, expanded.environment, hint);\n const name = callName(call);\n if (name === \"decimal\" && call.arguments[0]) return lowerExpr(call.arguments[0], env, hint);\n const compositeMember = ts.isPropertyAccessExpression(call.expression) ? call.expression : undefined;\n const compositeCall = compositeMember && ts.isIdentifier(compositeMember.expression)\n ? env.variables.get(compositeMember.expression.text)?.operationComposite\n : undefined;\n if (compositeCall === \"ctx\" && compositeMember?.name.text === \"now\") {\n return { Input: env.kind === \"Query\" ? \"ReadTime\" : \"Now\" };\n }\n if (compositeCall === \"ctx\" && compositeMember?.name.text === \"commitTime\") return { Input: \"Now\" };\n if (compositeCall === \"ctx\" && compositeMember?.name.text === \"newId\") return { Input: \"NewId\" };\n if (name.endsWith(\".get\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n return { Get: lowerRead(call, env, hint) };\n }\n if (name.endsWith(\".exists\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n return { Exists: lowerRead(call, env, hint) };\n }\n if (name.endsWith(\".scan\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n return { Scan: lowerScan(call, env, hint) };\n }\n if ([\"normalizeWordPrefix\", \"normalizeHandle\"].includes(name) && call.arguments[0]) {\n return lowerExpr(call.arguments[0], env, hint);\n }\n if (name === \"memberOf\") {\n const conversation = call.arguments[0];\n if (!conversation) refuse(env, \"E_OPAQUE\", call, \"memberOf requires a conversation id\");\n return {\n Exists: {\n site: allocateReadSite(env),\n table: \"memberships\",\n index: \"byConvUser\",\n key: [lowerExpr(conversation, env), { Input: \"Viewer\" }],\n provenance: combineProvenance([readProvenance(conversation, env), \"Viewer\"]),\n },\n };\n }\n if ([\"concat\", \"max\", \"min\", \"divmod\", \"deterministicShare\", \"mentionTokens\"].includes(name)) {\n const builtin = ({\n concat: \"Concat\",\n max: \"Max\",\n min: \"Min\",\n divmod: { Divmod: { remainder_sink: \"lexicographic-id\" } },\n deterministicShare: \"DeterministicShare\",\n mentionTokens: \"MentionTokens\",\n } as Record<string, string | Record<string, unknown>>)[name]!;\n const args = call.arguments.map((arg) => lowerExpr(arg, env));\n const required = name === \"deterministicShare\" ? 3 : name === \"mentionTokens\" ? 1 : 2;\n if (args.length < required || (name !== \"concat\" && name !== \"max\" && name !== \"min\" && args.length !== required)) {\n refuse(env, \"E_OPAQUE\", call, `${name} requires ${required === 1 ? \"one argument\" : required === 2 ? \"at least two arguments\" : \"three arguments\"}`);\n }\n if (name === \"concat\" && args.length > 2) return concatExpressions(args);\n if ((name === \"max\" || name === \"min\") && args.length > 2) {\n return args.slice(1).reduce<Expr>(\n (left, right) => ({ Builtin: { builtin, args: [left, right] } }),\n args[0]!,\n );\n }\n return { Builtin: { builtin, args } };\n }\n if (ts.isPropertyAccessExpression(call.expression)) {\n const method = call.expression.name.text;\n const owner = call.expression.expression;\n if (method === \"count\" || method === \"countCapped\") {\n return { Builtin: {\n builtin: method === \"count\" ? \"Count\" : \"CountCapped\",\n args: [lowerExpr(owner, env, hint)],\n } };\n }\n if (method === \"slice\") {\n if (call.arguments.length !== 2) refuse(env, \"E_OPAQUE\", call, \"slice requires start and end arguments\");\n return { Builtin: { builtin: \"Slice\", args: [lowerExpr(owner, env), ...call.arguments.map((arg) => lowerExpr(arg, env))] } };\n }\n if (method === \"sort\") return lowerSort(owner, call.arguments[0], env);\n }\n refuse(env, \"E_OPAQUE\", call, `helper ${name} is not defined in this module or the pure builtin set`);\n}\n\nfunction lowerSort(owner: ts.Expression, comparator: ts.Expression | undefined, env: Environment): Expr {\n return lowerSortExpression(lowerExpr(owner, env), comparator, env);\n}\n\nexport function lowerSortExpression(owner: Expr, comparator: ts.Expression | undefined, env: Environment): Expr {\n if (!comparator || !isFunctionLike(comparator) || comparator.parameters.length !== 2\n || !ts.isIdentifier(comparator.parameters[0]!.name) || !ts.isIdentifier(comparator.parameters[1]!.name)\n || ts.isBlock(comparator.body)) {\n refuse(env, \"E_OPAQUE\", comparator ?? env.sourceFile, \"sort requires an inline field comparator\");\n }\n const body = comparator.body;\n if (!ts.isBinaryExpression(body) || body.operatorToken.kind !== ts.SyntaxKind.MinusToken\n || !ts.isPropertyAccessExpression(body.left) || !ts.isPropertyAccessExpression(body.right)) {\n refuse(env, \"E_OPAQUE\", body, \"sort comparator must subtract the same scalar field\");\n }\n const leftParam = ts.isIdentifier(body.left.expression) ? body.left.expression.text : \"\";\n const rightParam = ts.isIdentifier(body.right.expression) ? body.right.expression.text : \"\";\n const firstParam = comparator.parameters[0].name.text;\n const secondParam = comparator.parameters[1].name.text;\n if (body.left.name.text !== body.right.name.text\n || !((leftParam === firstParam && rightParam === secondParam)\n || (leftParam === secondParam && rightParam === firstParam))) {\n refuse(env, \"E_OPAQUE\", body, \"sort comparator must subtract the same field from its two opposite parameters\");\n }\n const order = leftParam === firstParam ? \"Asc\" : \"Desc\";\n return { Builtin: {\n builtin: { Sort: { keys: [{ field: body.left.name.text, order }] } },\n args: [owner],\n } };\n}\n\nfunction lowerRead(call: ts.CallExpression, env: Environment, hint?: string) {\n const target = call.arguments[0];\n const key = call.arguments[1];\n if (!target || !key) refuse(env, \"E_OPAQUE\", call, \"point read requires target and key\");\n const ref = tableReference(target, env);\n return {\n site: allocateReadSite(env),\n table: ref.table,\n index: ref.index,\n key: lowerKey(key, env),\n provenance: readProvenance(key, env),\n };\n}\n\nfunction lowerScan(call: ts.CallExpression, env: Environment, hint?: string): Scan {\n const target = call.arguments[0];\n const prefix = call.arguments[1];\n const options = call.arguments[2];\n if (!target || !prefix || !options || !ts.isObjectLiteralExpression(options)) {\n refuse(env, \"E_UNBOUND_SCAN\", call, \"scan requires target, prefix, and options with take\");\n }\n const ref = tableReference(target, env);\n const takeNode = expressionProperty(options, \"take\");\n if (!takeNode) refuse(env, \"E_UNBOUND_SCAN\", call, \"scan options require take\");\n let take: Scan[\"take\"];\n const literalTake = numericLiteral(takeNode);\n if (literalTake !== undefined) {\n take = { Literal: literalTake };\n } else {\n const name = identifierFromArgsOrLocal(\n takeNode,\n (binding) => env.variables.get(binding)?.operationComposite === \"args\",\n );\n const operationArgument = name && env.variables.get(name)?.operationArgument;\n const arg = operationArgument && env.args[operationArgument];\n const max = name && arg && typeof arg !== \"string\" && \"List\" in arg ? arg.List.max : undefined;\n if (!operationArgument || max === undefined) refuse(env, \"E_UNBOUND_SCAN\", takeNode, \"take argument needs a declared max\");\n take = { Arg: { name: operationArgument, max } };\n }\n const orderNode = expressionProperty(options, \"order\");\n const authoredOrder = stringLiteral(orderNode);\n if (orderNode && authoredOrder !== \"asc\" && authoredOrder !== \"desc\") {\n refuse(env, \"E_OPAQUE\", orderNode, 'scan order must be \"asc\" or \"desc\"');\n }\n const rangeNode = expressionProperty(options, \"range\");\n const loweredPrefix = lowerKey(prefix, env);\n const afterNode = expressionProperty(options, \"after\");\n const beforeNode = expressionProperty(options, \"before\");\n const opaqueCursorNode = expressionProperty(options, \"opaqueCursor\");\n const opaqueCursor = opaqueCursorNode?.kind === ts.SyntaxKind.TrueKeyword;\n if (opaqueCursorNode && !opaqueCursor) refuse(env, \"E_OPAQUE\", opaqueCursorNode, \"opaqueCursor is an internal literal true tag\");\n if (checkScanPrefix(prefix, env, ref.table, ref.index, loweredPrefix.length)) {\n if (!opaqueCursor) {\n checkTupleCursor(afterNode, env, ref.table, ref.index, loweredPrefix.length);\n checkTupleCursor(beforeNode, env, ref.table, ref.index, loweredPrefix.length);\n }\n }\n const mergeSiteNode = expressionProperty(options, \"mergeSite\");\n const mergeSite = stringLiteral(mergeSiteNode);\n if (mergeSiteNode && mergeSite === undefined) refuse(env, \"E_OPAQUE\", mergeSiteNode, \"mergeSite must be a static string\");\n return {\n site: allocateReadSite(env),\n table: ref.table,\n index: ref.index,\n prefix: loweredPrefix,\n order: authoredOrder === \"desc\" ? \"Desc\" : \"Asc\",\n take,\n after: optionalLower(afterNode, env),\n before: optionalLower(beforeNode, env),\n range: rangeNode && ts.isObjectLiteralExpression(rangeNode)\n ? {\n gt: optionalLower(expressionProperty(rangeNode, \"gt\"), env),\n gte: optionalLower(expressionProperty(rangeNode, \"gte\"), env),\n lt: optionalLower(expressionProperty(rangeNode, \"lt\"), env),\n lte: optionalLower(expressionProperty(rangeNode, \"lte\"), env),\n }\n : null,\n ...(opaqueCursor ? { opaque_cursor: true } : {}),\n merge_site: mergeSite ?? null,\n provenance: readProvenance(prefix, env),\n };\n}\n\nexport function tableReference(node: ts.Expression, env: Environment): { table: string; index: string } {\n const path = staticMemberPath(node);\n const direct = path && env.tables.get(path);\n if (direct) return { table: direct.name, index: direct.maintainedFrom ? \"byGroup\" : \"byId\" };\n const separator = path?.lastIndexOf(\".\") ?? -1;\n const owner = separator > 0 ? env.tables.get(path!.slice(0, separator)) : undefined;\n if (owner) return { table: owner.name, index: path!.slice(separator + 1) };\n refuse(\n env,\n \"E_OPAQUE\",\n node,\n `static table/index reference required; ${node.getText(env.sourceFile)} does not resolve to an imported table or table.index`,\n replaceNode(env.source, node, \"table.index\"),\n );\n}\n\nexport function lowerKey(node: ts.Expression, env: Environment): Expr[] {\n const value = unwrapExpression(node);\n if (ts.isArrayLiteralExpression(value)) return value.elements.map((element) => lowerExpr(element, env));\n if (ts.isIdentifier(value)) {\n const identity = env.variables.get(value.text)?.identityExpression;\n if (identity && \"Array\" in identity) return identity.Array;\n }\n const lowered = lowerExpr(value, env);\n return \"Array\" in lowered ? lowered.Array : [lowered];\n}\n\nexport function cloneEnvironment(env: Environment): Environment {\n return {\n ...env,\n variables: new Map([...env.variables].map(([name, info]) => [name, { ...info }])),\n substitutions: new Map(env.substitutions),\n helperStack: [...env.helperStack],\n deferredCollectionMutations: new Set(env.deferredCollectionMutations),\n };\n}\n\nexport function enterLexicalScope(env: Environment): Environment {\n return {\n ...env,\n // Declarations and shadows write only to this map. Existing bindings keep\n // their VariableInfo identity so analysis updates survive the scope.\n variables: new Map(env.variables),\n substitutions: new Map(env.substitutions),\n helperStack: [...env.helperStack],\n deferredCollectionMutations: new Set(env.deferredCollectionMutations),\n };\n}\n\n/**\n * Certificate identities are pinned to module + exported operation + the lexical\n * read/write ordinal. The shared counter makes helper rename, extraction/inlining,\n * and whitespace irrelevant; writes reserve ordinals even though today's WriteSite\n * serde shape does not yet expose a site string.\n */\nexport function allocateReadSite(env: Environment): string {\n const site = `${env.siteBase}.${env.accessOrdinal.value}`;\n env.accessOrdinal.value += 1;\n return site;\n}\n\nexport function reserveWriteSite(env: Environment): void {\n env.accessOrdinal.value += 1;\n}\n\nexport function containsRead(value: unknown, seen = new Set<object>(), depth = 0): boolean {\n if (depth >= MAX_RECURSION_DEPTH) return true;\n if (Array.isArray(value)) {\n if (seen.has(value)) return true;\n seen.add(value);\n const result = value.some((item) => containsRead(item, seen, depth + 1));\n seen.delete(value);\n return result;\n }\n if (!value || typeof value !== \"object\") return false;\n const object = value as Record<string, unknown>;\n if (seen.has(object)) return true;\n seen.add(object);\n const result = [\"Get\", \"Exists\", \"Scan\"].some((kind) => kind in object)\n || Object.values(object).some((item) => containsRead(item, seen, depth + 1));\n seen.delete(object);\n return result;\n}\n\nexport function lowerArrayMethod(\n method: string,\n owner: ts.Expression,\n call: ts.CallExpression,\n env: Environment,\n lowerValue: (node: ts.Expression, env: Environment, hint?: string) => LoweredValue,\n hint?: string,\n): LoweredValue {\n const callback = call.arguments[0];\n if (!callback || !isFunctionLike(callback) || callback.parameters.length < 1\n || !ts.isIdentifier(callback.parameters[0]!.name)) {\n refuse(env, \"E_OPAQUE\", call, `${method} requires an inline callback with an identifier`);\n }\n if (ts.isBlock(callback.body)) refuse(env, \"E_OPAQUE\", callback.body, `${method} callback must be an expression`);\n const expectedParameters = method === \"reduce\" ? 2 : 1;\n if (callback.parameters.length !== expectedParameters\n || callback.parameters.some((parameter) => !ts.isIdentifier(parameter.name))) {\n refuse(env, \"E_OPAQUE\", callback, method === \"reduce\"\n ? \"reduce callback requires exactly accumulator and item parameters\"\n : `${method} callback requires exactly one parameter`);\n }\n const binding = callback.parameters[0].name.text;\n const loopEnv = cloneEnvironment(env);\n const { statements: domainStatements, domain, bindingInfo } = lowerCollectionDomain(\n owner,\n loopEnv,\n binding,\n lowerValue,\n hint,\n );\n loopEnv.variables.set(binding, bindingInfo);\n if (method === \"map\" || method === \"filter\") {\n const name = temporary(env, method);\n const lowered = lowerValue(callback.body, loopEnv, hint);\n const body = method === \"map\"\n ? [...lowered.statements, { Push: { target: name, value: lowered.expression } } satisfies import(\"../ir\").Stmt]\n : [...lowered.statements, { If: {\n condition: lowered.expression,\n then_body: [{ Push: { target: name, value: { Variable: binding } } }],\n else_body: [],\n } } satisfies import(\"../ir\").Stmt];\n const resultOrigin = method === \"filter\"\n ? { provenance: bindingInfo.provenance, ...(bindingInfo.provenanceAmbiguity\n ? { provenanceAmbiguity: { ...bindingInfo.provenanceAmbiguity } }\n : {}) }\n : withDirectRewrite(provenanceBinding(callback.body, loopEnv), callback.body, loopEnv);\n const callbackValue = unwrapExpression(callback.body);\n const identityMap = method === \"map\" && ts.isIdentifier(callbackValue) && callbackValue.text === binding;\n const preservesRows = (method === \"filter\" || identityMap) && bindingInfo.rowBinding;\n const elementOrigins = method === \"filter\"\n ? bindingOrigins(bindingInfo)\n : [{ expression: callback.body, environment: loopEnv } satisfies ProvenanceOrigin];\n const bound = derivedBound(owner, env);\n env.variables.set(name, maintainCollectionFacts({\n ...resultOrigin,\n ...(preservesRows ? { rowCollection: true, objectFields: bindingInfo.objectFields } : {}),\n }, { ...bound, elementOrigins }));\n return {\n statements: [...domainStatements, { Let: { name, value: { Array: [] } } }, { For: { binding, domain, body } }],\n expression: { Variable: name },\n };\n }\n if (method === \"flatMap\") {\n const name = temporary(env, \"flatMap\");\n const innerBinding = temporary(env, \"flatItem\");\n const inner = lowerCollectionDomain(callback.body, loopEnv, innerBinding, lowerValue, hint);\n const innerEnv = cloneEnvironment(loopEnv);\n innerEnv.variables.set(innerBinding, inner.bindingInfo);\n env.variables.set(name, maintainCollectionFacts({\n ...inner.bindingInfo,\n ...(inner.bindingInfo.rowBinding\n ? { rowCollection: true, objectFields: inner.bindingInfo.objectFields }\n : {}),\n }, {\n max: loopDomainMaximum(domain) * loopDomainMaximum(inner.domain),\n boundSource: `${call.getText(env.sourceFile)} flatMap bounds`,\n elementOrigins: bindingOrigins(inner.bindingInfo),\n }));\n return {\n statements: [\n ...domainStatements,\n { Let: { name, value: { Array: [] } } },\n { For: {\n binding,\n domain,\n body: [...inner.statements, { For: {\n binding: innerBinding,\n domain: inner.domain,\n body: [{ Push: { target: name, value: { Variable: innerBinding } } }],\n } }],\n } },\n ],\n expression: { Variable: name },\n };\n }\n if (method === \"reduce\") {\n const initial = call.arguments[1];\n if (!initial || callback.parameters.length < 2 || !ts.isIdentifier(callback.parameters[1]!.name)) {\n refuse(env, \"E_OPAQUE\", call, \"reduce requires accumulator, item, and initial value\");\n }\n const accumulator = callback.parameters[0].name.text;\n const item = callback.parameters[1].name.text;\n const reduceEnv = cloneEnvironment(env);\n reduceEnv.variables.set(item, bindingInfo);\n const name = temporary(env, \"reduce\");\n reduceEnv.substitutions.set(accumulator, {\n expression: syntheticIdentifier(env.sourceFile, name),\n environment: reduceEnv,\n });\n const lowered = lowerValue(callback.body, reduceEnv, hint);\n return {\n statements: [\n ...domainStatements,\n { Let: { name, value: lowerExpr(initial, env) } },\n { For: { binding: item, domain, body: [...lowered.statements, { Assign: { name, value: lowered.expression } }] } },\n ],\n expression: { Variable: name },\n };\n }\n const name = temporary(env, \"some\");\n const lowered = lowerValue(callback.body, loopEnv, hint);\n return {\n statements: [\n ...domainStatements,\n { Let: { name, value: literal(false) } },\n { For: {\n binding,\n domain,\n body: [...lowered.statements, { If: {\n condition: lowered.expression,\n then_body: [{ Assign: { name, value: literal(true) } }, \"Break\"],\n else_body: [],\n } }],\n } },\n ],\n expression: { Variable: name },\n };\n}\n\nexport function lowerCollectionDomain(\n expression: ts.Expression,\n env: Environment,\n binding: string,\n lowerValue: (node: ts.Expression, env: Environment, hint?: string) => LoweredValue,\n hint?: string,\n): ReturnType<typeof lowerDomain> & { statements: import(\"../ir\").Stmt[] } {\n const value = unwrapExpression(expression);\n const call = unwrapCall(value);\n const method = call && ts.isPropertyAccessExpression(call.expression) ? call.expression.name.text : undefined;\n if (method && [\"map\", \"flatMap\", \"filter\", \"sort\", \"slice\"].includes(method)) {\n const lowered = lowerValue(expression, env, hint);\n if (\"Variable\" in lowered.expression) {\n const loweredDomain = lowerDomain(syntheticIdentifier(env.sourceFile, lowered.expression.Variable), env, binding, hint);\n return { statements: lowered.statements, ...loweredDomain };\n }\n const maximum = staticBound(expression, env);\n if (maximum === undefined) refuse(env, \"E_UNBOUND_LOOP\", expression, \"loop domain has no static cardinality\");\n const rowCollection = isRowCollectionExpression(expression, env);\n return {\n statements: lowered.statements,\n domain: { DerivedArray: {\n value: lowered.expression,\n max: maximum,\n bound_source: `${expression.getText(env.sourceFile)} static bound`,\n } },\n bindingInfo: rowCollection\n ? { provenance: \"Shape\", rowBinding: true, objectFields: rowCollectionFields(expression, env) }\n : collectionElementBinding(expression, env),\n };\n }\n if (ts.isArrayLiteralExpression(value)) {\n const maximum = staticBound(expression, env);\n if (maximum === undefined) refuse(env, \"E_UNBOUND_LOOP\", expression, \"loop domain has no static cardinality\");\n const lowered = lowerValue(expression, env, hint);\n return {\n statements: lowered.statements,\n domain: { DerivedArray: {\n value: lowered.expression,\n max: maximum,\n bound_source: `${expression.getText(env.sourceFile)} static bound`,\n } },\n bindingInfo: collectionElementBinding(expression, env),\n };\n }\n return { statements: [], ...lowerDomain(expression, env, binding, hint) };\n}\nfunction bindingOrigins(binding: VariableInfo): ProvenanceOrigin[] {\n if (binding.alternativeOrigins) return binding.alternativeOrigins;\n const { elementOrigins: _elements, ...valueBinding } = binding;\n return [{ binding: valueBinding }];\n}\n\nfunction optionalLower(node: ts.Expression | undefined, env: Environment): Expr | null {\n return node ? lowerExpr(node, env) : null;\n}\n", "import ts from \"typescript\";\nimport type { Environment, ProvenanceOrigin, VariableInfo } from \"../compiler\";\nimport { refuse } from \"../diagnostics\";\nimport type { Provenance } from \"../ir\";\nimport { guardedWalk } from \"./recursion\";\nimport {\n callName,\n isDbMember,\n propertyName,\n replaceNode,\n staticMemberPath,\n unwrapCall,\n unwrapExpression,\n} from \"../syntax\";\nimport { collectionElementOrigins, originDirectCandidates, selectExpressionMember, snapshotEnvironment } from \"./collection-origins\";\nimport { expandHelper } from \"./helper-expansion\";\nimport {\n candidateAmbiguity,\n directOriginCandidates,\n isOperationCompositeBinding,\n UNKNOWN_DIRECT_ORIGIN,\n} from \"./operation-context\";\n\ntype Presence = \"required\" | \"optional\";\ntype Classification =\n | { kind: \"known\"; provenance: Provenance; presence: Presence; candidates?: string[] }\n | { kind: \"absent\" }\n | { kind: \"ambiguous\"; directRewrite?: string; candidates?: string[] };\ntype KnownClassification = Extract<Classification, { kind: \"known\" }>;\n\nexport type ProvenanceBinding = Pick<VariableInfo, \"provenance\" | \"provenanceAmbiguity\">;\n\n/**\n * @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 this is the one\n * recursive implementation of the closed provenance rules. A member selection\n * is a path through the same domain as its base: operation composites, helper\n * substitutions, immutable aliases, rows, nested literals, and ordered spreads\n * do not get separate provenance shortcuts.\n */\nexport function provenance(node: ts.Expression, env: Environment): Provenance {\n const result = classify(node, env, [], node);\n return result.kind === \"known\" ? result.provenance : \"Computed\";\n}\n\nexport function readProvenance(node: ts.Expression, env: Environment): Provenance {\n const result = classify(node, env, [], node);\n if (result.kind !== \"known\") {\n refuseAmbiguous(node, env, result.kind === \"ambiguous\" ? result.directRewrite : undefined,\n result.kind === \"ambiguous\" ? result.candidates : undefined);\n }\n return result.provenance;\n}\n\nexport function provenanceBinding(node: ts.Expression, env: Environment): ProvenanceBinding {\n const result = classify(node, env, [], node);\n return result.kind === \"known\"\n ? { provenance: result.provenance }\n : {\n provenance: \"Computed\",\n provenanceAmbiguity: result.kind === \"ambiguous\"\n ? candidateAmbiguity(\n result.candidates ?? (result.directRewrite ? [result.directRewrite] : [UNKNOWN_DIRECT_ORIGIN]),\n )\n : {},\n };\n}\n\nexport function combinedProvenanceBinding(nodes: readonly ts.Expression[], env: Environment): ProvenanceBinding {\n const bindings = nodes.map((node) => provenanceBinding(node, env));\n const ambiguous = bindings.find((binding) => binding.provenanceAmbiguity);\n return ambiguous\n ? { provenance: \"Computed\", provenanceAmbiguity: { ...ambiguous.provenanceAmbiguity } }\n : { provenance: combineProvenance(bindings.map((binding) => binding.provenance)) };\n}\n\nexport function collectionElementBinding(node: ts.Expression, env: Environment): VariableInfo {\n const origins = collectionElementOrigins(node, env);\n if (!origins || origins.length === 0) {\n return { ...provenanceBinding(node, env), provenanceAmbiguity: {} };\n }\n const classified = combineAlternatives(\n origins.map((origin) => classifyOrigin(origin, [], node)),\n \"required\",\n originDirectCandidates(origins),\n );\n return {\n ...(classified.kind === \"known\"\n ? { provenance: classified.provenance }\n : {\n provenance: \"Computed\" as const,\n provenanceAmbiguity: candidateAmbiguity(\n classified.kind === \"ambiguous\"\n ? classified.candidates ?? [UNKNOWN_DIRECT_ORIGIN]\n : originDirectCandidates(origins),\n ),\n }),\n alternativeOrigins: origins,\n };\n}\n\nexport function collectionOriginsBinding(\n origins: readonly ProvenanceOrigin[],\n authoredNode: ts.Expression,\n): ProvenanceBinding {\n const classified = combineAlternatives(\n origins.map((origin) => classifyOrigin(origin, [], authoredNode)),\n \"required\",\n originDirectCandidates(origins),\n );\n return classified.kind === \"known\"\n ? { provenance: classified.provenance }\n : {\n provenance: \"Computed\",\n provenanceAmbiguity: candidateAmbiguity(\n classified.kind === \"ambiguous\" ? classified.candidates ?? originDirectCandidates(origins) : originDirectCandidates(origins),\n ),\n };\n}\n\nfunction classify(\n node: ts.Expression,\n env: Environment,\n path: readonly string[],\n authoredNode: ts.Expression,\n): Classification {\n return guardedWalk(env, node, \"provenance\", () => classifyInner(node, env, path, authoredNode));\n}\n\nfunction classifyInner(\n node: ts.Expression,\n env: Environment,\n path: readonly string[],\n authoredNode: ts.Expression,\n): Classification {\n const value = unwrapExpression(node);\n const substituted = ts.isIdentifier(value) ? env.substitutions.get(value.text) : undefined;\n if (substituted) return classify(substituted.expression, substituted.environment, path, authoredNode);\n\n if (ts.isIdentifier(value)) return classifyIdentifier(value, env, path, authoredNode);\n if (ts.isPropertyAccessExpression(value)) {\n return classify(value.expression, env, [value.name.text, ...path], authoredNode);\n }\n\n if (ts.isStringLiteralLike(value) || ts.isNumericLiteral(value)\n || value.kind === ts.SyntaxKind.NullKeyword || value.kind === ts.SyntaxKind.TrueKeyword\n || value.kind === ts.SyntaxKind.FalseKeyword) {\n return path.length === 0 ? known(\"Const\") : ambiguous();\n }\n\n if (ts.isObjectLiteralExpression(value)) {\n return path.length === 0\n ? classifyObject(value, env, authoredNode)\n : classifyObjectMember(value, env, path, authoredNode);\n }\n if (ts.isArrayLiteralExpression(value)) {\n if (path.length > 0) return ambiguous();\n return combineClassifications(value.elements.map((element) => {\n const expression = ts.isSpreadElement(element) ? element.expression : element;\n return classify(expression, env, [], authoredNode);\n }));\n }\n\n if (ts.isCallExpression(value)) {\n const expanded = expandHelper(value, env);\n if (expanded) return classify(expanded.expression, expanded.environment, path, authoredNode);\n if (isRowCall(value, env)) return classifyRow(value, env, path);\n return path.length === 0 ? known(\"Computed\") : ambiguous();\n }\n\n if (ts.isConditionalExpression(value)) {\n return path.length === 0\n ? known(\"Computed\")\n : combineAlternatives([\n classify(value.whenTrue, env, path, authoredNode),\n classify(value.whenFalse, env, path, authoredNode),\n ], \"required\");\n }\n\n if (ts.isTemplateExpression(value) || ts.isBinaryExpression(value) || ts.isNewExpression(value)\n || ts.isPrefixUnaryExpression(value)) {\n return path.length === 0 ? known(\"Computed\") : ambiguous();\n }\n\n if (path.length > 0) return ambiguous();\n const children: Classification[] = [];\n value.forEachChild((child) => {\n if (ts.isExpression(child)) children.push(classify(child, env, [], authoredNode));\n });\n return combineClassifications(children);\n}\n\nfunction classifyIdentifier(\n node: ts.Identifier,\n env: Environment,\n path: readonly string[],\n authoredNode: ts.Expression,\n): Classification {\n const info = env.variables.get(node.text);\n if (!info) return ambiguous();\n if (info.provenanceAmbiguity) {\n const merged = candidateAmbiguity([\n ...(info.provenanceAmbiguity.candidates ?? []),\n ...(info.provenanceAmbiguity.directRewrite ? [info.provenanceAmbiguity.directRewrite] : []),\n ...(info.elementOrigins ? originDirectCandidates(info.elementOrigins) : []),\n ...(info.alternativeOrigins ? originDirectCandidates(info.alternativeOrigins) : []),\n ]);\n return ambiguous(merged.directRewrite, merged.candidates);\n }\n if (info.operationComposite === \"args\") {\n if (path.length === 0) {\n return Object.keys(env.args).length === 0 ? known(\"Const\") : known(\"Arg\");\n }\n const descriptor = env.args[path[0]!];\n if (!descriptor) return absent();\n return {\n ...known(\"Arg\"),\n presence: typeof descriptor !== \"string\" && \"Optional\" in descriptor ? \"optional\" : \"required\",\n };\n }\n if (info.operationComposite === \"ctx\") {\n if (path.length === 0) return known(\"Viewer\");\n return path[0] === \"viewer\" ? known(\"Viewer\") : absent();\n }\n if (info.alternativeOrigins) {\n return combineAlternatives(\n info.alternativeOrigins.map((origin) => classifyOrigin(origin, path, authoredNode)),\n \"required\",\n originDirectCandidates(info.alternativeOrigins),\n );\n }\n if (info.rowBinding) return classifyBoundRow(info, path);\n if (info.immutableOrigin) {\n return classify(info.immutableOrigin.expression, info.immutableOrigin.environment, path, authoredNode);\n }\n if (path.length === 0 || info.provenance === \"Arg\" || info.provenance === \"Viewer\" || info.provenance === \"Const\") {\n return known(info.provenance);\n }\n return ambiguous();\n}\n\nfunction classifyOrigin(\n origin: ProvenanceOrigin,\n path: readonly string[],\n authoredNode: ts.Expression,\n): Classification {\n return \"expression\" in origin\n ? classify(origin.expression, origin.environment, path, authoredNode)\n : classifyBinding(origin.binding, path, authoredNode);\n}\n\nfunction classifyBinding(\n info: VariableInfo,\n path: readonly string[],\n authoredNode: ts.Expression,\n): Classification {\n if (info.provenanceAmbiguity) {\n return ambiguous(info.provenanceAmbiguity.directRewrite, info.provenanceAmbiguity.candidates);\n }\n if (info.alternativeOrigins) {\n return combineAlternatives(\n info.alternativeOrigins.map((origin) => classifyOrigin(origin, path, authoredNode)),\n \"required\",\n originDirectCandidates(info.alternativeOrigins),\n );\n }\n if (info.rowBinding) return classifyBoundRow(info, path);\n if (path.length === 0) return known(info.provenance);\n return ambiguous();\n}\n\nfunction classifyObject(\n node: ts.ObjectLiteralExpression,\n env: Environment,\n authoredNode: ts.Expression,\n): Classification {\n const members: Classification[] = [];\n for (const property of node.properties) {\n if (ts.isSpreadAssignment(property)) {\n members.push(classify(property.expression, env, [], authoredNode));\n } else if (ts.isShorthandPropertyAssignment(property)) {\n members.push(classify(property.name, env, [], authoredNode));\n } else if (ts.isPropertyAssignment(property)) {\n members.push(classify(property.initializer, env, [], authoredNode));\n } else {\n members.push(ambiguous());\n }\n }\n return combineClassifications(members);\n}\n\nfunction classifyObjectMember(\n node: ts.ObjectLiteralExpression,\n env: Environment,\n path: readonly string[],\n authoredNode: ts.Expression,\n): Classification {\n const [selected, ...rest] = path;\n const laterOptional: Classification[] = [];\n for (const property of [...node.properties].reverse()) {\n let candidate: Classification | undefined;\n if (ts.isSpreadAssignment(property)) {\n candidate = classify(property.expression, env, path, authoredNode);\n const selectedOrigins = selectExpressionMember(property.expression, env, selected!);\n if (selectedOrigins.kind === \"found\") {\n candidate = withCandidates(candidate, originDirectCandidates(selectedOrigins.origins));\n }\n } else if (ts.isShorthandPropertyAssignment(property) && property.name.text === selected) {\n candidate = withCandidates(\n classify(property.name, env, rest, authoredNode),\n [...directOriginCandidates(property.name, env)],\n );\n } else if (ts.isPropertyAssignment(property) && propertyName(property.name) === selected) {\n candidate = withCandidates(\n classify(property.initializer, env, rest, authoredNode),\n [...directOriginCandidates(property.initializer, env)],\n );\n }\n if (!candidate || candidate.kind === \"absent\") continue;\n if (candidate.kind === \"ambiguous\") return candidate;\n if (candidate.presence === \"optional\") {\n laterOptional.push(candidate);\n continue;\n }\n return combineAlternatives([...laterOptional, candidate], \"required\");\n }\n return laterOptional.length > 0 ? combineAlternatives(laterOptional, \"optional\") : absent();\n}\n\nfunction classifyBoundRow(info: VariableInfo, path: readonly string[]): Classification {\n if (path.length === 0) return known(\"Shape\");\n if (info.objectFields && !info.objectFields.includes(path[0]!)) return absent();\n if (path.length > 1) return ambiguous();\n return { ...known(\"Shape\"), presence: info.nullableRead ? \"optional\" : \"required\" };\n}\n\nfunction classifyRow(call: ts.CallExpression, env: Environment, path: readonly string[]): Classification {\n if (path.length === 0) return known(\"Shape\");\n const fields = rowFields(call.arguments[0], env);\n if (fields && !fields.includes(path[0]!)) return absent();\n if (path.length > 1) return ambiguous();\n return { ...known(\"Shape\"), presence: \"optional\" };\n}\n\nfunction combineClassifications(values: Classification[]): Classification {\n const ambiguousValue = values.find((value) => value.kind === \"ambiguous\");\n if (ambiguousValue?.kind === \"ambiguous\") return ambiguousValue;\n const provenances = values.flatMap((value) => value.kind === \"known\" ? [value.provenance] : []);\n return known(combineProvenance(provenances));\n}\n\nfunction combineAlternatives(\n values: Classification[],\n presence: Presence,\n candidates: string[] = [],\n): Classification {\n const knownValues = values.filter((value): value is KnownClassification => value.kind === \"known\");\n const inherited = values.flatMap((value) => value.kind === \"absent\"\n ? []\n : value.candidates ?? (value.kind === \"ambiguous\" && value.directRewrite ? [value.directRewrite] : []));\n const allCandidates = [...new Set([...candidates, ...inherited])];\n if (knownValues.length !== values.length) {\n const incomplete = values.some((value) => value.kind === \"absent\"\n || value.kind === \"ambiguous\" && !value.directRewrite && (value.candidates?.length ?? 0) === 0);\n return ambiguous(undefined, incomplete\n ? [...new Set([...allCandidates, UNKNOWN_DIRECT_ORIGIN])]\n : allCandidates);\n }\n const first = knownValues[0]?.provenance;\n if (!first || knownValues.some((value) => value.provenance !== first)) return ambiguous(undefined, allCandidates);\n return {\n kind: \"known\",\n provenance: first,\n presence,\n ...(allCandidates.length > 0 ? { candidates: allCandidates } : {}),\n };\n}\n\nfunction known(provenance: Provenance, candidates?: string[]): KnownClassification {\n return {\n kind: \"known\",\n provenance,\n presence: \"required\",\n ...(candidates && candidates.length > 0 ? { candidates } : {}),\n };\n}\n\nfunction absent(): Classification {\n return { kind: \"absent\" };\n}\n\nfunction ambiguous(directRewrite?: string, candidates?: string[]): Classification {\n return {\n kind: \"ambiguous\",\n ...(directRewrite ? { directRewrite } : {}),\n ...(candidates && candidates.length > 0 ? { candidates } : {}),\n };\n}\n\nfunction withCandidates(value: Classification, candidates: string[]): Classification {\n if (value.kind === \"absent\" || candidates.length === 0) return value;\n return { ...value, candidates: [...new Set([...(value.candidates ?? []), ...candidates])] };\n}\n\nfunction isRowCall(call: ts.CallExpression, env: Environment): boolean {\n return callName(call).endsWith(\".get\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env));\n}\n\nfunction rowFields(target: ts.Expression | undefined, env: Environment): string[] | undefined {\n if (!target) return undefined;\n const path = staticMemberPath(target);\n const binding = path?.split(\".\")[0];\n const columns = binding && env.tables.get(binding)?.columns;\n return columns ? [...new Set([\"id\", ...Object.keys(columns)])] : undefined;\n}\n\nfunction refuseAmbiguous(\n node: ts.Expression,\n env: Environment,\n directRewrite?: string,\n directCandidates?: string[],\n): never {\n const value = unwrapExpression(node);\n const choices: string[] = [];\n const replacementFor = (expression: ts.Expression, direct?: string, candidates?: string[]): string => {\n const choice = honestRewrite(expression, env, direct, candidates);\n choices.push(...choice.candidates);\n return choice.replacement;\n };\n const replacement = ts.isArrayLiteralExpression(value)\n ? `[${value.elements.map((element) => {\n const expression = ts.isSpreadElement(element) ? element.expression : element;\n const classified = classify(expression, env, [], node);\n return classified.kind === \"known\"\n ? element.getText(env.sourceFile)\n : classified.kind === \"ambiguous\" && classified.directRewrite\n ? replacementFor(expression, classified.directRewrite)\n : replacementFor(expression, undefined, classified.kind === \"ambiguous\" ? classified.candidates : undefined);\n }).join(\", \")}]`\n : replacementFor(value, directRewrite, directCandidates);\n const candidates = [...new Set(choices)];\n const candidateMessage = candidates.length > 0 ? `; candidate direct origins: ${candidates.join(\", \")}` : \"\";\n refuse(\n env,\n \"E_PROVENANCE_AMBIGUOUS\",\n node,\n `read key provenance is ambiguous; each key must follow one direct origin rule${candidateMessage}`,\n replaceNode(env.source, node, replacement),\n );\n}\n\nfunction honestRewrite(\n node: ts.Expression,\n env: Environment,\n directRewrite?: string,\n directCandidates?: string[],\n): { replacement: string; candidates: string[] } {\n const discovered = [...new Set([\n ...(directCandidates ?? []),\n ...(directRewrite ? [directRewrite] : []),\n ])];\n if (discovered.length === 1 && discovered[0] !== UNKNOWN_DIRECT_ORIGIN) {\n return { replacement: discovered[0]!, candidates: discovered };\n }\n if (discovered.length > 1) return sentinelRewrite(discovered);\n return sentinelRewrite(discovered.length === 0 ? [UNKNOWN_DIRECT_ORIGIN] : discovered);\n}\n\nfunction sentinelRewrite(candidates: string[]): { replacement: string; candidates: string[] } {\n const description = candidates.length > 0 ? candidates.join(\" | \") : \"no bound direct origins\";\n return {\n replacement: `(() => { throw new Error(${JSON.stringify(`E_PROVENANCE_AMBIGUOUS: choose one direct origin: ${description}`)}); })()`,\n candidates,\n };\n}\n\nexport function combineProvenance(values: Provenance[]): Provenance {\n if (values.includes(\"Computed\")) return \"Computed\";\n const meaningful = new Set(values.filter((value) => value !== \"Const\"));\n if (meaningful.size === 0) return \"Const\";\n if (meaningful.size === 1) return [...meaningful][0]!;\n return \"Shape\";\n}\n\nexport { expandHelper } from \"./helper-expansion\";\n\nexport function isRowExpression(node: ts.Expression, env: Environment): boolean {\n return guardedWalk(env, node, \"row expression\", () => isRowExpressionInner(node, env));\n}\n\nfunction isRowExpressionInner(node: ts.Expression, env: Environment): boolean {\n const value = unwrapExpression(node);\n const substituted = ts.isIdentifier(value) ? env.substitutions.get(value.text) : undefined;\n if (substituted) return isRowExpression(substituted.expression, substituted.environment);\n if (ts.isIdentifier(value)) return env.variables.get(value.text)?.rowBinding === true;\n const call = unwrapCall(value);\n if (!call) return false;\n const expanded = expandHelper(call, env);\n if (expanded) return isRowExpression(expanded.expression, expanded.environment);\n return isRowCall(call, env);\n}\n\nexport function isRowCollectionExpression(node: ts.Expression, env: Environment): boolean {\n return guardedWalk(env, node, \"row collection\", () => isRowCollectionExpressionInner(node, env));\n}\n\nfunction isRowCollectionExpressionInner(node: ts.Expression, env: Environment): boolean {\n const value = unwrapExpression(node);\n const substituted = ts.isIdentifier(value) ? env.substitutions.get(value.text) : undefined;\n if (substituted) return isRowCollectionExpression(substituted.expression, substituted.environment);\n if (ts.isIdentifier(value)) return env.variables.get(value.text)?.rowCollection === true;\n const call = unwrapCall(value);\n if (!call) return false;\n const expanded = expandHelper(call, env);\n if (expanded) return isRowCollectionExpression(expanded.expression, expanded.environment);\n if (callName(call).endsWith(\".scan\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))) return true;\n if (!ts.isPropertyAccessExpression(call.expression)) return false;\n if ([\"filter\", \"sort\", \"slice\"].includes(call.expression.name.text)) {\n return isRowCollectionExpression(call.expression.expression, env);\n }\n if (call.expression.name.text === \"flatMap\") {\n if (!isRowCollectionExpression(call.expression.expression, env)) return false;\n const callback = call.arguments[0];\n if (!callback || !ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)\n || callback.parameters.length === 0 || !ts.isIdentifier(callback.parameters[0]!.name)\n || ts.isBlock(callback.body)) return false;\n const body = unwrapExpression(callback.body);\n if (!ts.isArrayLiteralExpression(body)) return false;\n const callbackEnv = snapshotEnvironment(env);\n callbackEnv.variables.set(callback.parameters[0].name.text, {\n provenance: \"Shape\",\n rowBinding: true,\n objectFields: rowFields(call.expression.expression, env),\n });\n return body.elements.every((element) => !ts.isSpreadElement(element) && isRowExpression(element, callbackEnv));\n }\n if (call.expression.name.text !== \"map\") return false;\n const callback = call.arguments[0];\n if (!callback || !ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)\n || callback.parameters.length === 0 || !ts.isIdentifier(callback.parameters[0]!.name)\n || ts.isBlock(callback.body)) return false;\n const body = unwrapExpression(callback.body);\n return ts.isIdentifier(body) && body.text === callback.parameters[0].name.text\n && isRowCollectionExpression(call.expression.expression, env);\n}\n", "import ts from \"typescript\";\nimport type { Environment } from \"../compiler\";\nimport { refuse } from \"../diagnostics\";\nimport { replaceNode } from \"../syntax\";\n\nexport type RecursionState = { depth: number; active: Map<ts.Node, Set<string>> };\n\nexport const MAX_RECURSION_DEPTH = 128;\n\nexport function guardedWalk<T>(\n env: Environment,\n node: ts.Node,\n kind: string,\n walk: () => T,\n): T {\n const activeKinds = env.recursion.active.get(node);\n if (env.recursion.depth >= MAX_RECURSION_DEPTH || activeKinds?.has(kind)) {\n return refuseRecursiveWalk(env, node);\n }\n env.recursion.depth += 1;\n if (activeKinds) activeKinds.add(kind);\n else env.recursion.active.set(node, new Set([kind]));\n try {\n return walk();\n } finally {\n const remaining = env.recursion.active.get(node);\n remaining?.delete(kind);\n if (remaining?.size === 0) env.recursion.active.delete(node);\n env.recursion.depth -= 1;\n }\n}\n\nexport function refuseRecursiveWalk(env: Environment, node: ts.Node): never {\n const expression = ts.isExpression(node) ? node : undefined;\n const rewrite = expression\n ? replaceNode(\n env.source,\n expression,\n \"PROVENANCE_ORIGIN_REQUIRED(/* choose one direct origin; recursive expansion was refused */)\",\n )\n : `${env.source}\\n// E_PROVENANCE_AMBIGUOUS: replace the recursive value with one direct origin.`;\n refuse(\n env,\n \"E_PROVENANCE_AMBIGUOUS\",\n node,\n `provenance expansion is recursive or exceeds ${MAX_RECURSION_DEPTH} levels; choose one direct origin`,\n rewrite,\n );\n}\n", "import ts from \"typescript\";\nimport type { Environment, ProvenanceOrigin, VariableInfo } from \"../compiler\";\nimport { callName, isDbMember, propertyName, staticMemberPath, unwrapCall, unwrapExpression } from \"../syntax\";\nimport { expandHelper } from \"./helper-expansion\";\nimport { directOriginCandidates, isOperationCompositeBinding } from \"./operation-context\";\nimport { guardedWalk } from \"./recursion\";\n\ntype Presence = \"required\" | \"optional\";\ntype MemberSelection =\n | { kind: \"found\"; origins: ProvenanceOrigin[]; presence: Presence }\n | { kind: \"absent\" }\n | { kind: \"unknown\" };\n\nexport function collectionElementOrigins(node: ts.Expression, env: Environment): ProvenanceOrigin[] | undefined {\n return guardedWalk(env, node, \"collection elements\", () => collectionElementOriginsInner(node, env));\n}\n\nfunction collectionElementOriginsInner(node: ts.Expression, env: Environment): ProvenanceOrigin[] | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) {\n const substituted = env.substitutions.get(value.text);\n if (substituted) return collectionElementOrigins(substituted.expression, substituted.environment);\n const info = env.variables.get(value.text);\n if (info?.elementOrigins) return info.elementOrigins;\n if (info?.alternativeOrigins) return flattenCollectionOrigins(info.alternativeOrigins);\n if (info?.rowCollection) {\n return [{ binding: {\n provenance: \"Shape\",\n rowBinding: true,\n objectFields: info.objectFields,\n } }];\n }\n if (info?.max !== undefined) return [elementOrigin(info, info.operationArgument)];\n return undefined;\n }\n if (ts.isPropertyAccessExpression(value)) {\n const selected = selectExpressionMember(value.expression, env, value.name.text);\n return selected.kind === \"found\" ? flattenCollectionOrigins(selected.origins) : undefined;\n }\n if (ts.isArrayLiteralExpression(value)) {\n const origins: ProvenanceOrigin[] = [];\n const elementEnvironment = snapshotEnvironment(env);\n for (const element of value.elements) {\n if (ts.isSpreadElement(element)) {\n const spread = collectionElementOrigins(element.expression, env);\n if (!spread) return undefined;\n origins.push(...spread);\n } else {\n origins.push({ expression: element, environment: elementEnvironment });\n }\n }\n return origins;\n }\n if (ts.isConditionalExpression(value)) {\n const whenTrue = collectionElementOrigins(value.whenTrue, env);\n const whenFalse = collectionElementOrigins(value.whenFalse, env);\n return whenTrue && whenFalse ? [...whenTrue, ...whenFalse] : undefined;\n }\n const call = unwrapCall(value);\n const expanded = call && expandHelper(call, env);\n if (expanded) return collectionElementOrigins(expanded.expression, expanded.environment);\n if (call && callName(call).endsWith(\".scan\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n return [{ binding: {\n provenance: \"Shape\",\n rowBinding: true,\n objectFields: rowFields(call.arguments[0], env),\n } }];\n }\n if (call && ts.isIdentifier(call.expression) && call.expression.text === \"mergeByIndex\") {\n const rows = call.arguments[0];\n return rows ? collectionElementOrigins(rows, env) : undefined;\n }\n if (call && ts.isIdentifier(call.expression) && call.expression.text === \"mentionTokens\") {\n return [{ binding: { provenance: \"Computed\" } }];\n }\n if (call && ts.isPropertyAccessExpression(call.expression)) {\n const method = call.expression.name.text;\n const owner = call.expression.expression;\n if ([\"filter\", \"sort\", \"slice\"].includes(method)) return collectionElementOrigins(owner, env);\n if (method === \"map\" || method === \"flatMap\") {\n const callback = call.arguments[0];\n if (!callback || !ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)\n || callback.parameters.length === 0 || !ts.isIdentifier(callback.parameters[0]!.name)\n || ts.isBlock(callback.body)) return undefined;\n const callbackEnv = snapshotEnvironment(env);\n callbackEnv.variables.set(callback.parameters[0].name.text, collectionElementBinding(owner, env));\n return method === \"map\"\n ? [{ expression: callback.body, environment: snapshotEnvironment(callbackEnv) }]\n : collectionElementOrigins(callback.body, callbackEnv);\n }\n }\n return undefined;\n}\n\nfunction collectionElementBinding(node: ts.Expression, env: Environment): VariableInfo {\n const origins = collectionElementOrigins(node, env);\n return origins && origins.length > 0\n ? { provenance: \"Computed\", alternativeOrigins: origins }\n : { provenance: \"Computed\", provenanceAmbiguity: {} };\n}\n\nfunction flattenCollectionOrigins(origins: readonly ProvenanceOrigin[]): ProvenanceOrigin[] | undefined {\n const elements: ProvenanceOrigin[] = [];\n for (const origin of origins) {\n if (\"binding\" in origin) {\n const nested = origin.binding.elementOrigins\n ?? (origin.binding.alternativeOrigins ? flattenCollectionOrigins(origin.binding.alternativeOrigins) : undefined);\n if (nested) elements.push(...nested);\n else if (origin.binding.max !== undefined || origin.binding.operationArgument || origin.binding.rowCollection) {\n elements.push(elementOrigin(origin.binding, origin.candidate));\n } else return undefined;\n continue;\n }\n const nested = collectionElementOrigins(origin.expression, origin.environment);\n if (!nested) return undefined;\n elements.push(...nested);\n }\n return elements;\n}\n\nexport function selectOriginMembers(origin: ProvenanceOrigin, member: string): MemberSelection {\n if (\"binding\" in origin) {\n return origin.binding.immutableOrigin\n ? selectOriginMembers(origin.binding.immutableOrigin, member)\n : { kind: \"unknown\" };\n }\n return selectExpressionMember(origin.expression, origin.environment, member);\n}\n\nexport function selectExpressionMember(\n node: ts.Expression,\n env: Environment,\n member: string,\n): MemberSelection {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) {\n const substituted = env.substitutions.get(value.text);\n if (substituted) return selectExpressionMember(substituted.expression, substituted.environment, member);\n const info = env.variables.get(value.text);\n if (info?.operationComposite === \"args\") {\n const descriptor = env.args[member];\n if (!descriptor) return { kind: \"absent\" };\n const unwrapped = typeof descriptor !== \"string\" && \"Optional\" in descriptor ? descriptor.Optional : descriptor;\n const max = typeof unwrapped !== \"string\" && \"List\" in unwrapped ? unwrapped.List.max : undefined;\n return {\n kind: \"found\",\n origins: [{ binding: {\n provenance: \"Arg\",\n operationArgument: member,\n ...(max !== undefined ? { max, boundSource: `arg ${member} max` } : {}),\n }, candidate: `${value.text}.${member}` }],\n presence: typeof descriptor !== \"string\" && \"Optional\" in descriptor ? \"optional\" : \"required\",\n };\n }\n if (info?.operationComposite === \"ctx\") {\n return member === \"viewer\"\n ? { kind: \"found\", origins: [{ binding: { provenance: \"Viewer\" } }], presence: \"required\" }\n : { kind: \"absent\" };\n }\n if (info?.provenanceAmbiguity) return { kind: \"unknown\" };\n if (info?.alternativeOrigins) {\n const selected = info.alternativeOrigins.map((origin) => selectOriginMembers(origin, member));\n if (selected.some((item) => item.kind !== \"found\")) return { kind: \"unknown\" };\n return {\n kind: \"found\",\n origins: selected.flatMap((item) => item.kind === \"found\" ? item.origins : []),\n presence: selected.some((item) => item.kind === \"found\" && item.presence === \"optional\")\n ? \"optional\"\n : \"required\",\n };\n }\n return info?.immutableOrigin\n ? selectOriginMembers(info.immutableOrigin, member)\n : { kind: \"unknown\" };\n }\n if (ts.isConditionalExpression(value)) {\n return mergeMemberAlternatives([\n selectExpressionMember(value.whenTrue, env, member),\n selectExpressionMember(value.whenFalse, env, member),\n ]);\n }\n if (!ts.isObjectLiteralExpression(value)) return { kind: \"unknown\" };\n const laterOptional: ProvenanceOrigin[] = [];\n for (const property of [...value.properties].reverse()) {\n let selected: MemberSelection | undefined;\n if (ts.isSpreadAssignment(property)) {\n selected = selectExpressionMember(property.expression, env, member);\n } else if (ts.isShorthandPropertyAssignment(property) && property.name.text === member) {\n selected = {\n kind: \"found\",\n origins: [{ expression: property.name, environment: snapshotEnvironment(env) }],\n presence: \"required\",\n };\n } else if (ts.isPropertyAssignment(property) && propertyName(property.name) === member) {\n selected = {\n kind: \"found\",\n origins: [{ expression: property.initializer, environment: snapshotEnvironment(env) }],\n presence: \"required\",\n };\n }\n if (!selected || selected.kind === \"absent\") continue;\n if (selected.kind === \"unknown\") return selected;\n if (selected.presence === \"optional\") {\n laterOptional.push(...selected.origins);\n continue;\n }\n return { kind: \"found\", origins: [...laterOptional, ...selected.origins], presence: \"required\" };\n }\n return laterOptional.length > 0\n ? { kind: \"found\", origins: laterOptional, presence: \"optional\" }\n : { kind: \"absent\" };\n}\n\nexport function originDirectCandidates(origins: readonly ProvenanceOrigin[]): string[] {\n const candidates = new Set<string>();\n for (const origin of origins) {\n if (\"expression\" in origin) {\n for (const candidate of directOriginCandidates(origin.expression, origin.environment)) candidates.add(candidate);\n continue;\n }\n if (origin.candidate) candidates.add(origin.candidate);\n for (const candidate of origin.binding.provenanceAmbiguity?.candidates ?? []) candidates.add(candidate);\n if (origin.binding.provenanceAmbiguity?.directRewrite) {\n candidates.add(origin.binding.provenanceAmbiguity.directRewrite);\n }\n if (origin.binding.immutableOrigin) {\n for (const candidate of directOriginCandidates(\n origin.binding.immutableOrigin.expression,\n origin.binding.immutableOrigin.environment,\n )) candidates.add(candidate);\n }\n if (origin.binding.alternativeOrigins) {\n for (const candidate of originDirectCandidates(origin.binding.alternativeOrigins)) candidates.add(candidate);\n }\n }\n return [...candidates];\n}\n\nfunction mergeMemberAlternatives(alternatives: readonly MemberSelection[]): MemberSelection {\n if (alternatives.some((item) => item.kind === \"unknown\")) return { kind: \"unknown\" };\n if (alternatives.every((item) => item.kind === \"absent\")) return { kind: \"absent\" };\n if (alternatives.some((item) => item.kind === \"absent\")) return { kind: \"unknown\" };\n const found = alternatives as Extract<MemberSelection, { kind: \"found\" }>[];\n return {\n kind: \"found\",\n origins: found.flatMap((item) => item.origins),\n presence: found.some((item) => item.presence === \"optional\") ? \"optional\" : \"required\",\n };\n}\n\nexport function snapshotEnvironment(env: Environment): Environment {\n return {\n ...env,\n variables: new Map([...env.variables].map(([name, info]) => [name, { ...info }])),\n substitutions: new Map(env.substitutions),\n helperStack: [...env.helperStack],\n deferredCollectionMutations: new Set(env.deferredCollectionMutations),\n };\n}\n\nfunction elementOrigin(info: VariableInfo, candidate?: string): ProvenanceOrigin {\n const {\n max: _max,\n boundSource: _boundSource,\n elementOrigins: _elementOrigins,\n alternativeOrigins: _alternativeOrigins,\n ...binding\n } = info;\n return { binding, ...(candidate ? { candidate } : {}) };\n}\n\nfunction rowFields(target: ts.Expression | undefined, env: Environment): string[] | undefined {\n if (!target) return undefined;\n const binding = staticMemberPath(target)?.split(\".\")[0];\n const columns = binding && env.tables.get(binding)?.columns;\n return columns ? [...new Set([\"id\", ...Object.keys(columns)])] : undefined;\n}\n", "import ts from \"typescript\";\nimport type { Environment, FunctionLike, Substitution } from \"../compiler\";\nimport { refuse } from \"../diagnostics\";\nimport { expansionContext, unwrapCall, unwrapExpression } from \"../syntax\";\nimport { refuseRecursiveWalk } from \"./recursion\";\n\nexport function expandHelper(\n node: ts.Expression,\n env: Environment,\n): { expression: ts.Expression; environment: Environment } | undefined {\n const call = unwrapCall(node);\n if (!call || !ts.isIdentifier(call.expression)) return undefined;\n const helper = env.helpers.get(call.expression.text);\n if (!helper) return undefined;\n if (env.helperStack.includes(call.expression.text)) {\n refuse(env, \"E_OPAQUE\", call, \"recursive helper is not inlineable\");\n }\n const body = helperBodyExpression(helper);\n if (!body) refuse(env, \"E_OPAQUE\", helper, \"helper must be a single pure return expression\");\n const next: Environment = {\n ...env,\n variables: new Map([...env.variables].map(([name, info]) => [name, { ...info }])),\n substitutions: new Map(env.substitutions),\n helperStack: [...env.helperStack, call.expression.text],\n deferredCollectionMutations: new Set(env.deferredCollectionMutations),\n literalContext: expansionContext(env.literalContext, call, env.sourceFile),\n };\n helper.parameters.forEach((parameter, index) => {\n if (!ts.isIdentifier(parameter.name) || !call.arguments[index]) {\n refuse(env, \"E_OPAQUE\", parameter, \"helper parameters must be positional identifiers\");\n }\n const argument = resolveSubstitution(call.arguments[index]!, env);\n next.substitutions.delete(parameter.name.text);\n if (!ts.isIdentifier(argument.expression) || argument.expression.text !== parameter.name.text\n || argument.environment !== env) {\n next.substitutions.set(parameter.name.text, argument);\n }\n });\n return { expression: body, environment: next };\n}\n\nfunction resolveSubstitution(node: ts.Expression, env: Environment): Substitution {\n let value = node;\n let environment = env;\n const seen = new Set<string>();\n for (;;) {\n const unwrapped = unwrapExpression(value);\n if (!ts.isIdentifier(unwrapped)) return { expression: value, environment };\n const substitution = environment.substitutions.get(unwrapped.text);\n if (!substitution) return { expression: value, environment };\n if (seen.has(unwrapped.text) || seen.size >= 128) return refuseRecursiveWalk(env, node);\n seen.add(unwrapped.text);\n value = substitution.expression;\n environment = substitution.environment;\n }\n}\n\nfunction helperBodyExpression(helper: FunctionLike): ts.Expression | undefined {\n if (!helper.body) return undefined;\n if (!ts.isBlock(helper.body)) return helper.body;\n if (helper.body.statements.length !== 1 || !ts.isReturnStatement(helper.body.statements[0])) return undefined;\n return helper.body.statements[0].expression;\n}\n", "import ts from \"typescript\";\nimport type { CollectionEscapeSite, Environment, ProvenanceOrigin, VariableInfo } from \"../compiler\";\nimport { refuse } from \"../diagnostics\";\nimport { collectionConstructor, propertyName, replaceNode, unwrapExpression } from \"../syntax\";\nimport { guardedWalk } from \"./recursion\";\n\ntype FunctionLike = ts.FunctionDeclaration | ts.ArrowFunction | ts.FunctionExpression;\ntype BindingScope = { parent?: BindingScope; bindings: Map<string, ts.Identifier> };\n\nexport const UNKNOWN_DIRECT_ORIGIN = \"<unknown origin>\";\n\nexport function assignedBindings(handler: FunctionLike): Set<ts.Identifier> {\n const assigned = new Set<ts.Identifier>();\n const functionScope: BindingScope = { bindings: new Map() };\n for (const parameter of handler.parameters) declareBinding(parameter.name, functionScope);\n if (handler.body) visitBindingMutations(handler.body, functionScope, assigned);\n return assigned;\n}\n\nexport function collectionSharingSites(handler: FunctionLike): {\n aliases: Map<ts.Identifier, ts.Expression[]>;\n escapes: Map<ts.Identifier, CollectionEscapeSite[]>;\n} {\n const edges: Array<{ left: ts.Identifier; right: ts.Identifier; site: ts.Expression }> = [];\n const directEscapes = new Map<ts.Identifier, CollectionEscapeSite[]>();\n const functionScope: BindingScope = { bindings: new Map() };\n for (const parameter of handler.parameters) declareBinding(parameter.name, functionScope);\n if (handler.body) visitCollectionSharing(handler.body, functionScope, edges, directEscapes);\n\n const graph = new Map<ts.Identifier, Array<{ other: ts.Identifier; site: ts.Expression }>>();\n for (const edge of edges) {\n addAliasEdge(graph, edge.left, edge.right, edge.site);\n addAliasEdge(graph, edge.right, edge.left, edge.site);\n }\n const aliases = new Map<ts.Identifier, ts.Expression[]>();\n const escapes = new Map<ts.Identifier, CollectionEscapeSite[]>();\n const bindings = new Set([...graph.keys(), ...directEscapes.keys()]);\n for (const binding of bindings) {\n const pending = [binding];\n const seen = new Set<ts.Identifier>();\n const aliasSites = new Set<ts.Expression>();\n const escapeSites = new Map<number, CollectionEscapeSite>();\n while (pending.length > 0) {\n const current = pending.pop()!;\n if (seen.has(current)) continue;\n seen.add(current);\n for (const site of directEscapes.get(current) ?? []) {\n escapeSites.set(site.expression.getStart(), site);\n }\n for (const edge of graph.get(current) ?? []) {\n aliasSites.add(edge.site);\n pending.push(edge.other);\n }\n }\n if (aliasSites.size > 0) aliases.set(binding, [...aliasSites]);\n if (escapeSites.size > 0) escapes.set(binding, [...escapeSites.values()]);\n }\n return { aliases, escapes };\n}\n\nexport function isLocallyCreatedCollection(node: ts.Expression): boolean {\n const value = unwrapExpression(node);\n if (ts.isArrayLiteralExpression(value)) return true;\n if (!ts.isNewExpression(value) || !collectionConstructor(value)) return false;\n const initializer = value.arguments?.[0];\n return initializer === undefined || ts.isArrayLiteralExpression(unwrapExpression(initializer));\n}\n\nexport function collectionMutationRewrite(\n info: VariableInfo,\n mutation: ts.CallExpression,\n owner: ts.Identifier,\n env: Environment,\n): string {\n const aliasSites = info.collectionDeclaration\n ? env.collectionAliasSites.get(info.collectionDeclaration) ?? []\n : [];\n const escapeSites = conflictingCollectionEscapeSites(info, mutation, env);\n const sharingSites = [\n ...aliasSites.map(copySite),\n ...escapeSites,\n ];\n if (sharingSites.length > 0) return spreadCopyRewrite(env, sharingSites);\n const declaration = info.collectionDeclaration?.parent;\n if (declaration && ts.isVariableDeclaration(declaration) && declaration.initializer) {\n return spreadCopyRewrite(env, [copySite(declaration.initializer)]);\n }\n const copy = `${owner.text}Copy`;\n const method = ts.isPropertyAccessExpression(mutation.expression)\n ? mutation.expression.name.getText(env.sourceFile)\n : \"push\";\n return replaceNode(\n env.source,\n mutation,\n `const ${copy} = [...${owner.text}]; ${copy}.${method}(${mutation.arguments.map((argument) => argument.getText(env.sourceFile)).join(\", \")})`,\n );\n}\n\nexport function requireCollectionMutation(\n owner: ts.Identifier,\n mutation: ts.CallExpression,\n env: Environment,\n): void {\n // @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 mutable collections have one local owner; mutations after an escape or cyclic with one in a loop body refuse so IR copy semantics cannot diverge from TypeScript aliases.\n const info = env.variables.get(owner.text)!;\n const aliases = info.collectionDeclaration\n ? env.collectionAliasSites.get(info.collectionDeclaration) ?? []\n : [];\n const escapes = conflictingCollectionEscapeSites(info, mutation, env);\n if (info.locallyCreatedCollection && aliases.length === 0 && escapes.length === 0) return;\n const reason = aliases.length > 0\n ? \"aliased under another binding\"\n : escapes.length > 0\n ? escapes.some((site) => site.expression.getStart(env.sourceFile) < mutation.getStart(env.sourceFile))\n ? \"shared by an escape before this mutation\"\n : \"shared by an escape in the same cyclic loop body\"\n : \"not locally created\";\n refuse(\n env,\n \"E_OPAQUE\",\n mutation,\n `collection mutation requires an unaliased local collection created from a literal or spread copy; ${owner.text} is ${reason}`,\n collectionMutationRewrite(info, mutation, owner, env),\n );\n}\n\nexport function operationCompositeBindings(\n handler: FunctionLike,\n): { args?: string; ctx?: string; db?: string } {\n const parameter = handler.parameters[0];\n if (!parameter || !ts.isObjectBindingPattern(parameter.name)) return {};\n const bindings: { args?: string; ctx?: string; db?: string } = {};\n for (const element of parameter.name.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const property = element.propertyName ? propertyName(element.propertyName) : element.name.text;\n if (property === \"args\" || property === \"ctx\" || property === \"db\") bindings[property] = element.name.text;\n }\n return bindings;\n}\n\nexport function isOperationCompositeBinding(\n name: string,\n composite: \"args\" | \"ctx\" | \"db\",\n env: Environment,\n): boolean {\n return resolvesOperationComposite(name, composite, env, new Set());\n}\n\nfunction resolvesOperationComposite(\n name: string,\n composite: \"args\" | \"ctx\" | \"db\",\n env: Environment,\n seen: Set<string>,\n): boolean {\n if (env.variables.get(name)?.operationComposite === composite) return true;\n const substitution = env.substitutions.get(name);\n if (!substitution || seen.has(name)) return false;\n const value = unwrapExpression(substitution.expression);\n if (!ts.isIdentifier(value)) return false;\n seen.add(name);\n return resolvesOperationComposite(value.text, composite, substitution.environment, seen);\n}\n\nfunction visitBindingMutations(node: ts.Node, scope: BindingScope, assigned: Set<ts.Identifier>): void {\n if (ts.isBlock(node)) {\n const block: BindingScope = { parent: scope, bindings: new Map() };\n for (const statement of node.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) declareBinding(declaration.name, block);\n }\n for (const statement of node.statements) visitBindingMutations(statement, block, assigned);\n return;\n }\n if (ts.isForOfStatement(node)) {\n visitBindingMutations(node.expression, scope, assigned);\n const loop: BindingScope = { parent: scope, bindings: new Map() };\n if (ts.isVariableDeclarationList(node.initializer)) {\n for (const declaration of node.initializer.declarations) declareBinding(declaration.name, loop);\n } else {\n visitBindingMutations(node.initializer, scope, assigned);\n }\n visitBindingMutations(node.statement, loop, assigned);\n return;\n }\n if (ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {\n const nested: BindingScope = { parent: scope, bindings: new Map() };\n for (const parameter of node.parameters) declareBinding(parameter.name, nested);\n if (node.body) visitBindingMutations(node.body, nested, assigned);\n return;\n }\n if (ts.isVariableDeclaration(node)) {\n if (node.initializer) visitBindingMutations(node.initializer, scope, assigned);\n return;\n }\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken\n && ts.isIdentifier(node.left)) {\n const binding = resolveBinding(node.left.text, scope);\n if (binding) assigned.add(binding);\n visitBindingMutations(node.right, scope, assigned);\n return;\n }\n if ((ts.isPostfixUnaryExpression(node) || ts.isPrefixUnaryExpression(node))\n && (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)\n && ts.isIdentifier(node.operand)) {\n const binding = resolveBinding(node.operand.text, scope);\n if (binding) assigned.add(binding);\n return;\n }\n ts.forEachChild(node, (child) => visitBindingMutations(child, scope, assigned));\n}\n\nfunction visitCollectionSharing(\n node: ts.Node,\n scope: BindingScope,\n edges: Array<{ left: ts.Identifier; right: ts.Identifier; site: ts.Expression }>,\n escapes: Map<ts.Identifier, CollectionEscapeSite[]>,\n): void {\n if (ts.isBlock(node)) {\n const block: BindingScope = { parent: scope, bindings: new Map() };\n for (const statement of node.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) declareBinding(declaration.name, block);\n }\n for (const statement of node.statements) visitCollectionSharing(statement, block, edges, escapes);\n return;\n }\n if (ts.isForOfStatement(node)) {\n visitCollectionSharing(node.expression, scope, edges, escapes);\n const loop: BindingScope = { parent: scope, bindings: new Map() };\n if (ts.isVariableDeclarationList(node.initializer)) {\n for (const declaration of node.initializer.declarations) declareBinding(declaration.name, loop);\n }\n visitCollectionSharing(node.statement, loop, edges, escapes);\n return;\n }\n if (ts.isFunctionLike(node)) return;\n if (ts.isVariableDeclaration(node)) {\n if (ts.isIdentifier(node.name) && node.initializer) {\n const source = unwrapExpression(node.initializer);\n const target = resolveBinding(node.name.text, scope);\n const origin = ts.isIdentifier(source) ? resolveBinding(source.text, scope) : undefined;\n if (target && origin && target !== origin) edges.push({ left: target, right: origin, site: node.initializer });\n visitCollectionSharing(node.initializer, scope, edges, escapes);\n }\n return;\n }\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken\n && ts.isIdentifier(node.left)) {\n const right = unwrapExpression(node.right);\n const target = resolveBinding(node.left.text, scope);\n const origin = ts.isIdentifier(right) ? resolveBinding(right.text, scope) : undefined;\n if (target && origin && target !== origin) edges.push({ left: target, right: origin, site: node.right });\n visitCollectionSharing(node.right, scope, edges, escapes);\n return;\n }\n recordEscapeContexts(node, scope, escapes);\n ts.forEachChild(node, (child) => visitCollectionSharing(child, scope, edges, escapes));\n}\n\nfunction addAliasEdge(\n graph: Map<ts.Identifier, Array<{ other: ts.Identifier; site: ts.Expression }>>,\n binding: ts.Identifier,\n other: ts.Identifier,\n site: ts.Expression,\n): void {\n const adjacent = graph.get(binding) ?? [];\n adjacent.push({ other, site });\n graph.set(binding, adjacent);\n}\n\nfunction spreadCopyRewrite(env: Environment, sites: readonly CollectionEscapeSite[]): string {\n const unique = new Map(sites.map((site) => [site.expression.getStart(env.sourceFile), site]));\n const edits = [...unique.values()].map((site) => ({\n start: site.expression.getStart(env.sourceFile),\n end: site.expression.getEnd(),\n text: site.replacement,\n })).sort((left, right) => right.start - left.start);\n let rewritten = env.source;\n for (const edit of edits) rewritten = rewritten.slice(0, edit.start) + edit.text + rewritten.slice(edit.end);\n return rewritten;\n}\n\nfunction conflictingCollectionEscapeSites(\n info: VariableInfo,\n mutation: ts.CallExpression,\n env: Environment,\n): CollectionEscapeSite[] {\n const declaration = info.collectionDeclaration;\n if (!declaration) return [];\n const mutationStart = mutation.getStart(env.sourceFile);\n return (env.collectionEscapeSites.get(declaration) ?? [])\n .filter((site) => site.expression.getStart(env.sourceFile) < mutationStart\n || sharesEnclosingLoopBody(site.expression, mutation, declaration));\n}\n\nfunction sharesEnclosingLoopBody(left: ts.Node, right: ts.Node, declaration: ts.Node): boolean {\n const leftBodies = new Set(enclosingLoopBodies(left));\n return enclosingLoopBodies(right).some((body) => leftBodies.has(body) && !isWithin(declaration, body));\n}\n\nfunction enclosingLoopBodies(node: ts.Node): ts.Statement[] {\n const bodies: ts.Statement[] = [];\n for (let current: ts.Node | undefined = node; current?.parent; current = current.parent) {\n if (ts.isForOfStatement(current.parent) && current.parent.statement === current) {\n bodies.push(current as ts.Statement);\n }\n }\n return bodies;\n}\n\nfunction isWithin(node: ts.Node, ancestor: ts.Node): boolean {\n for (let current: ts.Node | undefined = node; current; current = current.parent) {\n if (current === ancestor) return true;\n }\n return false;\n}\n\nfunction copySite(expression: ts.Expression): CollectionEscapeSite {\n return { expression, replacement: `[...${expression.getText()}]` };\n}\n\nfunction recordEscapeContexts(\n node: ts.Node,\n scope: BindingScope,\n escapes: Map<ts.Identifier, CollectionEscapeSite[]>,\n): void {\n if (ts.isReturnStatement(node) && node.expression) recordEscapedExpression(node.expression, scope, escapes);\n if (ts.isCallExpression(node)) {\n for (const argument of node.arguments) {\n if (!ts.isSpreadElement(argument)) recordEscapedExpression(argument, scope, escapes);\n }\n }\n if (ts.isArrayLiteralExpression(node)) {\n for (const element of node.elements) {\n if (!ts.isSpreadElement(element)) recordEscapedExpression(element, scope, escapes);\n }\n }\n if (ts.isObjectLiteralExpression(node)) {\n for (const property of node.properties) {\n if (ts.isShorthandPropertyAssignment(property)) {\n recordEscapedIdentifier(property.name, scope, escapes, `${property.name.text}: [...${property.name.text}]`);\n } else if (ts.isPropertyAssignment(property)) {\n recordEscapedExpression(property.initializer, scope, escapes);\n }\n }\n }\n if (ts.isConditionalExpression(node)) {\n recordEscapedExpression(node.whenTrue, scope, escapes);\n recordEscapedExpression(node.whenFalse, scope, escapes);\n }\n if (ts.isBinaryExpression(node) && [\n ts.SyntaxKind.AmpersandAmpersandToken,\n ts.SyntaxKind.BarBarToken,\n ts.SyntaxKind.QuestionQuestionToken,\n ].includes(node.operatorToken.kind)) {\n recordEscapedExpression(node.left, scope, escapes);\n recordEscapedExpression(node.right, scope, escapes);\n }\n}\n\nfunction recordEscapedExpression(\n node: ts.Expression,\n scope: BindingScope,\n escapes: Map<ts.Identifier, CollectionEscapeSite[]>,\n): void {\n if (ts.isFunctionLike(node) || ts.isSpreadElement(node)) return;\n if (ts.isIdentifier(node)) {\n recordEscapedIdentifier(node, scope, escapes);\n return;\n }\n if (ts.isCallExpression(node)) {\n for (const argument of node.arguments) {\n if (!ts.isSpreadElement(argument)) recordEscapedExpression(argument, scope, escapes);\n }\n return;\n }\n if (ts.isPropertyAccessExpression(node)) {\n recordEscapedExpression(node.expression, scope, escapes);\n return;\n }\n node.forEachChild((child) => {\n if (ts.isExpression(child)) recordEscapedExpression(child, scope, escapes);\n });\n}\n\nfunction recordEscapedIdentifier(\n node: ts.Identifier,\n scope: BindingScope,\n escapes: Map<ts.Identifier, CollectionEscapeSite[]>,\n replacement = `[...${node.text}]`,\n): void {\n const binding = resolveBinding(node.text, scope);\n if (!binding) return;\n const sites = escapes.get(binding) ?? [];\n if (!sites.some((site) => site.expression === node)) sites.push({ expression: node, replacement });\n escapes.set(binding, sites);\n}\n\nfunction declareBinding(name: ts.BindingName, scope: BindingScope): void {\n if (ts.isIdentifier(name)) {\n scope.bindings.set(name.text, name);\n return;\n }\n for (const element of name.elements) {\n if (ts.isBindingElement(element)) declareBinding(element.name, scope);\n }\n}\n\nfunction resolveBinding(name: string, scope: BindingScope | undefined): ts.Identifier | undefined {\n for (let current = scope; current; current = current.parent) {\n const binding = current.bindings.get(name);\n if (binding) return binding;\n }\n return undefined;\n}\n\nexport function directOriginCandidates(node: ts.Expression, env: Environment): Set<string> {\n return guardedWalk(env, node, \"direct origin\", () => directOriginCandidatesInner(node, env));\n}\n\nfunction directOriginCandidatesInner(node: ts.Expression, env: Environment): Set<string> {\n const value = unwrapExpression(node);\n if (ts.isPropertyAccessExpression(value) && ts.isIdentifier(value.expression)) {\n const info = env.variables.get(value.expression.text);\n const composite = info?.operationComposite;\n if (composite === \"args\" || composite === \"ctx\" && value.name.text === \"viewer\") {\n return new Set([value.getText(env.sourceFile)]);\n }\n if (info?.rowBinding) return new Set([value.getText(env.sourceFile)]);\n }\n if (ts.isIdentifier(value)) {\n const info = env.variables.get(value.text);\n if (info?.operationComposite === \"args\") return new Set([value.text]);\n if (info?.operationComposite === \"ctx\") return new Set([`${value.text}.viewer`]);\n if (info?.operationArgument) {\n const args = [...env.variables].find(([, candidate]) => candidate.operationComposite === \"args\")?.[0];\n return new Set([args ? `${args}.${info.operationArgument}` : info.operationArgument]);\n }\n if (info?.provenanceAmbiguity) {\n return new Set([\n ...(info.provenanceAmbiguity.candidates ?? []),\n ...(info.provenanceAmbiguity.directRewrite ? [info.provenanceAmbiguity.directRewrite] : []),\n ]);\n }\n if (info?.alternativeOrigins) return directCandidatesForOrigins(info.alternativeOrigins, new Set());\n return info?.immutableOrigin\n ? directOriginCandidates(info.immutableOrigin.expression, info.immutableOrigin.environment)\n : new Set();\n }\n // Property names are labels, never value operands. Walking `value.key` through\n // forEachChild would otherwise discover an unrelated operation argument named\n // `key` and rewrite the helper declaration instead of the authored read key.\n if (ts.isPropertyAccessExpression(value)) return directOriginCandidates(value.expression, env);\n if (ts.isObjectLiteralExpression(value)) {\n const candidates = new Set<string>();\n for (const property of value.properties) {\n const expression = ts.isSpreadAssignment(property)\n ? property.expression\n : ts.isPropertyAssignment(property)\n ? property.initializer\n : ts.isShorthandPropertyAssignment(property)\n ? property.name\n : undefined;\n if (!expression) continue;\n for (const direct of directOriginCandidates(expression, env)) candidates.add(direct);\n }\n return candidates;\n }\n if (ts.isCallExpression(value)) {\n const candidates = new Set<string>();\n for (const argument of value.arguments) {\n for (const direct of directOriginCandidates(argument, env)) candidates.add(direct);\n }\n return candidates;\n }\n if (ts.isConditionalExpression(value)) {\n return new Set([\n ...directOriginCandidates(value.whenTrue, env),\n ...directOriginCandidates(value.whenFalse, env),\n ]);\n }\n const candidates = new Set<string>();\n value.forEachChild((child) => {\n if (!ts.isExpression(child)) return;\n for (const direct of directOriginCandidates(child, env)) candidates.add(direct);\n });\n return candidates;\n}\n\nexport function withDirectRewrite(\n binding: Pick<VariableInfo, \"provenance\" | \"provenanceAmbiguity\">,\n node: ts.Expression,\n env: Environment,\n): Pick<VariableInfo, \"provenance\" | \"provenanceAmbiguity\"> {\n if (!binding.provenanceAmbiguity) return binding;\n const candidates = new Set([\n ...(binding.provenanceAmbiguity.candidates ?? []),\n ...(binding.provenanceAmbiguity.directRewrite ? [binding.provenanceAmbiguity.directRewrite] : []),\n ...directOriginCandidates(node, env),\n ]);\n return { ...binding, provenanceAmbiguity: candidateAmbiguity([...candidates]) };\n}\n\nexport function recordAssignmentOrigin(info: VariableInfo | undefined, node: ts.Expression, env: Environment): void {\n if (!info) return;\n const discovered = [...directOriginCandidates(node, env)];\n const candidates = new Set([\n ...(info.provenanceAmbiguity?.candidates ?? []),\n ...(info.provenanceAmbiguity?.directRewrite ? [info.provenanceAmbiguity.directRewrite] : []),\n ...(info.immutableOrigin ? directOriginCandidates(\n info.immutableOrigin.expression,\n info.immutableOrigin.environment,\n ) : []),\n ...(discovered.length > 0 ? discovered : [UNKNOWN_DIRECT_ORIGIN]),\n ]);\n info.provenanceAmbiguity = candidateAmbiguity([...candidates]);\n}\n\nexport function candidateAmbiguity(candidates: string[]): NonNullable<VariableInfo[\"provenanceAmbiguity\"]> {\n const distinct = [...new Set(candidates)];\n return {\n ...(distinct.length === 1 && distinct[0] !== UNKNOWN_DIRECT_ORIGIN ? { directRewrite: distinct[0] } : {}),\n ...(distinct.length > 0 ? { candidates: distinct } : {}),\n };\n}\n\nfunction directCandidatesForOrigins(origins: readonly ProvenanceOrigin[], seen: Set<VariableInfo>): Set<string> {\n const candidates = new Set<string>();\n for (const origin of origins) {\n if (\"expression\" in origin) {\n for (const candidate of directOriginCandidates(origin.expression, origin.environment)) candidates.add(candidate);\n continue;\n }\n if (origin.candidate) candidates.add(origin.candidate);\n const info = origin.binding;\n if (seen.has(info)) continue;\n seen.add(info);\n for (const candidate of info.provenanceAmbiguity?.candidates ?? []) candidates.add(candidate);\n if (info.provenanceAmbiguity?.directRewrite) candidates.add(info.provenanceAmbiguity.directRewrite);\n if (info.alternativeOrigins) {\n for (const candidate of directCandidatesForOrigins(info.alternativeOrigins, seen)) candidates.add(candidate);\n }\n if (info.immutableOrigin) {\n for (const candidate of directOriginCandidates(\n info.immutableOrigin.expression,\n info.immutableOrigin.environment,\n )) candidates.add(candidate);\n }\n }\n return candidates;\n}\n\nexport function moduleBasename(fileName: string): string {\n return fileName.split(/[\\\\/]/).at(-1)!.replace(/\\.[^.]+$/, \"\");\n}\n", "import ts from \"typescript\";\nimport type { Environment } from \"../compiler\";\nimport { refuse } from \"../diagnostics\";\nimport {\n callName,\n isDbMember,\n isFunctionLike,\n propertyName,\n replaceNode,\n unwrapCall,\n unwrapExpression,\n} from \"../syntax\";\nimport { expandHelper } from \"./helper-expansion\";\nimport { isOperationCompositeBinding } from \"./operation-context\";\nimport { isRowCollectionExpression } from \"./provenance\";\nimport { guardedWalk } from \"./recursion\";\n\nexport function knownObjectFields(node: ts.Expression, env: Environment): string[] | undefined {\n return guardedWalk(env, node, \"object fields\", () => knownObjectFieldsInner(node, env));\n}\n\nfunction knownObjectFieldsInner(node: ts.Expression, env: Environment): string[] | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) {\n const substituted = env.substitutions.get(value.text);\n if (substituted) return knownObjectFields(substituted.expression, substituted.environment);\n const info = env.variables.get(value.text);\n if (info?.operationComposite === \"args\") return Object.keys(env.args);\n if (info?.operationComposite === \"ctx\") return [\"viewer\"];\n return info?.objectFields ?? (info?.immutableOrigin\n ? knownObjectFields(info.immutableOrigin.expression, info.immutableOrigin.environment)\n : undefined);\n }\n if (ts.isPropertyAccessExpression(value)) {\n const selected = selectedObjectMember(value.expression, value.name.text, env);\n return selected && knownObjectFields(selected.expression, selected.environment);\n }\n if (ts.isObjectLiteralExpression(value)) {\n const fields: string[] = [];\n for (const property of value.properties) {\n if (ts.isSpreadAssignment(property)) {\n const spread = knownObjectFields(property.expression, env);\n if (!spread) return undefined;\n for (const field of spread) if (!fields.includes(field)) fields.push(field);\n continue;\n }\n if (ts.isShorthandPropertyAssignment(property)) {\n if (!fields.includes(property.name.text)) fields.push(property.name.text);\n continue;\n }\n if (!ts.isPropertyAssignment(property)) return undefined;\n const name = propertyName(property.name);\n if (!name) return undefined;\n if (!fields.includes(name)) fields.push(name);\n }\n return fields;\n }\n const call = unwrapCall(value);\n const expanded = call && expandHelper(call, env);\n if (expanded) return knownObjectFields(expanded.expression, expanded.environment);\n if (call && callName(call).endsWith(\".get\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n return rowFields(call.arguments[0], env);\n }\n if (call && ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === \"require\") {\n return knownObjectFields(call.expression.expression, env);\n }\n return undefined;\n}\n\nfunction selectedObjectMember(\n node: ts.Expression,\n member: string,\n env: Environment,\n): { expression: ts.Expression; environment: Environment } | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) {\n const substituted = env.substitutions.get(value.text);\n if (substituted) return selectedObjectMember(substituted.expression, member, substituted.environment);\n const origin = env.variables.get(value.text)?.immutableOrigin;\n return origin && selectedObjectMember(origin.expression, member, origin.environment);\n }\n if (ts.isPropertyAccessExpression(value)) {\n const selected = selectedObjectMember(value.expression, value.name.text, env);\n return selected && selectedObjectMember(selected.expression, member, selected.environment);\n }\n if (ts.isObjectLiteralExpression(value)) {\n for (const property of [...value.properties].reverse()) {\n if (ts.isSpreadAssignment(property)) {\n const fields = knownObjectFields(property.expression, env);\n if (!fields) return undefined;\n if (fields.includes(member)) return selectedObjectMember(property.expression, member, env);\n continue;\n }\n if (ts.isShorthandPropertyAssignment(property) && property.name.text === member) {\n return { expression: property.name, environment: env };\n }\n if (ts.isPropertyAssignment(property) && propertyName(property.name) === member) {\n return { expression: property.initializer, environment: env };\n }\n }\n return undefined;\n }\n const call = unwrapCall(value);\n const expanded = call && expandHelper(call, env);\n return expanded && selectedObjectMember(expanded.expression, member, expanded.environment);\n}\n\nexport function rowCollectionFields(node: ts.Expression, env: Environment): string[] | undefined {\n return guardedWalk(env, node, \"row collection fields\", () => rowCollectionFieldsInner(node, env));\n}\n\nfunction rowCollectionFieldsInner(node: ts.Expression, env: Environment): string[] | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) {\n const substituted = env.substitutions.get(value.text);\n if (substituted) return rowCollectionFields(substituted.expression, substituted.environment);\n const info = env.variables.get(value.text);\n return info?.rowCollection ? info.objectFields : undefined;\n }\n const call = unwrapCall(value);\n if (!call) return undefined;\n const expanded = expandHelper(call, env);\n if (expanded) return rowCollectionFields(expanded.expression, expanded.environment);\n if (callName(call).endsWith(\".scan\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))) {\n return rowFields(call.arguments[0], env);\n }\n if (ts.isPropertyAccessExpression(call.expression) && [\"filter\", \"sort\", \"slice\"].includes(call.expression.name.text)) {\n return rowCollectionFields(call.expression.expression, env);\n }\n if (ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === \"map\") {\n const callback = call.arguments[0];\n if (callback && isFunctionLike(callback) && callback.parameters.length > 0 && !ts.isBlock(callback.body)\n && ts.isIdentifier(callback.parameters[0]!.name)) {\n const body = unwrapExpression(callback.body);\n if (ts.isIdentifier(body) && body.text === callback.parameters[0].name.text) {\n return rowCollectionFields(call.expression.expression, env);\n }\n }\n }\n if (ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === \"flatMap\"\n && isRowCollectionExpression(call, env)) {\n return rowCollectionFields(call.expression.expression, env);\n }\n return undefined;\n}\n\nexport function nullableReadSpread(node: ts.Expression, env: Environment): string | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value) && env.variables.get(value.text)?.nullableRead) return value.text;\n const call = unwrapCall(value);\n return call && callName(call).endsWith(\".get\")\n && isDbMember(call.expression, (binding) => isOperationCompositeBinding(binding, \"db\", env))\n ? call.getText(env.sourceFile)\n : undefined;\n}\n\nexport function nullableSpreadRefusal(node: ts.SpreadAssignment, env: Environment, value: string): never {\n const direct = value.includes(\".get(\");\n const rewrite = direct\n ? `const row = ${value};\\ndb.require(row !== null, \"ROW_REQUIRED\");\\n{ ...row }`\n : `db.require(${value} !== null, \"ROW_REQUIRED\");\\n{ ...${value} }`;\n refuse(env, \"E_OPAQUE\", node, `nullable db.get result ${value} cannot be spread before it is required`, rewrite);\n}\n\nexport function objectSpreadRewrite(env: Environment, spread: ts.SpreadAssignment): string {\n const value = spread.expression.getText(env.sourceFile);\n return replaceNode(env.source, spread, `field: ${value}.field`);\n}\n\nexport function arraySpreadRewrite(env: Environment, spread: ts.SpreadElement): string {\n const value = spread.expression.getText(env.sourceFile);\n return replaceNode(env.source, spread, `${value}[0], ${value}[1]`);\n}\n\nfunction rowFields(target: ts.Expression | undefined, env: Environment): string[] | undefined {\n if (!target) return undefined;\n const value = unwrapExpression(target);\n const binding = ts.isIdentifier(value)\n ? value.text\n : ts.isPropertyAccessExpression(value) && ts.isIdentifier(value.expression)\n ? value.expression.text\n : undefined;\n const columns = binding && env.tables.get(binding)?.columns;\n if (!columns) return undefined;\n return [...new Set([\"id\", ...Object.keys(columns)])];\n}\n", "import ts from \"typescript\";\nimport type { Environment, ProvenanceOrigin, VariableInfo } from \"../compiler\";\nimport {\n callName,\n collectionConstructor,\n expressionProperty,\n isFunctionLike,\n numericLiteral,\n unwrapCall,\n unwrapExpression,\n} from \"../syntax\";\nimport { selectExpressionMember } from \"./collection-origins\";\nimport { expandHelper } from \"./helper-expansion\";\nimport { guardedWalk } from \"./recursion\";\n\nexport function operationArgumentList(\n node: ts.Expression,\n env: Environment,\n): { name: string; max?: number } | undefined {\n const value = unwrapExpression(node);\n if (!ts.isPropertyAccessExpression(value)) return undefined;\n const base = unwrapExpression(value.expression);\n if (!ts.isIdentifier(base) || env.variables.get(base.text)?.operationComposite !== \"args\") return undefined;\n const argument = env.args[value.name.text];\n return {\n name: value.name.text,\n ...(argument && typeof argument !== \"string\" && \"List\" in argument ? { max: argument.List.max } : {}),\n };\n}\n\nexport function derivedBound(node: ts.Expression, env: Environment): Partial<VariableInfo> {\n const known = staticBound(node, env);\n return known === undefined ? {} : { max: known, boundSource: `${node.getText()} static bound` };\n}\n\nexport function staticBound(node: ts.Expression, env: Environment): number | undefined {\n return guardedWalk(env, node, \"static bound\", () => staticBoundInner(node, env));\n}\n\nfunction staticBoundInner(node: ts.Expression, env: Environment): number | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) {\n const substituted = env.substitutions.get(value.text);\n if (substituted) return staticBound(substituted.expression, substituted.environment);\n const info = env.variables.get(value.text);\n return info?.max ?? (info ? alternativeOriginBound(info, staticBound) : undefined);\n }\n const operationList = operationArgumentList(value, env);\n if (operationList) return operationList.max;\n if (ts.isPropertyAccessExpression(value)) {\n const selected = selectExpressionMember(value.expression, env, value.name.text);\n if (selected.kind === \"found\") {\n const bounds = selected.origins.map((origin) => originBound(origin, staticBound));\n if (bounds.every((bound): bound is number => bound !== undefined)) return Math.max(...bounds);\n }\n }\n if (ts.isArrayLiteralExpression(value)) {\n let total = 0;\n for (const element of value.elements) {\n if (ts.isSpreadElement(element)) {\n const bound = staticBound(element.expression, env);\n if (bound === undefined) return undefined;\n total += bound;\n } else total += 1;\n }\n return total;\n }\n if (ts.isConditionalExpression(value)) {\n const whenTrue = staticBound(value.whenTrue, env);\n const whenFalse = staticBound(value.whenFalse, env);\n return whenTrue === undefined || whenFalse === undefined ? undefined : Math.max(whenTrue, whenFalse);\n }\n if (ts.isNewExpression(value) && collectionConstructor(value)) {\n const initializer = value.arguments?.[0];\n return initializer ? staticBound(initializer, env) : 0;\n }\n const call = unwrapCall(node);\n const expanded = call && expandHelper(call, env);\n if (expanded) return staticBound(expanded.expression, expanded.environment);\n if (call && callName(call).endsWith(\".scan\")) {\n const take = scanTake(call);\n if (typeof take === \"number\") return take;\n }\n if (call && ts.isIdentifier(call.expression) && call.expression.text === \"mergeByIndex\") {\n return numericLiteral(call.arguments[3]);\n }\n if (call && ts.isIdentifier(call.expression) && call.expression.text === \"mentionTokens\") return 85;\n if (call && ts.isPropertyAccessExpression(call.expression)) {\n const method = call.expression.name.text;\n const owner = staticBound(call.expression.expression, env);\n if (method === \"map\" || method === \"filter\" || method === \"sort\") return owner;\n if (method === \"slice\") {\n const start = numericLiteral(call.arguments[0]) ?? 0;\n const end = numericLiteral(call.arguments[1]);\n return end === undefined ? owner : Math.max(0, end - start);\n }\n if (method === \"flatMap\" && owner !== undefined) {\n const callback = call.arguments[0];\n if (callback && isFunctionLike(callback) && !ts.isBlock(callback.body)) {\n const inner = staticBound(callback.body, env);\n if (inner !== undefined) return owner * inner;\n }\n }\n }\n return undefined;\n}\n\nfunction alternativeOriginBound(\n info: VariableInfo,\n bound: (node: ts.Expression, env: Environment) => number | undefined,\n): number | undefined {\n if (!info.alternativeOrigins || info.alternativeOrigins.length === 0) return undefined;\n const values = info.alternativeOrigins.map((origin) => originBound(origin, bound));\n return values.every((value): value is number => value !== undefined) ? Math.max(...values) : undefined;\n}\n\nfunction originBound(\n origin: ProvenanceOrigin,\n bound: (node: ts.Expression, env: Environment) => number | undefined,\n): number | undefined {\n return \"binding\" in origin\n ? origin.binding.max ?? alternativeOriginBound(origin.binding, bound)\n : bound(origin.expression, origin.environment);\n}\n\nfunction scanTake(call: ts.CallExpression): number | \"arg\" | undefined {\n const options = call.arguments[2];\n if (!options || !ts.isObjectLiteralExpression(options)) return undefined;\n const take = expressionProperty(options, \"take\");\n return take ? numericLiteral(take) ?? \"arg\" : undefined;\n}\n", "import ts from \"typescript\";\nimport type { CollectionMutationCounts, Environment, ProvenanceOrigin, VariableInfo } from \"../compiler\";\nimport { collectionElementOrigins, originDirectCandidates, snapshotEnvironment } from \"./collection-origins\";\nimport { candidateAmbiguity } from \"./operation-context\";\n\nexport type CollectionFacts = Pick<VariableInfo, \"max\" | \"boundSource\" | \"elementOrigins\">;\n\nexport function collectionMutationIncrement(info: VariableInfo, name: string, env: Environment): number {\n const identity = info.collectionIdentity;\n if (!identity) return 1;\n if (env.collectionMutationCounts) addCollectionMutationCount(env.collectionMutationCounts, identity, 1, name);\n return env.deferredCollectionMutations.has(identity) ? 0 : 1;\n}\n\nexport function addCollectionMutationCount(\n target: CollectionMutationCounts,\n identity: object,\n count: number,\n name: string,\n): void {\n const prior = target.get(identity);\n const total = (prior?.count ?? 0) + count;\n target.set(identity, { count: total, name: prior?.name ?? name });\n}\n\n/**\n * The only writer for cardinality and per-element origin facts. Callers may\n * compute facts in different lowering contexts, but a bound and the origins\n * that justify widening it are installed or invalidated together here.\n */\nexport function maintainCollectionFacts(info: VariableInfo, facts: CollectionFacts): VariableInfo {\n setOrDelete(info, \"max\", facts.max);\n setOrDelete(info, \"boundSource\", facts.boundSource);\n setOrDelete(info, \"elementOrigins\", facts.elementOrigins);\n return info;\n}\n\nexport function collectionFactsFor(\n node: ts.Expression,\n env: Environment,\n max: number | undefined,\n boundSource: string | undefined,\n): CollectionFacts {\n const elementOrigins = collectionElementOrigins(node, env);\n return {\n ...(max !== undefined ? { max, boundSource } : {}),\n ...(elementOrigins !== undefined ? { elementOrigins } : max === 0 ? { elementOrigins: [] } : {}),\n };\n}\n\nexport function appendCollectionFacts(\n info: VariableInfo,\n value: ts.Expression,\n env: Environment,\n count: number,\n summarize: (origins: readonly ProvenanceOrigin[], authoredNode: ts.Expression) =>\n Pick<VariableInfo, \"provenance\" | \"provenanceAmbiguity\">,\n): void {\n const prior = info.elementOrigins ?? (info.max === 0 ? [] : undefined);\n if (!prior) {\n const candidates = new Set<string>([\n \"unknown prior collection origin\",\n ...(info.provenanceAmbiguity?.candidates ?? []),\n ...(info.provenanceAmbiguity?.directRewrite ? [info.provenanceAmbiguity.directRewrite] : []),\n ...directCandidatesForBinding(info),\n ...originDirectCandidates([{ expression: value, environment: env }]),\n ]);\n info.provenance = \"Computed\";\n info.provenanceAmbiguity = candidateAmbiguity([...candidates]);\n maintainCollectionFacts(info, {});\n return;\n }\n const origins = [\n ...prior,\n { expression: value, environment: snapshotEnvironment(env) } satisfies ProvenanceOrigin,\n ];\n maintainCollectionFacts(info, {\n ...(info.max !== undefined ? { max: info.max + count } : {}),\n ...(info.max !== undefined\n ? { boundSource: count > 0 ? `${value.getText(env.sourceFile)} push count` : info.boundSource }\n : {}),\n elementOrigins: origins,\n });\n const summary = summarize(origins, value);\n if (summary.provenanceAmbiguity) {\n info.provenance = summary.provenance;\n info.provenanceAmbiguity = summary.provenanceAmbiguity;\n } else if (!info.provenanceAmbiguity) {\n info.provenance = summary.provenance;\n }\n}\n\nexport function mergeAssignedCollectionFacts(\n info: VariableInfo,\n value: ts.Expression,\n env: Environment,\n nextMax: number | undefined,\n nextBoundSource: string | undefined,\n): void {\n const nextOrigins = collectionElementOrigins(value, env);\n const isCollection = info.collection !== undefined || info.max !== undefined\n || info.elementOrigins !== undefined || nextMax !== undefined || nextOrigins !== undefined;\n if (!isCollection) return;\n const priorOrigins = info.elementOrigins ?? (info.max === 0 ? [] : undefined);\n maintainCollectionFacts(info, {\n ...(info.max !== undefined && nextMax !== undefined\n ? { max: Math.max(info.max, nextMax), boundSource: nextBoundSource ?? info.boundSource }\n : {}),\n ...(priorOrigins !== undefined && nextOrigins !== undefined\n ? { elementOrigins: [...priorOrigins, ...nextOrigins] }\n : {}),\n });\n}\n\nexport function mergeCollectionFactAlternatives(\n target: VariableInfo,\n alternatives: readonly VariableInfo[],\n boundSource: string,\n): void {\n const isCollection = target.collection !== undefined || target.max !== undefined\n || target.elementOrigins !== undefined || alternatives.some((info) =>\n info.collection !== undefined || info.max !== undefined || info.elementOrigins !== undefined);\n if (!isCollection) return;\n const maxima = alternatives.map((info) => info.max);\n const origins = alternatives.map((info) => info.elementOrigins);\n maintainCollectionFacts(target, {\n ...(maxima.every((maximum): maximum is number => maximum !== undefined)\n ? { max: Math.max(...maxima), boundSource }\n : {}),\n ...(origins.every((items): items is ProvenanceOrigin[] => items !== undefined)\n ? { elementOrigins: origins.flat() }\n : {}),\n });\n}\n\nfunction directCandidatesForBinding(info: VariableInfo): string[] {\n if (info.immutableOrigin) return originDirectCandidates([info.immutableOrigin]);\n return [];\n}\n\nfunction setOrDelete<K extends \"max\" | \"boundSource\" | \"elementOrigins\">(\n info: VariableInfo,\n key: K,\n value: VariableInfo[K],\n): void {\n if (key === \"max\") {\n if (value === undefined) delete info.max;\n else info.max = value as number;\n } else if (key === \"boundSource\") {\n if (value === undefined) delete info.boundSource;\n else info.boundSource = value as string;\n } else if (value === undefined) delete info.elementOrigins;\n else info.elementOrigins = value as ProvenanceOrigin[];\n}\n", "import ts from \"typescript\";\nimport { authoredTypeFromColumn, requiredType, isIdType, type AuthoredType } from \"../authored-types\";\nimport { diagnostic } from \"../diagnostics\";\nimport { callName, contextualNodeKey, propertyName, replaceNode, unwrapExpression } from \"../syntax\";\nimport type { Environment, VariableInfo } from \"./environment\";\nimport { expandHelper } from \"./helper-expansion\";\n\nexport function checkScanPrefix(\n node: ts.Expression,\n env: Environment,\n table: string,\n index: string,\n prefixLength: number,\n): boolean {\n const tableInfo = [...env.tables.values()].find((candidate) => candidate.name === table);\n const indexInfo = tableInfo?.indexes?.[index];\n if (!indexInfo || prefixLength <= indexInfo.columns.length) return true;\n env.diagnostics.push(diagnostic(\n env,\n \"E_ARGS_TYPE\",\n node,\n `scan ${env.siteBase}.${env.accessOrdinal.value} prefix supplies ${prefixLength} components but ${table}.${index} has ${indexInfo.columns.length} columns`,\n overlongPrefixRewrite(node, env, indexInfo.columns.length),\n ));\n return false;\n}\n\nexport function checkTupleCursor(\n node: ts.Expression | undefined,\n env: Environment,\n table: string,\n index: string,\n prefixLength: number,\n): void {\n if (!node) return;\n const value = unwrapExpression(node);\n const tableInfo = [...env.tables.values()].find((candidate) => candidate.name === table);\n const indexInfo = tableInfo?.indexes?.[index];\n if (!indexInfo) return;\n const remainingColumns = indexInfo.columns.slice(prefixLength);\n const expectedTypes = indexInfo.types.slice(prefixLength);\n if (remainingColumns.length === 0) {\n env.diagnostics.push(diagnostic(\n env,\n \"E_ARGS_CURSOR_SHAPE\",\n value,\n `scan ${table}.${index} prefix names every index column, so a cursor has no position to compare; remove after/before or shorten the prefix`,\n removeCursorProperties(node, env),\n ));\n return;\n }\n // @ref LLP 1001#3-read-and-write-states-no-silent-states \u2014 a cursored index must be a total order (ends in `id`, or is\n // unique); otherwise tied keys are skipped between pages. The runtime accepts the\n // lossy shape, so this is a policy refusal like an unbounded scan, not a type check.\n if (indexInfo.columns.at(-1) !== \"id\" && indexInfo.unique !== true) {\n const totalOrderColumns = [...indexInfo.columns.filter((column) => column !== \"id\"), \"id\"];\n env.diagnostics.push(diagnostic(\n env,\n \"E_ARGS_CURSOR_INDEX\",\n value,\n `scan ${table}.${index} uses a cursor, so the index must be a total order: end in id, or be unique`,\n `change ${table}.${index} to { columns: [${totalOrderColumns.map((column) => JSON.stringify(column)).join(\", \")}] }`,\n ));\n return;\n }\n\n const expanded = expandHelper(value, env);\n const shapeValue = unwrapExpression(expanded?.expression ?? value);\n const shapeEnv = expanded?.environment ?? env;\n const authored = expressionType(shapeValue, shapeEnv);\n const elements = ts.isArrayLiteralExpression(shapeValue) ? [...shapeValue.elements] : undefined;\n const knownNonScalar = staticallyObjectExpression(shapeValue, shapeEnv) || knownRuntimeScalar(authored) === false;\n if (remainingColumns.length === 1 && !elements && knownNonScalar) {\n env.diagnostics.push(diagnostic(\n env,\n \"E_ARGS_CURSOR_SHAPE\",\n value,\n `scan ${table}.${index} cursor must be an indexable scalar for its one remaining index column`,\n argumentTupleRewrite(node, env, remainingColumns, expectedTypes),\n ));\n return;\n }\n const shapeMatches = elements\n ? elements.length === remainingColumns.length\n : knownRuntimeScalar(authored) === true\n ? remainingColumns.length === 1\n : knownRuntimeScalar(authored) === false\n ? remainingColumns.length === 1 ? undefined : false\n : undefined;\n const tuple = tupleExpression(node, env, table, remainingColumns);\n const tupleRewrite = tuple ? replaceNode(env.source, node, tuple) : env.source;\n const rewrite = tuple && tupleRewrite !== env.source\n ? tupleRewrite\n : argumentTupleRewrite(node, env, remainingColumns, expectedTypes);\n if (shapeMatches === false) {\n env.diagnostics.push(diagnostic(\n env,\n \"E_ARGS_CURSOR_SHAPE\",\n value,\n `scan ${table}.${index} cursor has the wrong static shape: expected exactly ${remainingColumns.length} cursor value(s), one per remaining index column`,\n rewrite,\n ));\n return;\n }\n\n const components = elements ?? (remainingColumns.length === 1 ? [shapeValue] : undefined);\n if (!components || components.length !== remainingColumns.length) return;\n const bound = node.parent && ts.isPropertyAssignment(node.parent)\n ? propertyName(node.parent.name) ?? \"after\"\n : \"after\";\n components.forEach((component, offset) => {\n const actual = expressionType(component, shapeEnv);\n const expected = expectedTypes[offset];\n if (cursorTypeMatches(actual, expected) !== false) return;\n env.diagnostics.push(diagnostic(\n env,\n \"E_ARGS_TYPE\",\n component,\n `scan ${env.siteBase}.${env.accessOrdinal.value} ${bound} cursor component ${offset + 1} is ${cursorTypeName(actual)} but ${table}.${index} column ${remainingColumns[offset]} is ${cursorTypeName(expected)}`,\n rewrite,\n ));\n });\n}\n\nfunction staticallyObjectExpression(\n node: ts.Expression,\n env: Environment,\n seen = new Set<ts.Expression>(),\n): boolean {\n const value = unwrapExpression(node);\n if (seen.has(value)) return false;\n seen.add(value);\n if (ts.isObjectLiteralExpression(value)) return true;\n if (!ts.isIdentifier(value)) return false;\n const substitution = env.substitutions.get(value.text);\n if (substitution) return staticallyObjectExpression(substitution.expression, substitution.environment, seen);\n const origin = env.variables.get(value.text)?.immutableOrigin;\n return origin ? staticallyObjectExpression(origin.expression, origin.environment, seen) : false;\n}\n\nfunction removeCursorProperties(node: ts.Expression, env: Environment): string {\n const property = node.parent;\n const object = property?.parent;\n if (!property || !ts.isPropertyAssignment(property) || !object || !ts.isObjectLiteralExpression(object)) {\n return env.source;\n }\n return replaceNode(env.source, object, optionsWithoutCursorProperties(object, env));\n}\n\nfunction overlongPrefixRewrite(node: ts.Expression, env: Environment, columnCount: number): string {\n const value = unwrapExpression(node);\n const prefix = ts.isArrayLiteralExpression(value)\n ? `[${value.elements.slice(0, columnCount).map((element) => element.getText(env.sourceFile)).join(\", \")}]`\n : \"[]\";\n const call = node.parent;\n const options = call && ts.isCallExpression(call) && call.arguments[1] === node\n ? call.arguments[2]\n : undefined;\n const object = options && ts.isObjectLiteralExpression(unwrapExpression(options))\n ? unwrapExpression(options) as ts.ObjectLiteralExpression\n : undefined;\n const edits = [{ start: node.getStart(env.sourceFile), end: node.getEnd(), value: prefix }];\n if (object && columnCount > 0) {\n edits.push({\n start: object.getStart(env.sourceFile),\n end: object.getEnd(),\n value: optionsWithoutCursorProperties(object, env),\n });\n }\n return replaceRanges(env.source, edits);\n}\n\nfunction optionsWithoutCursorProperties(object: ts.ObjectLiteralExpression, env: Environment): string {\n const kept = object.properties.filter((property) => {\n if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) return true;\n const name = propertyName(property.name);\n return name !== \"after\" && name !== \"before\";\n });\n return `{ ${kept.map((property) => property.getText(env.sourceFile)).join(\", \")} }`;\n}\n\nfunction expressionType(node: ts.Expression, env: Environment): AuthoredType | undefined {\n const value = unwrapExpression(node);\n if (ts.isIdentifier(value)) {\n const origin = env.variables.get(value.text)?.immutableOrigin;\n if (origin) return expressionType(origin.expression, origin.environment);\n }\n if (ts.isPropertyAccessExpression(value)) {\n const base = unwrapExpression(value.expression);\n if (ts.isIdentifier(base) && env.variables.get(base.text)?.operationComposite === \"args\") {\n return authoredTypeFromColumn(env.args[value.name.text]);\n }\n const baseType = env.expressionTypes.get(contextualNodeKey(env.literalContext, base, env.sourceFile));\n const row = requiredType(baseType);\n if (row.kind === \"row\") {\n const table = [...env.tables.values()].find((candidate) => candidate.name === row.table);\n const field = table?.columns?.[value.name.text];\n if (field) return field;\n }\n }\n return env.expressionTypes.get(contextualNodeKey(env.literalContext, value, env.sourceFile));\n}\n\nfunction knownRuntimeScalar(type: AuthoredType | undefined): boolean | undefined {\n if (type?.kind === \"optional\" || type?.kind === \"row\" || type?.kind === \"asset\") return undefined;\n const value = requiredType(type);\n if (value.kind === \"unknown\" || value.kind === \"json\" || value.kind === \"list\") return undefined;\n if (value.kind === \"object\") return false;\n return true;\n}\n\nfunction cursorTypeMatches(\n actual: AuthoredType | undefined,\n expected: AuthoredType | undefined,\n): boolean | undefined {\n if (actual?.kind === \"optional\") {\n const nonNull = cursorTypeMatches(actual.of, expected);\n return nonNull === false ? undefined : nonNull;\n }\n const left = requiredType(actual);\n const right = requiredType(expected);\n if (left.kind === \"null\") return true;\n if (left.kind === \"unknown\" || left.kind === \"json\" || left.kind === \"row\" || right.kind === \"unknown\") return undefined;\n if (right.kind === \"json\") return knownRuntimeScalar(left);\n if (isIdType(right) || right.kind === \"principal\") {\n return isIdType(left) || left.kind === \"principal\";\n }\n if (right.kind === \"string\" || right.kind === \"enum\") {\n return left.kind === \"string\" && !isIdType(left) || left.kind === \"enum\";\n }\n if (right.kind === \"int\" || right.kind === \"decimal\") {\n return left.kind === \"int\" || left.kind === \"decimal\";\n }\n if (right.kind === \"bool\") return left.kind === \"bool\";\n if (right.kind === \"bytes\") return left.kind === \"bytes\";\n return false;\n}\n\nfunction cursorTypeName(type: AuthoredType | undefined): string {\n const value = requiredType(type);\n if (isIdType(value) || value.kind === \"principal\") return \"Id\";\n if (value.kind === \"string\" || value.kind === \"enum\") return \"String\";\n if (value.kind === \"int\" || value.kind === \"decimal\") return \"Int\";\n if (value.kind === \"bool\") return \"Bool\";\n if (value.kind === \"bytes\") return \"Bytes\";\n if (value.kind === \"null\") return \"Null\";\n if (value.kind === \"list\") return \"array\";\n if (value.kind === \"row\" || value.kind === \"object\") return \"object\";\n return \"unknown\";\n}\n\nfunction tupleExpression(node: ts.Expression, env: Environment, table: string, columns: string[]): string | undefined {\n const value = unwrapExpression(node);\n const rowBase = (candidate: ts.Expression): ts.Expression | undefined => {\n const unwrapped = unwrapExpression(candidate);\n if (ts.isPropertyAccessExpression(unwrapped)) {\n const base = unwrapExpression(unwrapped.expression);\n if (ts.isIdentifier(base) && bindingTable(env.variables.get(base.text)) === table) {\n return unwrapped.expression;\n }\n const type = env.expressionTypes.get(contextualNodeKey(env.literalContext, base, env.sourceFile));\n if (requiredType(type).kind === \"row\") return unwrapped.expression;\n }\n return undefined;\n };\n if (ts.isArrayLiteralExpression(value)) {\n const bases = value.elements.map(rowBase);\n const first = bases[0]?.getText(env.sourceFile);\n if (first && bases.every((base) => base?.getText(env.sourceFile) === first)) {\n return `[${columns.map((column) => `${first}.${column}`).join(\", \")}]`;\n }\n return undefined;\n }\n const authoredBase = rowBase(value)?.getText(env.sourceFile);\n const rowBinding = [...env.variables].find(([, info]) => info.rowBinding && bindingTable(info) === table)?.[0];\n const base = authoredBase ?? rowBinding;\n if (base) return `[${columns.map((column) => `${base}.${column}`).join(\", \")}]`;\n\n if (columns.length === 1 && !ts.isArrayLiteralExpression(value)) {\n return value.getText(env.sourceFile);\n }\n return undefined;\n}\n\nfunction bindingTable(info: VariableInfo | undefined): string | undefined {\n if (!info) return undefined;\n if (info.rowTable) return info.rowTable;\n const expression: any = info.identityExpression;\n return expression?.Get?.table;\n}\n\nfunction argumentTupleRewrite(\n node: ts.Expression,\n env: Environment,\n columns: string[],\n types: AuthoredType[],\n): string {\n const operation = enclosingOperation(node);\n const argsNode = operation?.arguments[0];\n const handler = operation?.arguments[1];\n if (!argsNode || !handler || !ts.isObjectLiteralExpression(unwrapExpression(argsNode))) return env.source;\n const argsObject = unwrapExpression(argsNode) as ts.ObjectLiteralExpression;\n const bound = node.parent && ts.isPropertyAssignment(node.parent) ? propertyName(node.parent.name) : undefined;\n const prefix = bound === \"before\" ? \"before\" : \"after\";\n const used = new Set(Object.keys(env.args));\n const names = columns.map((column) => uniqueArgument(used, `${prefix}${column[0]?.toUpperCase() ?? \"\"}${column.slice(1)}`));\n const declarations = names.map((name, index) => `${name}: ${descriptor(types[index])}`).join(\", \");\n const argsText = argsObject.getText(env.sourceFile);\n const rewrittenArgs = `${argsText.slice(0, -1).trimEnd()}${argsObject.properties.length === 0 ? \" \" : \", \"}${declarations} }`;\n const edits = [\n { start: argsObject.getStart(env.sourceFile), end: argsObject.getEnd(), value: rewrittenArgs },\n { start: node.getStart(env.sourceFile), end: node.getEnd(), value: `[${names.map((name) => `__ARGS__.${name}`).join(\", \")}]` },\n ];\n let binding = [...env.variables].find(([, info]) => info.operationComposite === \"args\")?.[0];\n const parameter = (ts.isArrowFunction(handler) || ts.isFunctionExpression(handler)) ? handler.parameters[0]?.name : undefined;\n if (!binding && parameter && ts.isObjectBindingPattern(parameter)) {\n binding = uniqueBinding(env.source, \"snapbackArgs\");\n const text = parameter.getText(env.sourceFile);\n edits.push({\n start: parameter.getStart(env.sourceFile),\n end: parameter.getEnd(),\n value: `${text.slice(0, -1).trimEnd()}${parameter.elements.length === 0 ? \" \" : \", \"}args: ${binding} }`,\n });\n }\n if (!binding) return env.source;\n edits[1]!.value = edits[1]!.value.replaceAll(\"__ARGS__\", binding);\n return replaceRanges(env.source, edits);\n}\n\nfunction enclosingOperation(node: ts.Node): ts.CallExpression | undefined {\n for (let parent: ts.Node | undefined = node.parent; parent; parent = parent.parent) {\n if (ts.isCallExpression(parent) && [\"query\", \"mutation\"].includes(callName(parent))) return parent;\n }\n return undefined;\n}\n\nfunction uniqueArgument(used: Set<string>, base: string): string {\n let value = base;\n let suffix = 1;\n while (used.has(value)) value = `${base}${suffix++}`;\n used.add(value);\n return value;\n}\n\nfunction uniqueBinding(source: string, base: string): string {\n let value = base;\n let suffix = 1;\n while (new RegExp(`\\\\b${value}\\\\b`).test(source)) value = `${base}${suffix++}`;\n return value;\n}\n\nfunction descriptor(type: AuthoredType | undefined): string {\n if (!type) return \"t.json(4096)\";\n if (isIdType(requiredType(type))) return \"t.id()\";\n switch (type.kind) {\n case \"optional\": return `t.optional(${descriptor(type.of)})`;\n case \"int\": return \"t.int()\";\n case \"principal\": return \"t.principal()\";\n case \"string\": return `t.text(${type.max ?? 4096})`;\n case \"bytes\": return `t.bytes(${type.max})`;\n case \"asset\": return `t.${type.asset}(${type.max})`;\n case \"bool\": return \"t.bool()\";\n case \"enum\": return `t.enum(${JSON.stringify(type.variants)})`;\n case \"decimal\": return type.currency ? `t.money(${JSON.stringify(type.currency)}, ${type.scale})` : `t.decimal(${type.scale})`;\n case \"list\": return `t.list(${descriptor(type.of)}, { max: ${type.max ?? 64} })`;\n default: return \"t.json(4096)\";\n }\n}\n\nfunction replaceRanges(source: string, ranges: Array<{ start: number; end: number; value: string }>): string {\n let rewritten = source;\n for (const range of ranges.sort((left, right) => right.start - left.start)) {\n rewritten = `${rewritten.slice(0, range.start)}${range.value}${rewritten.slice(range.end)}`;\n }\n return rewritten;\n}\n", "export type AuthoredType =\n | { kind: \"unknown\" }\n | { kind: \"null\" }\n | { kind: \"object\"; fields?: Record<string, AuthoredType> }\n | { kind: \"int\" }\n | { kind: \"decimal\"; scale: number; currency?: string }\n | { kind: \"enum\"; variants: string[] }\n | { kind: \"string\"; max?: number; id?: true }\n | { kind: \"principal\" }\n | { kind: \"bytes\"; max: number }\n | { kind: \"asset\"; asset: \"image\" | \"video\"; max: number }\n | { kind: \"bool\" }\n | { kind: \"json\"; max?: number }\n | { kind: \"row\"; table: string }\n | { kind: \"list\"; of: AuthoredType; max?: number }\n | { kind: \"optional\"; of: AuthoredType };\n\nexport type TableInfo = {\n name: string;\n private: boolean;\n maintainedFrom?: string;\n columns?: Record<string, AuthoredType>;\n indexes?: Record<string, { columns: string[]; types: AuthoredType[]; unique?: boolean }>;\n readRule?: unknown;\n};\n\nexport const unknownType: AuthoredType = { kind: \"unknown\" };\nexport const intType: AuthoredType = { kind: \"int\" };\nexport const idType: AuthoredType = { kind: \"string\", id: true };\n\nexport function isIdType(value: AuthoredType | undefined): boolean {\n return value?.kind === \"string\" && value.id === true;\n}\n\nexport function authoredTypeFromColumn(value: unknown): AuthoredType {\n if (value === \"Int\" || value === \"Time\") return intType;\n if (value === \"Bool\") return { kind: \"bool\" };\n if (value === \"Id\") return idType;\n if (value === \"Principal\") return { kind: \"principal\" };\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return unknownType;\n const descriptor = value as Record<string, any>;\n if (descriptor.Text) return { kind: \"string\", max: descriptor.Text.max };\n if (descriptor.Bytes) return { kind: \"bytes\", max: descriptor.Bytes.max };\n if (descriptor.Image) return { kind: \"asset\", asset: \"image\", max: descriptor.Image.max };\n if (descriptor.Video) return { kind: \"asset\", asset: \"video\", max: descriptor.Video.max };\n if (descriptor.Ref) return idType;\n if (descriptor.Json) return { kind: \"json\", max: descriptor.Json.max_bytes };\n if (descriptor.Enum) return { kind: \"enum\", variants: [...descriptor.Enum.variants] };\n if (descriptor.Decimal) return { kind: \"decimal\", scale: descriptor.Decimal.scale };\n if (descriptor.Money) {\n return { kind: \"decimal\", scale: descriptor.Money.scale, currency: descriptor.Money.currency };\n }\n if (\"Optional\" in descriptor) return { kind: \"optional\", of: authoredTypeFromColumn(descriptor.Optional) };\n if (descriptor.List) {\n return { kind: \"list\", of: authoredTypeFromColumn(descriptor.List.of), max: descriptor.List.max };\n }\n return unknownType;\n}\n\nexport function requiredType(value: AuthoredType | undefined): AuthoredType {\n return value?.kind === \"optional\" ? requiredType(value.of) : value ?? unknownType;\n}\n\nexport function sameDecimal(left: AuthoredType, right: AuthoredType): boolean {\n return left.kind === \"decimal\" && right.kind === \"decimal\"\n && left.scale === right.scale && left.currency === right.currency;\n}\n", "import ts from \"typescript\";\nimport type { CollectionMutationCounts, Environment, VariableInfo } from \"../compiler\";\nimport { addCollectionMutationCount, mergeCollectionFactAlternatives } from \"./collection-facts\";\nimport { cloneEnvironment } from \"./expr\";\nimport { candidateAmbiguity } from \"./operation-context\";\n\nexport type BranchEnvironment = {\n environment: Environment;\n outerBindings: Map<string, VariableInfo>;\n collectionMutationCounts?: CollectionMutationCounts;\n};\n\nexport function forkBranchEnvironment(env: Environment): BranchEnvironment {\n const environment = cloneEnvironment(env);\n const collectionMutationCounts = env.collectionMutationCounts ? new Map() : undefined;\n environment.collectionMutationCounts = collectionMutationCounts;\n return { environment, outerBindings: new Map(environment.variables), collectionMutationCounts };\n}\n\nexport function mergeBranchEnvironments(\n env: Environment,\n branches: readonly BranchEnvironment[],\n site: ts.Node,\n): void {\n for (const [name, target] of env.variables) {\n const alternatives = branches.flatMap((branch) => branch.outerBindings.get(name)\n ? [branch.outerBindings.get(name)!]\n : []);\n if (alternatives.length !== branches.length) continue;\n const candidates = new Set(alternatives.flatMap((info) => [\n ...(info.provenanceAmbiguity?.candidates ?? []),\n ...(info.provenanceAmbiguity?.directRewrite ? [info.provenanceAmbiguity.directRewrite] : []),\n ]));\n if (candidates.size > 0) {\n target.provenance = \"Computed\";\n target.provenanceAmbiguity = candidateAmbiguity([...candidates]);\n }\n mergeCollectionFactAlternatives(target, alternatives, `${site.getText(env.sourceFile)} branch maximum`);\n if (alternatives.some((info) => info.nullableRead === false)) target.nullableRead = false;\n }\n if (!env.collectionMutationCounts) return;\n const identities = new Set(branches.flatMap((branch) => [...(branch.collectionMutationCounts?.keys() ?? [])]));\n for (const identity of identities) {\n const alternatives = branches.map((branch) => branch.collectionMutationCounts?.get(identity));\n const maximum = Math.max(...alternatives.map((entry) => entry?.count ?? 0));\n const name = alternatives.find((entry) => entry)?.name;\n if (name && maximum > 0) addCollectionMutationCount(env.collectionMutationCounts, identity, maximum, name);\n }\n}\n", "import ts from \"typescript\";\nimport type { CollectionMutationCounts, Environment, VariableInfo } from \"./environment\";\nimport type { Stmt } from \"../ir\";\nimport { refuse, Refusal } from \"../diagnostics\";\nimport { addCollectionMutationCount, maintainCollectionFacts } from \"./collection-facts\";\nimport { cloneEnvironment } from \"./expr\";\n\ntype InheritedCollection = { name: string; info: VariableInfo };\ntype LoopMutationPlan = {\n counts: CollectionMutationCounts;\n facts: Map<object, VariableInfo>;\n iterations: number;\n};\n\nconst LOOP_MUTATION_FIXPOINT_LIMIT = 16;\n\nexport function lowerLoopBodyWithMutationPlan(\n statement: ts.ForOfStatement,\n env: Environment,\n iterations: number,\n domainIdentity: object | undefined,\n lowerBody: (statement: ts.Statement, env: Environment) => Stmt[],\n): Stmt[] {\n const ancestorDeferred = new Set(env.deferredCollectionMutations);\n const inherited = inheritedCollections(env);\n const plan = settleLoopMutationPlan(statement, env, inherited, iterations, domainIdentity, lowerBody);\n applyLoopMutationPlan(env, inherited, plan, ancestorDeferred);\n env.deferredCollectionMutations = new Set([...ancestorDeferred, ...inherited.keys()]);\n const parentMutationCounts = env.collectionMutationCounts;\n env.collectionMutationCounts = new Map();\n const body = lowerBody(statement.statement, env);\n applyLoopMutationPlan(env, inherited, plan, ancestorDeferred);\n if (parentMutationCounts) {\n for (const [identity, mutation] of plan.counts) {\n const scaled = mutation.count * iterations;\n if (!Number.isSafeInteger(scaled)) {\n refuse(env, \"E_UNBOUND_LOOP\", statement.expression, \"nested collection mutation delta exceeds the static integer range\");\n }\n addCollectionMutationCount(parentMutationCounts, identity, scaled, mutation.name);\n }\n }\n return body;\n}\n\nfunction inheritedCollections(env: Environment): Map<object, InheritedCollection> {\n const inherited = new Map<object, InheritedCollection>();\n for (const [name, info] of env.variables) {\n if (info.collectionIdentity && !inherited.has(info.collectionIdentity)) {\n inherited.set(info.collectionIdentity, { name, info });\n }\n }\n return inherited;\n}\n\nfunction settleLoopMutationPlan(\n statement: ts.ForOfStatement,\n env: Environment,\n inherited: Map<object, InheritedCollection>,\n iterations: number,\n domainIdentity: object | undefined,\n lowerBody: (statement: ts.Statement, env: Environment) => Stmt[],\n): LoopMutationPlan {\n let priorCounts: CollectionMutationCounts = new Map();\n let priorFacts = new Map<object, VariableInfo>();\n for (let pass = 0; pass < LOOP_MUTATION_FIXPOINT_LIMIT; pass += 1) {\n const probe = isolatedAnalysisEnvironment(env);\n for (const [identity, collection] of inherited) {\n const info = variableByIdentity(probe, identity, collection.name);\n if (!info) continue;\n const prior = priorFacts.get(identity);\n if (prior) copyCollectionBounds(info, prior);\n const mutation = priorCounts.get(identity);\n if (mutation && !env.deferredCollectionMutations.has(identity)) {\n if (collection.info.max === undefined) {\n refuse(env, \"E_UNBOUND_LOOP\", statement.expression, \"collection mutation has no provable pre-loop cardinality\");\n }\n const maximum = collection.info.max + iterations * mutation.count;\n if (!Number.isSafeInteger(maximum)) {\n refuse(env, \"E_UNBOUND_LOOP\", statement.expression, \"collection mutation bound exceeds the static integer range\");\n }\n maintainCollectionFacts(info, {\n max: maximum,\n boundSource: `${mutation.name} mutations \u00D7 loop bound ${iterations}`,\n ...(info.elementOrigins !== undefined ? { elementOrigins: info.elementOrigins } : {}),\n });\n }\n }\n probe.deferredCollectionMutations = new Set([...env.deferredCollectionMutations, ...inherited.keys()]);\n probe.collectionMutationCounts = new Map();\n lowerBody(statement.statement, probe);\n const unbound = probe.diagnostics.find((diagnostic) => diagnostic.code === \"E_UNBOUND_LOOP\");\n if (unbound) throw new Refusal(unbound);\n const counts = new Map([...probe.collectionMutationCounts]\n .filter(([identity]) => inherited.has(identity)));\n if (domainIdentity && counts.has(domainIdentity)) {\n refuse(\n env,\n \"E_UNBOUND_LOOP\",\n statement.expression,\n \"collection mutation bound depends on its own growing loop domain and has no finite static fixed point\",\n );\n }\n const facts = new Map<object, VariableInfo>();\n for (const [identity, collection] of inherited) {\n const info = variableByIdentity(probe, identity, collection.name);\n if (info) facts.set(identity, info);\n }\n if (sameMutationCounts(priorCounts, counts)) return { counts, facts, iterations };\n priorCounts = counts;\n priorFacts = facts;\n }\n refuse(\n env,\n \"E_UNBOUND_LOOP\",\n statement.expression,\n \"collection mutation bound depends on a growing loop domain and has no finite static fixed point\",\n );\n}\n\nfunction copyCollectionBounds(target: VariableInfo, source: VariableInfo): void {\n maintainCollectionFacts(target, {\n ...(source.max !== undefined ? { max: source.max } : {}),\n ...(source.boundSource !== undefined ? { boundSource: source.boundSource } : {}),\n ...(target.elementOrigins !== undefined ? { elementOrigins: target.elementOrigins } : {}),\n });\n}\n\nfunction isolatedAnalysisEnvironment(env: Environment): Environment {\n const probe = cloneEnvironment(env);\n probe.accessOrdinal = { value: env.accessOrdinal.value };\n probe.temp = { value: env.temp.value };\n probe.diagnostics = [];\n probe.recursion = { depth: 0, active: new Map() };\n probe.collectionMutationCounts = new Map();\n return probe;\n}\n\nfunction applyLoopMutationPlan(\n env: Environment,\n inherited: Map<object, InheritedCollection>,\n plan: LoopMutationPlan,\n ancestorDeferred: Set<object>,\n): void {\n for (const [identity, collection] of inherited) {\n if (ancestorDeferred.has(identity)) continue;\n const target = variableByIdentity(env, identity, collection.name);\n const source = plan.facts.get(identity);\n if (!target || !source) continue;\n copyCollectionState(target, source);\n const mutation = plan.counts.get(identity);\n if (mutation && target.max !== undefined) {\n target.boundSource = `${mutation.name} mutations \u00D7 loop bound ${plan.iterations}`;\n }\n }\n}\n\nfunction copyCollectionState(target: VariableInfo, source: VariableInfo): void {\n target.provenance = source.provenance;\n if (source.provenanceAmbiguity) {\n target.provenanceAmbiguity = {\n ...source.provenanceAmbiguity,\n ...(source.provenanceAmbiguity.candidates\n ? { candidates: [...source.provenanceAmbiguity.candidates] }\n : {}),\n };\n } else {\n delete target.provenanceAmbiguity;\n }\n maintainCollectionFacts(target, {\n ...(source.max !== undefined ? { max: source.max } : {}),\n ...(source.boundSource !== undefined ? { boundSource: source.boundSource } : {}),\n ...(source.elementOrigins !== undefined ? { elementOrigins: [...source.elementOrigins] } : {}),\n });\n}\n\nfunction variableByIdentity(env: Environment, identity: object, preferredName: string): VariableInfo | undefined {\n const preferred = env.variables.get(preferredName);\n if (preferred?.collectionIdentity === identity) return preferred;\n return [...env.variables.values()].find((info) => info.collectionIdentity === identity);\n}\n\nfunction sameMutationCounts(left: CollectionMutationCounts, right: CollectionMutationCounts): boolean {\n if (left.size !== right.size) return false;\n for (const [identity, mutation] of left) {\n if (right.get(identity)?.count !== mutation.count) return false;\n }\n return true;\n}\n", "import ts from \"typescript\";\nimport { refuse } from \"../diagnostics\";\nimport type { Expr } from \"../ir\";\nimport { literal, stringArgument, unwrapExpression } from \"../syntax\";\nimport type { Environment, LoweredValue } from \"./environment\";\n\nexport function lowerMergeByIndex(\n call: ts.CallExpression,\n env: Environment,\n hint: string | undefined,\n lowerValue: (node: ts.Expression, env: Environment, hint?: string) => LoweredValue,\n lowerExpr: (node: ts.Expression, env: Environment, hint?: string) => Expr,\n): LoweredValue {\n const rows = call.arguments[0];\n const fields = call.arguments[1];\n const order = stringArgument(call.arguments[2]);\n const limit = call.arguments[3];\n const site = stringArgument(call.arguments[4]);\n const table = stringArgument(call.arguments[5]);\n if (!rows || !fields || !ts.isArrayLiteralExpression(unwrapExpression(fields)) || !limit || !site || !table\n || (order !== \"asc\" && order !== \"desc\")) {\n refuse(env, \"E_OPAQUE\", call, \"mergeByIndex requires rows, static fields, asc/desc, take, site, and table\");\n }\n const lowered = lowerValue(rows, env, hint);\n const keys = (unwrapExpression(fields) as ts.ArrayLiteralExpression).elements.map((field) => {\n const name = stringArgument(field);\n if (!name) refuse(env, \"E_OPAQUE\", field, \"mergeByIndex fields must be static strings\");\n return { field: name, order: order === \"desc\" ? \"Desc\" as const : \"Asc\" as const };\n });\n const sorted: Expr = { Builtin: { builtin: { Sort: { keys } }, args: [lowered.expression] } };\n const deduped: Expr = { Builtin: { builtin: { DedupeById: { site, table } }, args: [sorted] } };\n return {\n statements: lowered.statements,\n expression: { Builtin: { builtin: \"Slice\", args: [deduped, literal(0), lowerExpr(limit, env)] } },\n };\n}\n", "import ts from \"typescript\";\nimport { requiredType } from \"../authored-types\";\nimport { refuse } from \"../diagnostics\";\nimport type { Expr, Stmt } from \"../ir\";\nimport { collectionConstructor, contextualNodeKey, literal, temporary, unwrapExpression } from \"../syntax\";\nimport { staticBound } from \"./binding-bound\";\nimport type { Environment, LoweredValue } from \"./environment\";\n\ntype LowerValue = (node: ts.Expression, env: Environment, hint?: string) => LoweredValue;\n\nexport function lowerCollectionConstructor(\n expression: ts.NewExpression,\n env: Environment,\n lowerValue: LowerValue,\n hint?: string,\n): LoweredValue {\n const kind = collectionConstructor(expression);\n if (!kind) refuse(env, \"E_OPAQUE\", expression, \"only Map and Set constructors are admitted\");\n const initializer = expression.arguments?.[0];\n if (!initializer) return { statements: [], expression: { Array: [] } };\n if ((expression.arguments?.length ?? 0) !== 1) {\n refuse(env, \"E_OPAQUE\", expression, `${kind} constructor accepts at most one bounded initializer`);\n }\n if (kind === \"Set\") return lowerSetConstructor(initializer, env, lowerValue, hint);\n const entries = unwrapExpression(initializer);\n if (!ts.isArrayLiteralExpression(entries)) {\n refuse(env, \"E_OPAQUE\", initializer, \"Map initializer must be a bounded array literal of [key, value] pairs\");\n }\n const statements: Stmt[] = [];\n const result = temporary(env, \"mapResult\");\n statements.push({ Let: { name: result, value: { Array: [] } } });\n let maximum = 0;\n for (const entry of entries.elements) {\n const pair = unwrapExpression(entry);\n if (!ts.isArrayLiteralExpression(pair) || pair.elements.length !== 2) {\n refuse(env, \"E_OPAQUE\", entry, \"Map initializer entries must be [key, value] pairs\");\n }\n requirePrimitiveCollectionIdentity(pair.elements[0]!, env, \"Map keys\");\n const key = lowerValue(pair.elements[0]!, env, hint);\n const value = lowerValue(pair.elements[1]!, env, hint);\n statements.push(...lowerMapAssignment(result, key, value, maximum, \"Map initializer bound\", env));\n maximum += 1;\n }\n return { statements, expression: { Variable: result } };\n}\n\nfunction lowerSetConstructor(\n initializer: ts.Expression,\n env: Environment,\n lowerValue: LowerValue,\n hint?: string,\n): LoweredValue {\n const lowered = lowerValue(initializer, env, hint);\n const max = staticBound(initializer, env);\n if (max === undefined) refuse(env, \"E_UNBOUND_LOOP\", initializer, \"Set initializer must have a static bound\");\n const sourceValue = unwrapExpression(initializer);\n if (ts.isArrayLiteralExpression(sourceValue)) {\n for (const element of sourceValue.elements) {\n if (ts.isSpreadElement(element)) {\n requirePrimitiveCollectionIdentity(element.expression, env, \"Set elements\", true);\n } else {\n requirePrimitiveCollectionIdentity(element, env, \"Set elements\");\n }\n }\n } else {\n requirePrimitiveCollectionIdentity(initializer, env, \"Set elements\", true);\n }\n const source = temporary(env, \"setSource\");\n const result = temporary(env, \"setResult\");\n const item = temporary(env, \"setItem\");\n const existing = temporary(env, \"setExisting\");\n const found = temporary(env, \"setFound\");\n return {\n statements: [\n ...lowered.statements,\n { Let: { name: source, value: lowered.expression } },\n { Let: { name: result, value: { Array: [] } } },\n { For: {\n binding: item,\n domain: { DerivedArray: { value: { Variable: source }, max, bound_source: `${initializer.getText(env.sourceFile)} static bound` } },\n body: [\n { Let: { name: found, value: literal(false) } },\n { For: {\n binding: existing,\n domain: { DerivedArray: { value: { Variable: result }, max, bound_source: \"Set uniqueness bound\" } },\n body: [{ If: {\n condition: { Binary: { op: \"SameValueZero\", left: { Variable: existing }, right: { Variable: item } } },\n then_body: [{ Assign: { name: found, value: literal(true) } }],\n else_body: [],\n } }],\n } },\n { If: {\n condition: { Unary: { op: \"Not\", value: { Variable: found } } },\n then_body: [{ Push: { target: result, value: { Variable: item } } }],\n else_body: [],\n } },\n ],\n } },\n ],\n expression: { Variable: result },\n };\n}\n\nexport function lowerMapAssignment(\n target: string,\n key: LoweredValue,\n value: LoweredValue,\n max: number,\n boundSource: string | undefined,\n env: Environment,\n): Stmt[] {\n // @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 Materialize each Map operand before any later operand setup.\n const authoredKey = temporary(env, \"authoredMapKey\");\n const authoredValue = temporary(env, \"authoredMapValue\");\n const keyName = temporary(env, \"mapKey\");\n const valueName = temporary(env, \"mapValue\");\n const result = temporary(env, \"mapUpdated\");\n const entry = temporary(env, \"mapEntry\");\n const found = temporary(env, \"mapFound\");\n const replacement = { Object: { key: { Variable: keyName }, value: { Variable: valueName } } } satisfies Expr;\n return [\n ...key.statements,\n { Let: { name: authoredKey, value: key.expression } },\n ...value.statements,\n { Let: { name: authoredValue, value: value.expression } },\n { Let: { name: keyName, value: { Variable: authoredKey } } },\n { Let: { name: valueName, value: { Variable: authoredValue } } },\n { Let: { name: result, value: { Array: [] } } },\n { Let: { name: found, value: literal(false) } },\n { For: {\n binding: entry,\n domain: { DerivedArray: { value: { Variable: target }, max, bound_source: boundSource ?? \"Map static bound\" } },\n body: [{ If: {\n condition: { Binary: { op: \"SameValueZero\", left: { Field: { base: { Variable: entry }, name: \"key\" } }, right: { Variable: keyName } } },\n then_body: [\n { If: {\n condition: { Unary: { op: \"Not\", value: { Variable: found } } },\n then_body: [{ Push: { target: result, value: replacement } }],\n else_body: [],\n } },\n { Assign: { name: found, value: literal(true) } },\n ],\n else_body: [{ Push: { target: result, value: { Variable: entry } } }],\n } }],\n } },\n { If: {\n condition: { Unary: { op: \"Not\", value: { Variable: found } } },\n then_body: [{ Push: { target: result, value: replacement } }],\n else_body: [],\n } },\n { Assign: { name: target, value: { Variable: result } } },\n ];\n}\n\nexport function lowerCollectionLookup(\n owner: ts.Identifier,\n needle: Expr,\n env: Environment,\n mode: \"MapGet\" | \"MapHas\" | \"SetHas\",\n): LoweredValue {\n const info = env.variables.get(owner.text);\n if (info?.max === undefined) {\n refuse(env, \"E_UNBOUND_LOOP\", owner, `${owner.text}.${mode === \"MapGet\" ? \"get\" : \"has\"} needs a statically bounded collection`);\n }\n const binding = temporary(env, mode === \"SetHas\" ? \"setItem\" : \"mapEntry\");\n const needleName = temporary(env, \"collectionNeedle\");\n const result = temporary(env, mode === \"MapGet\" ? \"mapValue\" : \"collectionHas\");\n const candidate = mode === \"SetHas\"\n ? { Variable: binding } satisfies Expr\n : { Field: { base: { Variable: binding }, name: \"key\" } } satisfies Expr;\n const assignment = mode === \"MapGet\"\n ? { Field: { base: { Variable: binding }, name: \"value\" } } satisfies Expr\n : literal(true);\n return {\n statements: [\n { Let: { name: needleName, value: needle } },\n { Let: { name: result, value: mode === \"MapGet\" ? literal(null) : literal(false) } },\n { For: {\n binding,\n domain: { DerivedArray: {\n value: { Variable: owner.text },\n max: info.max,\n bound_source: info.boundSource ?? `${owner.text} static bound`,\n } },\n body: [{ If: {\n condition: { Binary: { op: \"SameValueZero\", left: candidate, right: { Variable: needleName } } },\n then_body: [{ Assign: { name: result, value: assignment } }],\n else_body: [],\n } }],\n } },\n ],\n expression: { Variable: result },\n };\n}\n\nexport function requirePrimitiveCollectionIdentity(\n node: ts.Expression,\n env: Environment,\n label: string,\n listElement = false,\n): void {\n // @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 Composite JS identity is refused; primitive keys use SameValueZero.\n const value = unwrapExpression(node);\n if (value.kind === ts.SyntaxKind.NullKeyword) return;\n let type = env.expressionTypes.get(contextualNodeKey(env.literalContext, value, env.sourceFile));\n if (listElement) type = type?.kind === \"list\" ? type.of : undefined;\n const required = type && requiredType(type);\n if (required && [\"null\", \"bool\", \"int\", \"decimal\", \"enum\", \"string\"].includes(required.kind)) return;\n refuse(\n env,\n \"E_OPAQUE\",\n node,\n `${label} must be primitive strings, numbers, booleans, or null; object identity cannot be preserved in bounded data IR`,\n \"select a primitive identity field before using this Map or Set operation\",\n );\n}\n", "import type { Expr } from \"../ir\";\n\nexport function upsertIdentityMatches(\n key: Expr,\n row: Expr,\n binding: (name: string) => Expr | undefined,\n): boolean | undefined {\n row = resolveRowContainer(row, binding, new Set());\n if (\"Object\" in row) {\n const id = row.Object.id;\n return id === undefined ? undefined : sameIr(key, id) && !expressionConsumesNewId(id);\n }\n if (!(\"Literal\" in row) || row.Literal === \"Null\" || typeof row.Literal !== \"object\") return undefined;\n const fields = \"Row\" in row.Literal ? row.Literal.Row : \"Map\" in row.Literal ? row.Literal.Map : undefined;\n const id = fields?.id;\n return id === undefined ? undefined : sameIr(key, { Literal: id });\n}\n\nfunction resolveRowContainer(\n expression: Expr,\n binding: (name: string) => Expr | undefined,\n seen: Set<string>,\n): Expr {\n if (!(\"Variable\" in expression) || seen.has(expression.Variable)) return expression;\n seen.add(expression.Variable);\n const value = binding(expression.Variable);\n return value === undefined ? expression : resolveRowContainer(value, binding, seen);\n}\n\nfunction expressionConsumesNewId(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(expressionConsumesNewId);\n if (!value || typeof value !== \"object\") return false;\n const item = value as Record<string, unknown>;\n return item.Input === \"NewId\" || Object.values(item).some(expressionConsumesNewId);\n}\n\nfunction sameIr(left: unknown, right: unknown): boolean {\n if (left === right) return true;\n if (Array.isArray(left) || Array.isArray(right)) {\n return Array.isArray(left) && Array.isArray(right) && left.length === right.length\n && left.every((item, index) => sameIr(item, right[index]));\n }\n if (!left || !right || typeof left !== \"object\" || typeof right !== \"object\") return false;\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const leftKeys = Object.keys(leftRecord).sort();\n const rightKeys = Object.keys(rightRecord).sort();\n return leftKeys.length === rightKeys.length\n && leftKeys.every((key, index) => key === rightKeys[index] && sameIr(leftRecord[key], rightRecord[key]));\n}\n", "import ts from \"typescript\";\nimport { diagnostic } from \"./diagnostics\";\nimport type { FrontendDiagnostic } from \"./ir\";\nimport type { TableInfo } from \"./compiler\";\nimport type { AuthoredType } from \"./authored-types\";\nimport {\n applyEdits,\n callName,\n containsCall,\n containsIncrement,\n expressionProperty,\n findAncestor,\n firstDescendantCall,\n hasAsyncModifier,\n isEffectFunction,\n isFunctionLike,\n isZero,\n memberName,\n nextStatement,\n numericLiteral,\n previousStatement,\n replaceNode,\n staticMemberPath,\n unwrapExpression,\n walk,\n} from \"./syntax\";\n\ntype PolicyModule = {\n sourceFile: ts.SourceFile;\n source: string;\n fileName: string;\n tables: Map<string, TableInfo>;\n};\n\nexport function mechanicalBoundRewrite(source: string): string {\n const sourceFile = ts.createSourceFile(\"bound-rewrite.ts\", source, ts.ScriptTarget.ES2022, true);\n let largest: { node: ts.Expression; value: number } | undefined;\n walk(sourceFile, (node) => {\n if (!ts.isCallExpression(node) || !callName(node).endsWith(\".scan\")) return;\n const options = node.arguments[2];\n const takeNode = options && ts.isObjectLiteralExpression(options) ? expressionProperty(options, \"take\") : undefined;\n const value = numericLiteral(takeNode);\n if (takeNode && value !== undefined && (!largest || value > largest.value)) largest = { node: takeNode, value };\n });\n return largest ? replaceNode(source, largest.node, String(Math.max(1, Math.floor(largest.value / 2)))) : source;\n}\n\nexport function findPolicyRefusals(module: PolicyModule, limit = 50): FrontendDiagnostic[] {\n const found: FrontendDiagnostic[] = [];\n const add = (item: FrontendDiagnostic) => {\n if (found.length < limit) found.push(item);\n };\n const visit = (node: ts.Node, currentFunction?: string) => {\n if (found.length >= limit) return;\n if (isFunctionLike(node) && isEffectFunction(node)) return;\n if (ts.isFunctionDeclaration(node) && node.name) currentFunction = node.name.text;\n\n if (ts.isWhileStatement(node)) {\n add(diagnostic(module, \"E_OPAQUE\", node, \"while loops have no static iteration bound\", rewriteWhile(module.source, node)));\n }\n if (ts.isAwaitExpression(node) || hasAsyncModifier(node)) {\n add(diagnostic(module, \"E_OPAQUE\", node, \"async/await is outside data programs\", module.source));\n }\n if (ts.isCallExpression(node)) {\n const name = callName(node);\n if (name === \"Date.now\" || (name === \"Date\" && node.arguments.length === 0)) {\n add(diagnostic(module, \"E_AMBIENT_TIME\", node, \"ambient time is not replay-stable\", rewriteAmbientTime(module.source, node)));\n }\n if ([\"Math.random\", \"fetch\", \"setTimeout\", \"eval\"].includes(name)) {\n add(diagnostic(module, \"E_OPAQUE\", node, `${name} is outside the deterministic subset`, module.source));\n }\n if (currentFunction && ts.isIdentifier(node.expression) && node.expression.text === currentFunction) {\n add(diagnostic(module, \"E_OPAQUE\", node, \"recursive helpers must use recurse with depth and fanout\", module.source));\n }\n }\n ts.forEachChild(node, (child) => visit(child, currentFunction));\n };\n visit(module.sourceFile);\n\n const reductions: ts.CallExpression[] = [];\n const scans: ts.CallExpression[] = [];\n const forLoops: ts.ForOfStatement[] = [];\n const structuralSorts: ts.ElementAccessExpression[] = [];\n walk(module.sourceFile, (node) => {\n if (ts.isCallExpression(node) && callName(node).endsWith(\".scan\")) scans.push(node);\n if (ts.isCallExpression(node) && [\"count\", \"reduce\"].includes(memberName(node.expression) ?? \"\")) reductions.push(node);\n if (ts.isForOfStatement(node)) forLoops.push(node);\n if (ts.isElementAccessExpression(node) && isZero(node.argumentExpression) && containsCall(node.expression, \".sort\")) structuralSorts.push(node);\n });\n\n for (const reduction of reductions) {\n if (found.length >= limit) break;\n const scan = firstDescendantCall(reduction.expression, \".scan\");\n if (!scan) continue;\n if (!scanTake(scan)) {\n add(diagnostic(module, \"E_UNBOUND_COUNT\", reduction, \"an exact reduction over a growing population has no static bound\", rewriteUnboundCount(module.source)));\n }\n if (scanIsPrivate(module, scan)) add(structuralDiagnostic(module, reduction, scan));\n }\n\n for (const access of structuralSorts) {\n if (found.length >= limit) break;\n const scan = firstDescendantCall(access.expression, \".scan\");\n if (scan && scanIsPrivate(module, scan)) add(structuralDiagnostic(module, access, scan));\n }\n\n for (const loop of forLoops) {\n if (found.length >= limit) break;\n const scan = firstDescendantCall(loop.expression, \".scan\");\n if (scan && scanIsPrivate(module, scan) && containsIncrement(loop.statement)) {\n add(structuralLoopDiagnostic(module, loop, scan));\n }\n if (containsCall(loop.expression, \".split\") && !boundedSplit(loop.expression)) {\n add(diagnostic(module, \"E_UNBOUND_LOOP\", loop.expression, \"split-derived loop cardinality is not declared\", rewriteSplit(module.source)));\n }\n }\n\n for (const scan of scans) {\n if (found.length >= limit) break;\n if (!scanTake(scan)) {\n add(diagnostic(\n module,\n \"E_UNBOUND_SCAN\",\n scan,\n \"scan requires a literal take or an argument with a declared maximum\",\n rewriteMapReturns(rewriteAllScans(module.sourceFile, module.source)),\n ));\n }\n }\n for (const item of boundRefusals(module, limit - found.length)) add(item);\n return found;\n}\n\nfunction structuralDiagnostic(module: PolicyModule, node: ts.Node, scan: ts.CallExpression): FrontendDiagnostic {\n const replacement = maintainedReplacement(module, scan);\n return diagnostic(\n module,\n \"E_STRUCTURAL_COUNT\",\n node,\n \"reduction would expose a fact about rows hidden by a non-tautologous rule\",\n replacement ? replaceNode(module.source, node, replacement) : module.source,\n );\n}\n\nfunction structuralLoopDiagnostic(module: PolicyModule, loop: ts.ForOfStatement, scan: ts.CallExpression): FrontendDiagnostic {\n const replacement = maintainedReplacement(module, scan) ?? \"null\";\n let start = loop.getStart(module.sourceFile);\n let end = loop.getEnd();\n const previous = previousStatement(module.sourceFile, loop);\n const next = nextStatement(module.sourceFile, loop);\n if (previous && ts.isVariableStatement(previous) && next && ts.isReturnStatement(next)) {\n start = previous.getStart(module.sourceFile);\n end = next.getEnd();\n }\n return diagnostic(\n module,\n \"E_STRUCTURAL_COUNT\",\n loop,\n \"loop tally would expose a structural count through caller visibility\",\n `${module.source.slice(0, start)}return ${replacement};${module.source.slice(end)}`,\n );\n}\n\nfunction maintainedReplacement(module: PolicyModule, scan: ts.CallExpression): string | undefined {\n const target = scan.arguments[0];\n const prefix = scan.arguments[1];\n if (!target || !prefix) return undefined;\n const table = tableReference(target, module.tables).table;\n const maintained = [...module.tables.entries()].find(([, info]) => {\n const source = info.maintainedFrom ? module.tables.get(info.maintainedFrom) : undefined;\n return source?.name === table;\n });\n if (!maintained) return undefined;\n const key = ts.isArrayLiteralExpression(prefix) && prefix.elements.length === 1\n ? prefix.elements[0]!.getText(module.sourceFile)\n : prefix.getText(module.sourceFile);\n return `db.get(${maintained[0]}, ${key})`;\n}\n\nfunction rewriteAllScans(sourceFile: ts.SourceFile, source: string): string {\n const edits: Array<{ start: number; end: number; text: string }> = [];\n walk(sourceFile, (node) => {\n if (!ts.isCallExpression(node) || !callName(node).endsWith(\".scan\") || scanTake(node)) return;\n if (node.arguments.length < 3) {\n edits.push({ start: node.arguments.end, end: node.arguments.end, text: \", { take: 50 }\" });\n return;\n }\n const options = node.arguments[2];\n if (options && ts.isObjectLiteralExpression(options)) {\n const at = options.properties.pos;\n edits.push({ start: at, end: at, text: \"take: 50, \" });\n }\n });\n return applyEdits(source, edits);\n}\n\nfunction rewriteUnboundCount(source: string): string {\n const sourceFile = ts.createSourceFile(\"rewrite.ts\", source, ts.ScriptTarget.ES2022, true);\n return rewriteAllScans(sourceFile, source).replace(/\\.count\\s*\\(\\s*\\)/g, \".countCapped()\");\n}\n\nfunction rewriteMapReturns(source: string): string {\n const sourceFile = ts.createSourceFile(\"rewrite-map.ts\", source, ts.ScriptTarget.ES2022, true);\n const edits: Array<{ start: number; end: number; text: string }> = [];\n walk(sourceFile, (node) => {\n if (!ts.isReturnStatement(node) || !node.expression || !ts.isCallExpression(node.expression)\n || !ts.isPropertyAccessExpression(node.expression.expression)\n || node.expression.expression.name.text !== \"map\") return;\n const callback = node.expression.arguments[0];\n if (!callback || !isFunctionLike(callback) || callback.parameters.length !== 1\n || !ts.isIdentifier(callback.parameters[0]!.name) || ts.isBlock(callback.body)) return;\n const binding = callback.parameters[0].name.text;\n const base = node.expression.expression.expression.getText(sourceFile);\n const value = callback.body.getText(sourceFile);\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n text: `let mapped = []; for (const ${binding} of ${base}) mapped.push(${value}); return mapped;`,\n });\n });\n return applyEdits(source, edits);\n}\n\nfunction rewriteSplit(source: string): string {\n return source.replace(/([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)\\.split\\(\\s*(['\"]) \\2\\s*\\)/g, \"mentionTokens($1)\");\n}\n\nfunction rewriteWhile(source: string, node: ts.WhileStatement): string {\n if (!ts.isBinaryExpression(node.expression)\n || node.expression.operatorToken.kind !== ts.SyntaxKind.LessThanToken\n || !ts.isIdentifier(node.expression.left)\n || numericLiteral(node.expression.right) === undefined) return source;\n const variable = node.expression.left.text;\n const end = numericLiteral(node.expression.right)!;\n const body = node.statement.getText().replace(new RegExp(`\\\\b${variable}\\\\+\\\\+\\\\s*;?`), \"\");\n return replaceNode(source, node, `for (const _ of range(0, ${end})) ${body}`);\n}\n\nfunction rewriteAmbientTime(source: string, node: ts.CallExpression): string {\n let rewritten = replaceNode(source, node, \"ctx.now()\");\n if (!/\\(\\{[^}]*\\bctx\\b[^}]*\\}\\)\\s*=>/.test(rewritten)) {\n rewritten = rewritten.replace(/\\(\\{([^}]*)\\}\\)\\s*=>/, (_match, bindings: string) => {\n const values = bindings.split(\",\").map((value) => value.trim()).filter(Boolean);\n const db = values.indexOf(\"db\");\n values.splice(db >= 0 ? db + 1 : 0, 0, \"ctx\");\n return `({ ${values.join(\", \")} }) =>`;\n });\n }\n return rewritten;\n}\n\nfunction boundRefusals(module: PolicyModule, limit: number): FrontendDiagnostic[] {\n const results: FrontendDiagnostic[] = [];\n const visitLoop = (loop: ts.ForOfStatement, factors: Array<{ value: number; node: ts.Expression; rowBytes: number }>) => {\n const scan = firstDescendantCall(loop.expression, \".scan\");\n const takeNode = scan && scan.arguments[2] && ts.isObjectLiteralExpression(scan.arguments[2])\n ? expressionProperty(scan.arguments[2], \"take\")\n : undefined;\n const take = numericLiteral(takeNode);\n const target = scan?.arguments[0];\n const rowBytes = target ? declaredRowMax(module.tables, tableReference(target, module.tables).table) : 1024;\n const next = take !== undefined && takeNode ? [...factors, { value: take, node: takeNode, rowBytes }] : factors;\n const product = next.reduce((total, factor) => total * factor.value, 1);\n if (product > 10_240 && takeNode && results.length < limit) {\n const largest = [...next].sort((a, b) => b.value - a.value)[0]!;\n const other = product / largest.value;\n // Use the refusing scans' actual declared serialized row maxima. One KiB\n // is only the missing-table fallback. The output ceiling is tighter than\n // closure for a returned collection, so the pasted rewrite clears both.\n const widestRow = Math.max(...next.map((factor) => factor.rowBytes));\n const outputRows = Math.floor(((1024 * 1024) - 2) / (widestRow + 1));\n const closureRows = Math.floor((4 * 1024 * 1024) / widestRow);\n const allowance = Math.min(10_240, outputRows, closureRows);\n const replacement = Math.max(1, Math.floor(allowance / (other + 4)));\n results.push(diagnostic(\n module,\n \"E_BOUND\",\n loop,\n `nested population product ${next.map((factor) => factor.value).join(\" \u00D7 \")} = ${product} exceeds 10240`,\n replaceNode(module.source, largest.node, String(replacement)),\n ));\n }\n const body = ts.isBlock(loop.statement) ? loop.statement.statements : [loop.statement];\n for (const statement of body) {\n walk(statement, (node) => {\n if (results.length < limit && ts.isForOfStatement(node) && node !== loop) visitLoop(node, next);\n });\n }\n };\n walk(module.sourceFile, (node) => {\n if (results.length < limit && ts.isForOfStatement(node) && !findAncestor(node, ts.isForOfStatement)) visitLoop(node, []);\n });\n return results;\n}\n\nfunction declaredRowMax(tables: Map<string, TableInfo>, tableName: string): number {\n const table = [...tables.values()].find((candidate) => candidate.name === tableName);\n if (!table?.columns) return 1024;\n return Object.entries(table.columns).reduce(\n (size, [name, column]) => size + name.length + 4 + declaredColumnMax(column),\n 10,\n );\n}\n\nfunction declaredColumnMax(column: AuthoredType): number {\n switch (column.kind) {\n case \"string\": return column.max === undefined ? 144 : column.max + 16;\n case \"principal\": return 144;\n case \"bytes\": return column.max * 2 + 16;\n case \"asset\": return column.asset === \"image\" ? 256 : 288;\n case \"int\":\n case \"decimal\": return 32;\n case \"bool\": return 16;\n case \"json\": return (column.max ?? 1024) + 16;\n case \"enum\": return Math.max(16, ...column.variants.map((variant) => variant.length + 16));\n case \"optional\": return Math.max(8, declaredColumnMax(column.of));\n case \"list\": return 2 + (column.max ?? 1) * (declaredColumnMax(column.of) + 1);\n case \"null\": return 8;\n case \"object\":\n case \"row\":\n case \"unknown\": return 1024;\n }\n}\n\nfunction scanIsPrivate(module: PolicyModule, scan: ts.CallExpression): boolean {\n const target = scan.arguments[0];\n if (!target) return false;\n const ref = tableReference(target, module.tables);\n const info = [...module.tables.values()].find((candidate) => candidate.name === ref.table);\n if (!info?.private) return false;\n const prefix = scan.arguments[1] && unwrapExpression(scan.arguments[1]);\n const columns = info.indexes?.[ref.index]?.columns;\n if (!prefix || !ts.isArrayLiteralExpression(prefix) || !columns || info.readRule === undefined) {\n return true;\n }\n const pinned = new Set(columns.slice(0, prefix.elements.length));\n return [...ruleFields(info.readRule)].some((field) => !pinned.has(field));\n}\n\nfunction ruleFields(rule: unknown, fields = new Set<string>()): Set<string> {\n if (!rule || typeof rule !== \"object\" || Array.isArray(rule)) return fields;\n const record = rule as Record<string, any>;\n const terms = record.Eq ?? record.Ne;\n if (Array.isArray(terms)) terms.forEach((term) => ruleTermField(term, fields));\n const exists = record.Exists;\n if (exists && Array.isArray(exists.key)) exists.key.forEach((term: unknown) => ruleTermField(term, fields));\n const children = record.And ?? record.Or;\n if (Array.isArray(children)) children.forEach((child) => ruleFields(child, fields));\n if (record.Not !== undefined) ruleFields(record.Not, fields);\n return fields;\n}\n\nfunction ruleTermField(term: unknown, fields: Set<string>): void {\n if (term && typeof term === \"object\" && !Array.isArray(term) && typeof (term as any).Field === \"string\") {\n fields.add((term as any).Field);\n }\n}\n\nfunction tableReference(node: ts.Expression, tables: Map<string, TableInfo>): { table: string; index: string } {\n const path = staticMemberPath(node);\n const direct = path && tables.get(path);\n if (direct) return { table: direct.name, index: direct.maintainedFrom ? \"byGroup\" : \"byId\" };\n const separator = path?.lastIndexOf(\".\") ?? -1;\n const owner = separator > 0 ? tables.get(path!.slice(0, separator)) : undefined;\n return owner\n ? { table: owner.name, index: path!.slice(separator + 1) }\n : { table: path ?? unwrapExpression(node).getText(), index: \"byId\" };\n}\n\nfunction scanTake(call: ts.CallExpression): number | \"arg\" | undefined {\n const options = call.arguments[2];\n if (!options || !ts.isObjectLiteralExpression(options)) return undefined;\n const take = expressionProperty(options, \"take\");\n if (!take) return undefined;\n return numericLiteral(take) ?? \"arg\";\n}\n\nfunction boundedSplit(expression: ts.Expression): boolean {\n const text = expression.getText();\n return /\\.split\\([^)]*\\)\\.slice\\(\\s*0\\s*,\\s*\\d+\\s*\\)/.test(text) || text.includes(\"mentionTokens(\");\n}\n", "import ts from \"typescript\";\nimport { expandArgumentObject } from \"./args\";\nimport { idType, isIdType, requiredType, sameDecimal, unknownType, type AuthoredType, type TableInfo } from \"./authored-types\";\nimport { diagnostic, type DiagnosticModule } from \"./diagnostics\";\nimport type { FrontendDiagnostic } from \"./ir\";\nimport { assignedBindings } from \"./lower/operation-context\";\nimport { callName, contextualNodeKey, expandedNumericLiteral, expansionContext, isFunctionLike, nonNullIdentifier, propertyName, replaceNode, staticMemberPath, unwrapCall, unwrapExpression } from \"./syntax\";\n\n// @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 Decimal target scales are compiler facts; the emitted value is integer minor units.\n\ntype FunctionLike = ts.FunctionDeclaration | ts.ArrowFunction | ts.FunctionExpression;\ntype TypeModule = DiagnosticModule & { tables: Map<string, TableInfo>; helpers?: Map<string, FunctionLike> };\ntype OperationComposite = \"args\" | \"ctx\" | \"db\";\ntype TypeBinding = { type: AuthoredType; operationComposite?: OperationComposite };\ntype TypeEnvironment = {\n variables: Map<string, TypeBinding>;\n constants: Map<string, ts.Expression>;\n args: Record<string, AuthoredType>;\n mutableBindings: Set<ts.Identifier>;\n memo: Map<ts.Expression, Map<string, AuthoredType>>;\n literalContext: string;\n};\n\nconst MAX_TYPE_ANALYSIS_DEPTH = 512;\nconst MAX_TYPE_ANALYSIS_NODES = 8192;\n\nexport type TypePlan = {\n diagnostics: FrontendDiagnostic[];\n literalValues: Map<string, number>;\n expressionTypes: Map<string, AuthoredType>;\n analysisLimitReached: boolean;\n};\n\nexport function analyzeOperationTypes(module: TypeModule, call: ts.CallExpression): TypePlan {\n const analyzer = new Analyzer(module, callName(call) === \"mutation\" ? \"Mutation\" : \"Query\", call);\n const argsObject = call.arguments[0] && unwrapExpression(call.arguments[0]);\n const args: Record<string, AuthoredType> = Object.create(null);\n if (argsObject && ts.isObjectLiteralExpression(argsObject)) {\n for (const property of expandArgumentObject(argsObject).entries) {\n args[property.name] = descriptorType(property.value);\n }\n }\n const handler = call.arguments[1];\n if (handler && isFunctionLike(handler)) {\n const env: TypeEnvironment = {\n variables: new Map(),\n constants: new Map(),\n args,\n mutableBindings: assignedBindings(handler),\n memo: new Map(),\n literalContext: \"operation\",\n };\n for (const parameter of handler.parameters) {\n for (const name of bindingNames(parameter.name)) setBinding(env, name, { type: unknownType });\n }\n for (const [composite, name] of Object.entries(operationCompositeBindings(handler))) {\n if (name) setBinding(env, name, { type: unknownType, operationComposite: composite as OperationComposite });\n }\n if (ts.isBlock(handler.body)) analyzer.statements(handler.body.statements, env);\n else analyzer.expression(handler.body, env);\n }\n return {\n diagnostics: analyzer.diagnostics,\n literalValues: analyzer.literalValues,\n expressionTypes: analyzer.expressionTypes,\n analysisLimitReached: analyzer.analysisLimitReached,\n };\n}\n\nclass Analyzer {\n readonly diagnostics: FrontendDiagnostic[] = [];\n readonly literalValues = new Map<string, number>();\n readonly expressionTypes = new Map<string, AuthoredType>();\n private readonly seen = new Set<string>();\n private readonly helperStack: string[] = [];\n private analysisVisits = 0;\n private analysisDepth = 0;\n analysisLimitReached = false;\n\n constructor(\n private readonly module: TypeModule,\n private readonly programKind: \"Query\" | \"Mutation\",\n private readonly operation: ts.CallExpression,\n ) {}\n\n statements(statements: readonly ts.Statement[], env: TypeEnvironment): void {\n for (const statement of statements) {\n this.statement(statement, env);\n }\n }\n\n private statement(statement: ts.Statement, env: TypeEnvironment): void {\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (!declaration.initializer) continue;\n const type = this.expression(declaration.initializer, env);\n const bindings = this.bindingTypes(declaration.name, declaration.initializer, type, env);\n for (const [name, bindingType] of bindings) {\n const identifier = namedBinding(declaration.name, name);\n const mutable = identifier !== undefined && env.mutableBindings.has(identifier);\n const binding = ts.isIdentifier(declaration.name)\n ? this.binding(declaration.initializer, env, mutable ? unknownType : bindingType)\n : { type: mutable ? unknownType : bindingType };\n setBinding(\n env,\n name,\n binding,\n !mutable ? declaration.initializer : undefined,\n );\n }\n }\n return;\n }\n if (ts.isExpressionStatement(statement)) {\n this.expression(statement.expression, env);\n return;\n }\n if (ts.isReturnStatement(statement) && statement.expression) {\n this.expression(statement.expression, env);\n return;\n }\n if (ts.isIfStatement(statement)) {\n this.expression(statement.expression, env);\n const thenEnv = cloneEnv(env);\n const narrowed = nonNullIdentifier(statement.expression);\n if (narrowed) {\n const binding = thenEnv.variables.get(narrowed);\n if (binding) binding.type = requiredType(binding.type);\n thenEnv.constants.delete(narrowed);\n }\n this.controlled(statement.thenStatement, thenEnv);\n if (statement.elseStatement) this.controlled(statement.elseStatement, cloneEnv(env));\n return;\n }\n if (ts.isForOfStatement(statement)) {\n const domain = this.expression(statement.expression, env);\n const loop = cloneEnv(env);\n if (ts.isVariableDeclarationList(statement.initializer)) {\n for (const declaration of statement.initializer.declarations) {\n for (const name of bindingNames(declaration.name)) {\n setBinding(loop, name, { type: domain.kind === \"list\" ? domain.of : unknownType });\n }\n }\n }\n this.controlled(statement.statement, loop);\n return;\n }\n if (ts.isBlock(statement)) this.statements(statement.statements, cloneEnv(env));\n }\n\n private controlled(statement: ts.Statement, env: TypeEnvironment): void {\n if (ts.isBlock(statement)) this.statements(statement.statements, env);\n else this.statement(statement, env);\n }\n\n expression(node: ts.Expression, env: TypeEnvironment, expected?: AuthoredType, quietFraction = false): AuthoredType {\n const value = unwrapExpression(node);\n const target = expected && requiredType(expected);\n const memoKey = `${quietFraction ? \"quiet\" : \"loud\"}:${JSON.stringify(target ?? null)}`;\n const cached = env.memo.get(value)?.get(memoKey);\n const expressionKey = contextualNodeKey(env.literalContext, value, this.module.sourceFile);\n if (cached) {\n this.expressionTypes.set(expressionKey, cached);\n return cached;\n }\n if (this.analysisLimitReached) return unknownType;\n if (this.analysisDepth >= MAX_TYPE_ANALYSIS_DEPTH) return this.analysisLimit(value);\n if (this.analysisVisits >= MAX_TYPE_ANALYSIS_NODES) return this.analysisLimit(value);\n this.analysisVisits += 1;\n this.analysisDepth += 1;\n let result: AuthoredType;\n try {\n result = this.expressionInner(value, env, target, quietFraction);\n } finally {\n this.analysisDepth -= 1;\n }\n if (isIdType(target) && !identityValueMatches(result) && result.kind !== \"unknown\" && result.kind !== \"json\"\n && isRuntimeValidatedIdentitySink(node)\n && !(expected?.kind === \"optional\" && result.kind === \"null\")) {\n this.add(\n \"E_ARGS_ID_SCALAR\",\n value,\n `an Id position requires an Id scalar, not ${authoredTypeName(result)}`,\n this.idScalarRewrite(value, env),\n );\n }\n const entries = env.memo.get(value) ?? new Map<string, AuthoredType>();\n entries.set(memoKey, result);\n env.memo.set(value, entries);\n this.expressionTypes.set(expressionKey, result);\n return result;\n }\n\n private expressionInner(\n value: ts.Expression,\n env: TypeEnvironment,\n target: AuthoredType | undefined,\n quietFraction: boolean,\n ): AuthoredType {\n if (ts.isNumericLiteral(value)) return this.numeric(value, env, target, quietFraction);\n if (ts.isStringLiteralLike(value)) {\n if (target?.kind === \"enum\" && !target.variants.includes(value.text)) this.enumVariant(value, target);\n if (target?.kind === \"string\" && target.max !== undefined && [...value.text].length > target.max) {\n this.add(\n \"E_ARGS_TYPE\",\n value,\n `text literal has ${[...value.text].length} Unicode scalars but text(${target.max}) allows at most ${target.max}`,\n replaceNode(this.module.source, value, JSON.stringify([...value.text].slice(0, target.max).join(\"\"))),\n );\n }\n return target?.kind === \"enum\" || (target?.kind === \"string\" && (!isIdType(target) || value.text.length > 0))\n ? target\n : { kind: \"string\" };\n }\n if (value.kind === ts.SyntaxKind.TrueKeyword || value.kind === ts.SyntaxKind.FalseKeyword) return { kind: \"bool\" };\n if (value.kind === ts.SyntaxKind.NullKeyword) return { kind: \"null\" };\n if (ts.isIdentifier(value)) {\n const constant = target && env.constants.get(value.text);\n const contextual = constant && !(isIdType(target) && opaqueScalarInitializer(constant));\n return contextual ? this.expression(constant, env, target) : env.variables.get(value.text)?.type ?? unknownType;\n }\n if (ts.isPrefixUnaryExpression(value)) {\n return this.expression(value.operand, env, target, quietFraction);\n }\n if (ts.isPropertyAccessExpression(value)) {\n const composite = this.operationComposite(value.expression, env);\n if (composite === \"args\") return requiredType(env.args[value.name.text]);\n if (composite === \"ctx\") {\n if (value.name.text === \"viewer\") return { kind: \"principal\" };\n if ([\"readTime\", \"commitTime\"].includes(value.name.text)) return { kind: \"int\" };\n }\n const base = this.expression(value.expression, env, undefined, true);\n if (base.kind === \"row\") return this.table(base.table)?.columns?.[value.name.text] ?? unknownType;\n if (base.kind === \"object\") return base.fields?.[value.name.text] ?? unknownType;\n if (base.kind === \"asset\") {\n const field = assetFieldType(base.asset, value.name.text);\n if (field) return field;\n const available = base.asset === \"image\" ? \"id, width, height\" : \"id, width, height, duration\";\n const replacement = `${value.expression.getText(this.module.sourceFile)}.${base.asset === \"video\" ? \"duration\" : \"width\"}`;\n this.add(\n \"E_ARGS_TYPE\",\n value,\n `${base.asset} asset has no field ${value.name.text}; available fields are ${available}`,\n replaceNode(this.module.source, value, replacement),\n );\n return unknownType;\n }\n if ((base.kind === \"list\" || base.kind === \"string\") && value.name.text === \"length\") return { kind: \"int\" };\n return unknownType;\n }\n if (ts.isNoSubstitutionTemplateLiteral(value)) return { kind: \"string\" };\n if (ts.isTemplateExpression(value)) {\n const expressions = value.templateSpans.map((span) => span.expression);\n const types = expressions.map((expression) => this.expression(expression, env));\n // Id-derived text is runtime-green in Text/List/Json positions (Concat with a String\n // operand yields String); only an Id/Ref target makes it a certify-time refusal.\n if (types.some(identityScalar) && isIdType(requiredType(target)) && isRuntimeValidatedIdentitySink(value)) {\n this.add(\n \"E_ARGS_ID_TEXT\",\n value,\n \"Id scalars cannot be interpolated into text; keep identity values structurally separate\",\n this.idTextRewrite(value, target, expressions, types),\n );\n return unknownType;\n }\n return { kind: \"string\" };\n }\n if (ts.isArrayLiteralExpression(value)) {\n const elementTarget = target?.kind === \"list\" ? target.of : undefined;\n const values = value.elements.map((item) => this.expression(item, env, elementTarget));\n return { kind: \"list\", of: commonType(values), max: values.length };\n }\n if (ts.isObjectLiteralExpression(value)) {\n const row = target?.kind === \"row\" ? this.table(target.table) : undefined;\n const fields: Record<string, AuthoredType> = Object.create(null);\n for (const property of value.properties) {\n if (ts.isSpreadAssignment(property)) {\n const spread = this.expression(property.expression, env);\n if (spread.kind === \"object\" && spread.fields) Object.assign(fields, spread.fields);\n else for (const name of Object.keys(fields)) delete fields[name];\n continue;\n }\n if (ts.isShorthandPropertyAssignment(property)) {\n fields[property.name.text] = this.expression(property.name, env, row?.columns?.[property.name.text]);\n continue;\n }\n if (!ts.isPropertyAssignment(property)) continue;\n const name = propertyName(property.name);\n const field = name ? row?.columns?.[name] : undefined;\n const type = this.expression(property.initializer, env, field);\n if (name) fields[name] = type;\n }\n return target ?? { kind: \"object\", fields };\n }\n if (ts.isConditionalExpression(value)) {\n this.expression(value.condition, env);\n const left = this.expression(value.whenTrue, env, target);\n const right = this.expression(value.whenFalse, env, target);\n return commonType([left, right]);\n }\n if (ts.isBinaryExpression(value)) return this.binary(value, env, target);\n if (ts.isCallExpression(value)) return this.call(value, env, target);\n if (ts.isNewExpression(value)) {\n for (const argument of value.arguments ?? []) this.expression(argument, env);\n return { kind: \"object\" };\n }\n if (ts.isArrowFunction(value) || ts.isFunctionExpression(value)) {\n const nested = cloneEnv(env);\n for (const parameter of value.parameters) {\n for (const name of bindingNames(parameter.name)) setBinding(nested, name, { type: unknownType });\n }\n if (ts.isBlock(value.body)) this.statements(value.body.statements, nested);\n else this.expression(value.body, nested, target);\n }\n return target ?? unknownType;\n }\n\n private analysisLimit(node: ts.Expression): AuthoredType {\n if (!this.analysisLimitReached) {\n this.analysisLimitReached = true;\n this.add(\n \"E_OPAQUE\",\n node,\n `type analysis is limited per operation to ${MAX_TYPE_ANALYSIS_DEPTH} nested expressions and ${MAX_TYPE_ANALYSIS_NODES} contextual expression visits; reduce this operation below those bounds or split it into multiple operations (naming values inside the same operation does not reset the bounds)`,\n replaceNode(\n this.module.source,\n node,\n `__snapback2_type_analysis_limit_${MAX_TYPE_ANALYSIS_DEPTH}_depth_${MAX_TYPE_ANALYSIS_NODES}_visits_per_operation__()`,\n ),\n );\n }\n return unknownType;\n }\n\n private numeric(\n node: ts.NumericLiteral,\n env: TypeEnvironment,\n expected: AuthoredType | undefined,\n quiet: boolean,\n ): AuthoredType {\n const digits = fractionalDigits(node.text);\n if (expected?.kind === \"decimal\") {\n if (digits > expected.scale) {\n this.add(\n \"E_DECIMAL_SCALE\",\n node,\n `${digits} fractional digits, scale ${expected.scale}; ${decimalName(expected)} cannot represent ${node.text}`,\n replaceNode(this.module.source, node, `decimal(${node.text}, ${expected.scale})`),\n );\n return expected;\n }\n const minor = scaledInteger(node.text, expected.scale);\n if (minor === undefined) {\n this.add(\"E_DECIMAL_SCALE\", node, `${node.text} at scale ${expected.scale} is outside the safe integer wire range`,\n replaceNode(this.module.source, node, `decimal(${node.text}, ${expected.scale})`));\n } else {\n this.literalValues.set(contextualNodeKey(env.literalContext, node, this.module.sourceFile), minor);\n }\n return expected;\n }\n if (digits === 0) return { kind: \"int\" };\n if (!quiet) {\n this.add(\"E_DECIMAL_SCALE\", node, `fractional literal ${node.text} has ${digits} fractional digits but no Decimal scale`,\n replaceNode(this.module.source, node, `decimal(${node.text}, ${digits})`));\n }\n return unknownType;\n }\n\n private binary(node: ts.BinaryExpression, env: TypeEnvironment, expected?: AuthoredType): AuthoredType {\n const operator = node.operatorToken.kind;\n if (operator === ts.SyntaxKind.PlusToken) {\n const operands = flattenPlus(node);\n const types = operands.map((operand) => this.expression(operand, env, undefined, true));\n if (types.some(identityScalar)) {\n this.add(\n \"E_ARGS_ID_TEXT\",\n node,\n \"Id scalars cannot be concatenated or added into text; keep identity values structurally separate\",\n this.idTextRewrite(node, expected, operands, types),\n );\n return unknownType;\n }\n }\n let left = this.expression(node.left, env, undefined, true);\n let right = this.expression(node.right, env, undefined, true);\n const equality = [\n ts.SyntaxKind.EqualsEqualsToken,\n ts.SyntaxKind.EqualsEqualsEqualsToken,\n ts.SyntaxKind.ExclamationEqualsToken,\n ts.SyntaxKind.ExclamationEqualsEqualsToken,\n ].includes(operator);\n const retargetIdentity = equality && identityScalar(left) !== identityScalar(right);\n if (this.analysisLimitReached) return unknownType;\n if (operator === ts.SyntaxKind.AsteriskToken) {\n if (left.kind === \"decimal\") right = this.expression(node.right, env);\n else if (right.kind === \"decimal\") left = this.expression(node.left, env);\n else {\n left = this.expression(node.left, env);\n right = this.expression(node.right, env);\n }\n } else if (retargetIdentity) {\n if (identityScalar(left)) {\n right = this.expression(node.right, env, idType);\n } else {\n left = this.expression(node.left, env, idType);\n }\n } else if (left.kind === \"decimal\") right = this.expression(node.right, env, left);\n else if (right.kind === \"decimal\") left = this.expression(node.left, env, right);\n else if (left.kind === \"enum\") right = this.expression(node.right, env, left);\n else if (right.kind === \"enum\") left = this.expression(node.left, env, right);\n else {\n left = this.expression(node.left, env, expected);\n right = this.expression(node.right, env, expected);\n }\n if (this.analysisLimitReached) return unknownType;\n if (operator === ts.SyntaxKind.QuestionQuestionToken) {\n if (left.kind === \"enum\") right = this.expression(node.right, env, left);\n if (right.kind === \"enum\") left = this.expression(node.left, env, right);\n if (left.kind === \"string\") right = this.expression(node.right, env, left);\n if (right.kind === \"string\") left = this.expression(node.left, env, right);\n if (left.kind === \"unknown\") return unknownType;\n return left.kind === \"null\" ? right : left;\n }\n const comparison = [\n ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken, ts.SyntaxKind.GreaterThanToken,\n ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken,\n ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken,\n ].includes(operator);\n if (left.kind === \"enum\" && ts.isStringLiteralLike(unwrapExpression(node.right))) this.enumVariant(unwrapExpression(node.right) as ts.StringLiteralLike, left);\n if (right.kind === \"enum\" && ts.isStringLiteralLike(unwrapExpression(node.left))) this.enumVariant(unwrapExpression(node.left) as ts.StringLiteralLike, right);\n if (left.kind === \"decimal\" || right.kind === \"decimal\") {\n return this.decimalBinary(node, left, right, comparison);\n }\n return comparison ? { kind: \"bool\" } : commonType([left, right]);\n }\n\n private decimalBinary(node: ts.BinaryExpression, left: AuthoredType, right: AuthoredType, comparison: boolean): AuthoredType {\n const operator = node.operatorToken.kind;\n const decimal = left.kind === \"decimal\" ? left : right.kind === \"decimal\" ? right : unknownType;\n if (comparison && (left.kind === \"null\" || right.kind === \"null\")) return { kind: \"bool\" };\n const zero = isIntegerZero(node.left) || isIntegerZero(node.right);\n const same = left.kind === \"decimal\" && right.kind === \"decimal\" && sameDecimal(left, right);\n const addCompare = comparison || operator === ts.SyntaxKind.PlusToken || operator === ts.SyntaxKind.MinusToken;\n if (addCompare && (same || zero)) return comparison ? { kind: \"bool\" } : decimal;\n if (operator === ts.SyntaxKind.AsteriskToken\n && ((left.kind === \"decimal\" && right.kind === \"int\") || (right.kind === \"decimal\" && left.kind === \"int\"))) return decimal;\n this.decimalMismatch(node, left, right, operatorText(operator));\n return comparison ? { kind: \"bool\" } : decimal;\n }\n\n private call(call: ts.CallExpression, env: TypeEnvironment, expected?: AuthoredType): AuthoredType {\n const name = callName(call);\n if (ts.isPropertyAccessExpression(call.expression)\n && this.operationComposite(call.expression.expression, env) === \"ctx\") {\n if (call.expression.name.text === \"newId\") return idType;\n if (call.expression.name.text === \"now\") return { kind: \"int\" };\n }\n if (ts.isIdentifier(call.expression)) {\n const helper = env.variables.has(call.expression.text) ? undefined : this.module.helpers?.get(call.expression.text);\n if (helper) {\n if (this.helperStack.includes(call.expression.text) || this.helperStack.length >= 128) return unknownType;\n this.helperStack.push(call.expression.text);\n try {\n const nested = cloneEnv(env);\n nested.literalContext = expansionContext(env.literalContext, call, this.module.sourceFile);\n helper.parameters.forEach((parameter, index) => {\n const type = call.arguments[index] ? this.expression(call.arguments[index]!, env) : unknownType;\n const binding = call.arguments[index]\n ? this.binding(call.arguments[index]!, env, type)\n : { type: unknownType };\n for (const parameterName of bindingNames(parameter.name)) setBinding(nested, parameterName, binding);\n });\n if (helper.body && ts.isBlock(helper.body)) {\n const returned = helper.body.statements.find(ts.isReturnStatement)?.expression;\n return returned ? this.expression(returned, nested, expected) : unknownType;\n }\n if (helper.body) return this.expression(helper.body, nested, expected);\n } finally {\n this.helperStack.pop();\n }\n }\n }\n if (name === \"decimal\" && !env.variables.has(name)) {\n const scaleNode = call.arguments[1] && unwrapExpression(call.arguments[1]);\n const scale = scaleNode && ts.isNumericLiteral(scaleNode) ? Number(scaleNode.text) : undefined;\n const input = call.arguments[0];\n const type: AuthoredType = Number.isInteger(scale) && scale! >= 0 && scale! <= 12\n ? { kind: \"decimal\", scale: scale! }\n : unknownType;\n if (!input || type.kind !== \"decimal\" || !numericExpression(input)) {\n this.add(\"E_DECIMAL_SCALE\", call, \"decimal(value, scale) requires a numeric literal and an integer scale from 0 through 12\", \"use decimal(9.99, 2)\");\n } else {\n this.expression(input, env, type);\n }\n return type;\n }\n if (ts.isPropertyAccessExpression(call.expression)\n && this.operationComposite(call.expression.expression, env) === \"db\") {\n const method = call.expression.name.text;\n const target = call.arguments[0];\n const table = target && this.tableReference(target);\n if (method === \"insert\" || method === \"update\" || method === \"upsert\") {\n const row = call.arguments[method === \"insert\" ? 1 : 2];\n if (target) this.expression(target, env);\n if (call.arguments[1] && method !== \"insert\") {\n this.expression(call.arguments[1], env, table?.columns?.id ?? idType);\n }\n if (row && table) {\n const rowType: AuthoredType = { kind: \"row\", table: table.name };\n if (isFunctionLike(row)) this.callback(row, env, rowType, rowType);\n else this.expression(row, env, rowType);\n }\n return method === \"insert\" && table ? { kind: \"row\", table: table.name } : unknownType;\n }\n if ((method === \"get\" || method === \"scan\") && table) {\n if (target) this.expression(target, env);\n const indexTypes = this.indexTypes(target, table);\n const key = call.arguments[1];\n if (key) this.key(key, env, indexTypes);\n if (method === \"scan\") {\n const options = call.arguments[2];\n if (options) this.scanOptions(options, env, indexTypes.slice(this.prefixArity(key, env)));\n }\n const row: AuthoredType = { kind: \"row\", table: table.name };\n return method === \"scan\" ? { kind: \"list\", of: row } : row;\n }\n }\n if ((name === \"min\" || name === \"max\") && !env.variables.has(name) && call.arguments.length > 0) {\n let types = call.arguments.map((item) => this.expression(item, env, undefined, true));\n const decimal = types.find((item) => item.kind === \"decimal\");\n if (decimal?.kind === \"decimal\") types = call.arguments.map((item) => this.expression(item, env, decimal));\n const valid = types.every((item, index) => sameDecimal(decimal ?? unknownType, item) || isIntegerZero(call.arguments[index]!));\n if (decimal?.kind === \"decimal\" && !valid) this.decimalMismatch(call, types[0] ?? unknownType, types[1] ?? unknownType, name);\n return decimal ?? commonType(types);\n }\n if (name === \"divmod\" && !env.variables.has(name) && call.arguments.length === 2) {\n const numeratorNode = unwrapExpression(call.arguments[0]!);\n if (ts.isBinaryExpression(numeratorNode)\n && numeratorNode.operatorToken.kind === ts.SyntaxKind.AsteriskToken) {\n const left = this.expression(numeratorNode.left, env, undefined, true);\n const right = this.expression(numeratorNode.right, env, undefined, true);\n if (left.kind === \"decimal\" && right.kind === \"decimal\") {\n // @ref LLP 1004#money-and-decimal-worked-out-2026-09-03 \u2014 the only branded \u00D7 branded lowering is an exact product divided by the dropped scale.\n const divisorNode = call.arguments[1]!;\n this.expression(divisorNode, env, { kind: \"int\" });\n if (left.currency && right.currency) {\n this.add(\n \"E_DECIMAL_SCALE\",\n numeratorNode,\n \"money multiplied by money has no currency-squared value\",\n \"multiply the money value by a decimal rate or an int\",\n );\n }\n const dropped = left.currency ? right : right.currency ? left : right;\n const surviving = left.currency ? left : right.currency ? right : left;\n const expectedDivisor = 10 ** dropped.scale;\n if (integerLiteralValue(divisorNode) !== expectedDivisor) {\n this.add(\n \"E_DECIMAL_SCALE\",\n divisorNode,\n `branded multiplication must divide by 10^${dropped.scale} (${expectedDivisor}) to drop ${decimalName(dropped)}`,\n replaceNode(this.module.source, divisorNode, String(expectedDivisor)),\n );\n }\n return { kind: \"object\", fields: { quotient: surviving, remainder: surviving } };\n }\n }\n const numerator = this.expression(call.arguments[0]!, env, undefined, true);\n this.expression(call.arguments[1]!, env, { kind: \"int\" });\n const carried = requiredType(numerator);\n if (carried.kind === \"int\" || carried.kind === \"decimal\") {\n return { kind: \"object\", fields: { quotient: carried, remainder: carried } };\n }\n return unknownType;\n }\n if (name === \"deterministicShare\" && !env.variables.has(name) && call.arguments.length === 3) {\n const amount = this.expression(call.arguments[0]!, env, undefined, true);\n this.expression(call.arguments[1]!, env);\n this.expression(call.arguments[2]!, env);\n return amount;\n }\n if (name === \"concat\" && !env.variables.has(name)) {\n const types = call.arguments.map((argument) => this.expression(argument, env, undefined, true));\n if (types.some(identityScalar)\n && types.some((type) => requiredType(type).kind === \"string\" && !isIdType(requiredType(type)))\n && isIdType(requiredType(expected))\n && isRuntimeValidatedIdentitySink(call)) {\n this.add(\n \"E_ARGS_ID_TEXT\",\n call,\n \"Id scalars cannot be concatenated into text; keep identity values structurally separate\",\n this.idTextRewrite(call, expected, [...call.arguments], types),\n );\n return unknownType;\n }\n if (types.length > 0 && types.every(identityScalar)) return idType;\n if (types.every((type) => requiredType(type).kind === \"list\")) {\n const lists = types.map(requiredType) as Array<Extract<AuthoredType, { kind: \"list\" }>>;\n return { kind: \"list\", of: commonType(lists.map((type) => type.of)) };\n }\n return types.some((type) => requiredType(type).kind === \"string\")\n ? { kind: \"string\" }\n : commonType(types);\n }\n if (name === \"String\" && !env.variables.has(name) && call.arguments.length === 1) {\n const argument = call.arguments[0]!;\n const type = this.expression(argument, env, undefined, true);\n if (identityScalar(type) && isIdType(requiredType(expected)) && isRuntimeValidatedIdentitySink(call)) {\n this.add(\n \"E_ARGS_ID_TEXT\",\n call,\n \"String(id) would erase the Id's nominal domain; keep the identity value separate\",\n this.idTextRewrite(call, expected, [argument], [type]),\n );\n return unknownType;\n }\n return { kind: \"string\" };\n }\n if (ts.isPropertyAccessExpression(call.expression)) {\n const owner = this.expression(call.expression.expression, env);\n const method = call.expression.name.text;\n if (owner.kind === \"list\" && [\"map\", \"filter\", \"some\"].includes(method)) {\n const callback = call.arguments[0];\n const result = callback && isFunctionLike(callback) ? this.callback(callback, env, owner.of) : unknownType;\n return method === \"map\" ? { kind: \"list\", of: result } : method === \"filter\" ? owner : { kind: \"bool\" };\n }\n }\n for (const argument of call.arguments) this.expression(argument, env);\n return expected ?? unknownType;\n }\n\n private callback(node: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration, env: TypeEnvironment, parameter: AuthoredType, expected?: AuthoredType): AuthoredType {\n const nested = cloneEnv(env);\n for (const item of node.parameters) {\n for (const name of bindingNames(item.name)) setBinding(nested, name, { type: parameter });\n }\n if (!node.body) return unknownType;\n if (ts.isBlock(node.body)) {\n this.statements(node.body.statements, nested);\n return unknownType;\n }\n return this.expression(node.body, nested, expected);\n }\n\n private binding(node: ts.Expression, env: TypeEnvironment, type: AuthoredType): TypeBinding {\n const value = unwrapExpression(node);\n return ts.isIdentifier(value) ? { ...env.variables.get(value.text), type } : { type };\n }\n\n private operationComposite(node: ts.Expression, env: TypeEnvironment): OperationComposite | undefined {\n const value = unwrapExpression(node);\n return ts.isIdentifier(value) ? env.variables.get(value.text)?.operationComposite : undefined;\n }\n\n private tableReference(node: ts.Expression): TableInfo | undefined {\n const path = staticMemberPath(node);\n if (!path) return undefined;\n const direct = this.module.tables.get(path);\n if (direct) return direct;\n const separator = path.lastIndexOf(\".\");\n return separator > 0 ? this.module.tables.get(path.slice(0, separator)) : undefined;\n }\n\n private table(name: string): TableInfo | undefined {\n return [...this.module.tables.values()].find((item) => item.name === name);\n }\n\n private indexTypes(node: ts.Expression | undefined, table: TableInfo): AuthoredType[] {\n const path = node && staticMemberPath(node);\n if (!path) return [];\n const direct = this.module.tables.get(path);\n if (direct) return direct.indexes?.byId?.types ?? [idType];\n const separator = path.lastIndexOf(\".\");\n return separator > 0 ? table.indexes?.[path.slice(separator + 1)]?.types ?? [] : [];\n }\n\n private key(node: ts.Expression, env: TypeEnvironment, types: AuthoredType[]): void {\n const value = unwrapExpression(node);\n if (ts.isArrayLiteralExpression(value)) {\n value.elements.forEach((item, index) => this.expression(item, env, types[index]));\n } else {\n this.expression(\n value,\n env,\n types.length === 1 ? types[0] : { kind: \"list\", of: commonType(types), max: types.length },\n );\n }\n }\n\n private scanOptions(node: ts.Expression, env: TypeEnvironment, cursorTypes: AuthoredType[]): void {\n const value = unwrapExpression(node);\n if (!ts.isObjectLiteralExpression(value)) {\n this.expression(value, env);\n return;\n }\n for (const property of value.properties) {\n if (!ts.isPropertyAssignment(property)) continue;\n const name = propertyName(property.name);\n if (name === \"after\" || name === \"before\") {\n const cursor = unwrapExpression(property.initializer);\n if (ts.isArrayLiteralExpression(cursor)) {\n cursor.elements.forEach((element, index) => this.expression(element, env, cursorTypes[index]));\n } else {\n this.expression(cursor, env, cursorTypes.length === 1 ? cursorTypes[0] : undefined);\n }\n } else if (name === \"range\") {\n const range = unwrapExpression(property.initializer);\n if (!ts.isObjectLiteralExpression(range)) this.expression(range, env);\n else for (const bound of range.properties) {\n if (ts.isPropertyAssignment(bound)) this.expression(bound.initializer, env, cursorTypes[0]);\n }\n } else {\n this.expression(property.initializer, env);\n }\n }\n }\n\n private enumVariant(node: ts.StringLiteralLike, type: Extract<AuthoredType, { kind: \"enum\" }>): void {\n if (type.variants.includes(node.text)) return;\n this.add(\n \"E_ENUM_VARIANT\",\n node,\n `${JSON.stringify(node.text)} is not an enum variant; expected ${type.variants.map((item) => JSON.stringify(item)).join(\", \")}`,\n replaceNode(this.module.source, node, JSON.stringify(type.variants[0] ?? \"\")),\n );\n }\n\n private decimalMismatch(node: ts.Node, left: AuthoredType, right: AuthoredType, operator: string): void {\n this.add(\n \"E_DECIMAL_SCALE\",\n node,\n `${operator} requires equal Decimal scales (or literal 0); received ${decimalName(left)} and ${decimalName(right)}`,\n `make both operands ${left.kind === \"decimal\" ? decimalName(left) : right.kind === \"decimal\" ? decimalName(right) : \"the same Decimal<S>\"}`,\n );\n }\n\n private idScalarRewrite(node: ts.Expression, env: TypeEnvironment): string {\n if (this.programKind === \"Mutation\" && isInsertIdSink(node)) {\n const ctx = [...env.variables].find(([, binding]) => binding.operationComposite === \"ctx\")?.[0];\n if (ctx) return replaceNode(this.module.source, node, insertIdReplacement(node, `${ctx}.newId()`));\n\n const handler = enclosingFunction(node);\n const parameter = handler?.parameters[0]?.name;\n if (parameter && ts.isObjectBindingPattern(parameter)) {\n const binding = uniqueBindingName(this.module.source, \"snapbackCtx\");\n const text = parameter.getText(this.module.sourceFile);\n const inserted = `${text.slice(0, -1).trimEnd()}${parameter.elements.length === 0 ? \" \" : \", \"}ctx: ${binding} }`;\n return replaceSourceRanges(this.module.source, [\n { start: parameter.getStart(this.module.sourceFile), end: parameter.getEnd(), value: inserted },\n { start: node.getStart(this.module.sourceFile), end: node.getEnd(), value: insertIdReplacement(node, `${binding}.newId()`) },\n ]);\n }\n }\n\n const args = [...env.variables].find(([, binding]) => binding.operationComposite === \"args\")?.[0];\n const directArgument = directArgsProperty(node, args);\n const argsNode = this.operation.arguments[0];\n const argsObject = argsNode ? unwrapExpression(argsNode) : undefined;\n if (directArgument && argsObject && ts.isObjectLiteralExpression(argsObject)) {\n const property = argsObject.properties.find((candidate) =>\n ts.isPropertyAssignment(candidate) && propertyName(candidate.name) === directArgument);\n if (property && ts.isPropertyAssignment(property)) {\n return replaceNode(this.module.source, property.initializer, \"t.id()\");\n }\n }\n\n const idArgument = Object.entries(env.args).find(([, type]) => isIdType(requiredType(type)))?.[0];\n if (args && idArgument) return replaceNode(this.module.source, node, `${args}.${idArgument}`);\n\n if (argsObject && ts.isObjectLiteralExpression(argsObject)) {\n const argument = uniqueArgumentName(env.args, \"id\");\n const argsText = argsObject.getText(this.module.sourceFile);\n const rewrittenArgs = `${argsText.slice(0, -1).trimEnd()}${argsObject.properties.length === 0 ? \" \" : \", \"}${argument}: t.id() }`;\n const ranges = [\n { start: argsObject.getStart(this.module.sourceFile), end: argsObject.getEnd(), value: rewrittenArgs },\n ];\n let argsBinding = args;\n if (!argsBinding) {\n const parameter = enclosingFunction(node)?.parameters[0]?.name;\n if (parameter && ts.isObjectBindingPattern(parameter)) {\n argsBinding = uniqueBindingName(this.module.source, \"snapbackArgs\");\n const text = parameter.getText(this.module.sourceFile);\n ranges.push({\n start: parameter.getStart(this.module.sourceFile),\n end: parameter.getEnd(),\n value: `${text.slice(0, -1).trimEnd()}${parameter.elements.length === 0 ? \" \" : \", \"}args: ${argsBinding} }`,\n });\n }\n }\n if (argsBinding) {\n ranges.push({ start: node.getStart(this.module.sourceFile), end: node.getEnd(), value: `${argsBinding}.${argument}` });\n return replaceSourceRanges(this.module.source, ranges);\n }\n }\n return this.module.source;\n }\n\n private bindingTypes(\n name: ts.BindingName,\n initializer: ts.Expression,\n overall: AuthoredType,\n env: TypeEnvironment,\n ): Map<string, AuthoredType> {\n const result = new Map<string, AuthoredType>();\n const visit = (\n binding: ts.BindingName,\n source: ts.Expression | undefined,\n fallback: AuthoredType,\n sourceEnv = env,\n ): void => {\n if (ts.isIdentifier(binding)) {\n result.set(binding.text, source ? this.expression(source, sourceEnv) : fallback);\n return;\n }\n const value = source && unwrapExpression(source);\n const structural = ts.isArrayBindingPattern(binding) && value\n ? this.arrayBindingSources(value, sourceEnv)\n : undefined;\n binding.elements.forEach((element, index) => {\n if (!ts.isBindingElement(element)) return;\n const elementFallback = fallback.kind === \"list\" ? fallback.of : unknownType;\n const elementSource = structural?.sources[index];\n visit(\n element.name,\n elementSource && !ts.isOmittedExpression(elementSource) ? elementSource as ts.Expression : undefined,\n elementFallback,\n structural?.env ?? sourceEnv,\n );\n });\n };\n visit(name, initializer, overall);\n return result;\n }\n\n private arrayBindingSources(\n value: ts.Expression,\n env: TypeEnvironment,\n ): { sources: readonly ts.Expression[]; env: TypeEnvironment } | undefined {\n if (ts.isArrayLiteralExpression(value)) return { sources: value.elements, env };\n if (!ts.isCallExpression(value) || !ts.isIdentifier(value.expression) || env.variables.has(value.expression.text)) return undefined;\n const helper = this.module.helpers?.get(value.expression.text);\n const returned = helperReturnExpression(helper);\n const array = returned && unwrapExpression(returned);\n if (!helper || !array || !ts.isArrayLiteralExpression(array)) return undefined;\n const nested = cloneEnv(env);\n nested.literalContext = expansionContext(env.literalContext, value, this.module.sourceFile);\n helper.parameters.forEach((parameter, index) => {\n const argument = value.arguments[index];\n const type = argument ? this.expression(argument, env) : unknownType;\n const binding = argument ? this.binding(argument, env, type) : { type: unknownType };\n for (const name of bindingNames(parameter.name)) setBinding(nested, name, binding);\n });\n return { sources: array.elements, env: nested };\n }\n\n private prefixArity(\n node: ts.Expression | undefined,\n env: TypeEnvironment,\n seen = new Set<string>(),\n ): number {\n if (!node) return 0;\n const value = unwrapExpression(node);\n if (ts.isArrayLiteralExpression(value)) return value.elements.length;\n if (ts.isIdentifier(value)) {\n const key = `binding:${value.text}`;\n if (seen.has(key)) return 1;\n seen.add(key);\n const stable = env.constants.get(value.text);\n return stable ? this.prefixArity(stable, env, seen) : 1;\n }\n if (ts.isCallExpression(value) && ts.isIdentifier(value.expression) && !env.variables.has(value.expression.text)) {\n const key = `helper:${value.expression.text}`;\n if (seen.has(key)) return 1;\n seen.add(key);\n const returned = helperReturnExpression(this.module.helpers?.get(value.expression.text));\n return returned ? this.prefixArity(returned, env, seen) : 1;\n }\n return 1;\n }\n\n private idTextRewrite(\n node: ts.Expression,\n expected: AuthoredType | undefined,\n operands: ts.Expression[],\n types: AuthoredType[],\n ): string {\n const idOperands = operands.filter((_, index) => isIdType(types[index]));\n let replacement: string;\n if (isIdType(requiredType(expected))) {\n replacement = idOperands[0]?.getText(this.module.sourceFile) ?? JSON.stringify(\"replace-with-id\");\n } else if ([\"string\", \"enum\"].includes(requiredType(expected).kind)) {\n replacement = JSON.stringify(\"replace-with-text\");\n } else {\n replacement = `[${idOperands.map((operand) => operand.getText(this.module.sourceFile)).join(\", \")}]`;\n }\n return replaceNode(this.module.source, node, replacement);\n }\n\n private add(code: \"E_DECIMAL_SCALE\" | \"E_ENUM_VARIANT\" | \"E_ARGS_TYPE\" | \"E_ARGS_ID_SCALAR\" | \"E_ARGS_ID_TEXT\" | \"E_OPAQUE\", node: ts.Node, message: string, rewrite: string): void {\n const key = `${code}:${node.getStart(this.module.sourceFile)}:${message}`;\n if (this.seen.has(key)) return;\n this.seen.add(key);\n this.diagnostics.push(diagnostic(this.module, code, node, message, rewrite));\n }\n}\n\nfunction flattenPlus(node: ts.Expression): ts.Expression[] {\n const value = unwrapExpression(node);\n return ts.isBinaryExpression(value) && value.operatorToken.kind === ts.SyntaxKind.PlusToken\n ? [...flattenPlus(value.left), ...flattenPlus(value.right)]\n : [value];\n}\n\nfunction opaqueScalarInitializer(node: ts.Expression): boolean {\n const value = unwrapExpression(node);\n return ts.isArrayLiteralExpression(value)\n || ts.isCallExpression(value)\n || ts.isBinaryExpression(value) && value.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken;\n}\n\nfunction identityScalar(type: AuthoredType): boolean {\n const value = requiredType(type);\n return isIdType(value) || value.kind === \"principal\";\n}\n\nfunction isInsertIdSink(node: ts.Expression): boolean {\n let current: ts.Node = node;\n while (current.parent && !ts.isFunctionLike(current.parent)) {\n const parent = current.parent;\n if ((ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent))\n && propertyName(parent.name) === \"id\") {\n const object = parent.parent;\n const call = object.parent;\n return ts.isObjectLiteralExpression(object)\n && ts.isCallExpression(call)\n && call.arguments[1] === object\n && ts.isPropertyAccessExpression(call.expression)\n && call.expression.name.text === \"insert\";\n }\n current = parent;\n }\n return false;\n}\n\nfunction isRuntimeValidatedIdentitySink(node: ts.Expression): boolean {\n for (let current: ts.Node = node; current.parent && !ts.isFunctionLike(current.parent); current = current.parent) {\n const parent = current.parent;\n if (!ts.isPropertyAssignment(parent) && !ts.isShorthandPropertyAssignment(parent)) continue;\n const object = parent.parent;\n const call = object.parent;\n if (!ts.isObjectLiteralExpression(object) || !ts.isCallExpression(call)\n || !ts.isPropertyAccessExpression(call.expression)) continue;\n const method = call.expression.name.text;\n if (method === \"insert\" && call.arguments[1] === object) return true;\n if ((method === \"update\" || method === \"upsert\") && call.arguments[2] === object) return true;\n }\n return false;\n}\n\nfunction identityValueMatches(type: AuthoredType): boolean {\n const value = requiredType(type);\n return isIdType(value) || value.kind === \"principal\";\n}\n\nfunction insertIdReplacement(node: ts.Expression, value: string): string {\n return ts.isIdentifier(node) && ts.isShorthandPropertyAssignment(node.parent)\n ? `id: ${value}`\n : value;\n}\n\nfunction directArgsProperty(node: ts.Expression, argsBinding: string | undefined): string | undefined {\n const value = unwrapExpression(node);\n return argsBinding\n && ts.isPropertyAccessExpression(value)\n && ts.isIdentifier(value.expression)\n && value.expression.text === argsBinding\n ? value.name.text\n : undefined;\n}\n\nfunction uniqueArgumentName(args: Record<string, AuthoredType>, base: string): string {\n let candidate = base;\n let suffix = 1;\n while (candidate in args) candidate = `${base}${suffix++}`;\n return candidate;\n}\n\nfunction enclosingFunction(node: ts.Node): FunctionLike | undefined {\n for (let parent = node.parent; parent; parent = parent.parent) {\n if (isFunctionLike(parent)) return parent;\n }\n return undefined;\n}\n\nfunction uniqueBindingName(source: string, base: string): string {\n let candidate = base;\n let suffix = 1;\n while (new RegExp(`\\\\b${candidate}\\\\b`).test(source)) candidate = `${base}${suffix++}`;\n return candidate;\n}\n\nfunction replaceSourceRanges(\n source: string,\n ranges: Array<{ start: number; end: number; value: string }>,\n): string {\n let rewritten = source;\n for (const range of ranges.sort((left, right) => right.start - left.start)) {\n rewritten = `${rewritten.slice(0, range.start)}${range.value}${rewritten.slice(range.end)}`;\n }\n return rewritten;\n}\n\nfunction descriptorType(node: ts.Expression): AuthoredType {\n const call = unwrapCall(node);\n const name = call && (ts.isIdentifier(call.expression)\n ? call.expression.text\n : ts.isPropertyAccessExpression(call.expression) ? call.expression.name.text : undefined);\n if (!call) return unknownType;\n if (name === \"int\" || name === \"time\") return { kind: \"int\" };\n if (name === \"principal\") return { kind: \"principal\" };\n if (name === \"id\" || name === \"ref\") return idType;\n if (name === \"text\") {\n const maxNode = call.arguments[0] && unwrapExpression(call.arguments[0]);\n return { kind: \"string\", ...(maxNode && ts.isNumericLiteral(maxNode) ? { max: Number(maxNode.text) } : {}) };\n }\n if (name === \"bytes\") {\n const maxNode = call.arguments[0] && unwrapExpression(call.arguments[0]);\n return { kind: \"bytes\", max: maxNode && ts.isNumericLiteral(maxNode) ? Number(maxNode.text) : 0 };\n }\n if (name === \"image\" || name === \"video\") {\n const maxNode = call.arguments[0] && unwrapExpression(call.arguments[0]);\n return { kind: \"asset\", asset: name, max: maxNode && ts.isNumericLiteral(maxNode) ? Number(maxNode.text) : 0 };\n }\n if (name === \"bool\") return { kind: \"bool\" };\n if (name === \"json\") return { kind: \"json\" };\n if (name === \"enum\") {\n const variants = call.arguments[0] && unwrapExpression(call.arguments[0]);\n return variants && ts.isArrayLiteralExpression(variants)\n ? { kind: \"enum\", variants: variants.elements.filter(ts.isStringLiteralLike).map((item) => item.text) }\n : unknownType;\n }\n if (name === \"decimal\" || name === \"money\") {\n const scaleAt = name === \"decimal\" ? 0 : 1;\n const scaleNode = call.arguments[scaleAt] && unwrapExpression(call.arguments[scaleAt]);\n const scale = scaleNode && ts.isNumericLiteral(scaleNode) ? Number(scaleNode.text) : name === \"money\" ? 2 : undefined;\n const currencyNode = name === \"money\" && call.arguments[0] && unwrapExpression(call.arguments[0]);\n return scale !== undefined\n ? { kind: \"decimal\", scale, ...(currencyNode && ts.isStringLiteralLike(currencyNode) ? { currency: currencyNode.text } : {}) }\n : unknownType;\n }\n if ((name === \"optional\" || name === \"list\") && call.arguments[0]) {\n const inner = descriptorType(call.arguments[0]);\n return name === \"optional\" ? { kind: \"optional\", of: inner } : { kind: \"list\", of: inner };\n }\n return unknownType;\n}\n\nfunction bindingNames(name: ts.BindingName): string[] {\n if (ts.isIdentifier(name)) return [name.text];\n return name.elements.flatMap((item) => ts.isBindingElement(item) ? bindingNames(item.name) : []);\n}\n\nfunction namedBinding(name: ts.BindingName, target: string): ts.Identifier | undefined {\n if (ts.isIdentifier(name)) return name.text === target ? name : undefined;\n for (const element of name.elements) {\n if (!ts.isBindingElement(element)) continue;\n const found = namedBinding(element.name, target);\n if (found) return found;\n }\n return undefined;\n}\n\nfunction helperReturnExpression(helper: FunctionLike | undefined): ts.Expression | undefined {\n if (!helper?.body) return undefined;\n if (!ts.isBlock(helper.body)) return helper.body;\n if (helper.body.statements.length !== 1 || !ts.isReturnStatement(helper.body.statements[0])) return undefined;\n return helper.body.statements[0].expression;\n}\n\nfunction operationCompositeBindings(handler: FunctionLike): Partial<Record<OperationComposite, string>> {\n const parameter = handler.parameters[0];\n if (!parameter || !ts.isObjectBindingPattern(parameter.name)) return {};\n const bindings: Partial<Record<OperationComposite, string>> = {};\n for (const element of parameter.name.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const property = element.propertyName ? propertyName(element.propertyName) : element.name.text;\n if (property === \"args\" || property === \"ctx\" || property === \"db\") bindings[property] = element.name.text;\n }\n return bindings;\n}\n\nfunction setBinding(env: TypeEnvironment, name: string, binding: TypeBinding, constant?: ts.Expression): void {\n env.variables.set(name, { ...binding });\n if (constant) env.constants.set(name, constant);\n else env.constants.delete(name);\n}\n\nfunction cloneEnv(env: TypeEnvironment): TypeEnvironment {\n return {\n variables: new Map([...env.variables].map(([name, binding]) => [name, { ...binding }])),\n constants: new Map(env.constants),\n args: env.args,\n mutableBindings: env.mutableBindings,\n memo: new Map(),\n literalContext: env.literalContext,\n };\n}\n\nfunction commonType(values: AuthoredType[]): AuthoredType {\n if (values.length === 0 || values.some((item) => item.kind === \"unknown\")) return unknownType;\n const first = JSON.stringify(values[0]);\n return values.every((item) => JSON.stringify(item) === first) ? values[0]! : unknownType;\n}\n\nfunction assetFieldType(asset: \"image\" | \"video\", field: string): AuthoredType | undefined {\n // @ref LLP 1006#3-authoring-surface \u2014 admission facts are a closed object type before ordinary Field lowering.\n if (field === \"id\") return idType;\n if (field === \"width\" || field === \"height\" || asset === \"video\" && field === \"duration\") return { kind: \"int\" };\n return undefined;\n}\n\nfunction authoredTypeName(value: AuthoredType): string {\n if (isIdType(value)) return \"Id\";\n if (value.kind === \"list\") return \"an array\";\n if (value.kind === \"object\" || value.kind === \"json\") return \"an object\";\n if (value.kind === \"asset\") return `${value.asset} asset`;\n return value.kind;\n}\n\nfunction fractionalDigits(value: string): number {\n const expanded = expandedNumericLiteral(value);\n return expanded?.fraction.length ?? 1;\n}\n\nfunction scaledInteger(value: string, scale: number): number | undefined {\n const expanded = expandedNumericLiteral(value);\n if (!expanded || expanded.fraction.length > scale) return undefined;\n const result = BigInt(`${expanded.whole}${expanded.fraction.padEnd(scale, \"0\")}`);\n return result <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(result) : undefined;\n}\n\nfunction decimalName(value: AuthoredType): string {\n if (value.kind === \"decimal\") return value.currency ? `Money<${JSON.stringify(value.currency)}, ${value.scale}>` : `Decimal<${value.scale}>`;\n return value.kind === \"int\" ? \"Int\" : value.kind === \"enum\" ? \"Enum\" : \"Unknown\";\n}\n\nfunction isIntegerZero(node: ts.Expression): boolean {\n const value = unwrapExpression(node);\n const expanded = ts.isNumericLiteral(value) && expandedNumericLiteral(value.text);\n return !!expanded && expanded.whole === \"0\" && expanded.fraction === \"\";\n}\n\nfunction integerLiteralValue(node: ts.Expression): number | undefined {\n const value = unwrapExpression(node);\n return ts.isNumericLiteral(value) ? scaledInteger(value.text, 0) : undefined;\n}\n\nfunction numericExpression(node: ts.Expression): boolean {\n const value = unwrapExpression(node);\n return ts.isNumericLiteral(value)\n || (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(value.operand));\n}\n\nfunction operatorText(kind: ts.SyntaxKind): string {\n return ts.tokenToString(kind) ?? ts.SyntaxKind[kind];\n}\n", "import ts from \"typescript\";\n\nexport function typecheckSource(source: string, fileName: string, libText: string): ts.Diagnostic[] {\n const sourceName = fileName.endsWith(\".ts\") ? fileName : `${fileName}.ts`;\n const files = new Map([[sourceName, source], [\"bounded-lib.d.ts\", libText]]);\n const options: ts.CompilerOptions = {\n module: ts.ModuleKind.ESNext,\n noEmit: true,\n noLib: true,\n strict: true,\n target: ts.ScriptTarget.ES2022,\n };\n const host: ts.CompilerHost = {\n fileExists: (name) => files.has(name),\n getCanonicalFileName: (name) => name,\n getCurrentDirectory: () => \"\",\n getDefaultLibFileName: () => \"bounded-lib.d.ts\",\n getNewLine: () => \"\\n\",\n getSourceFile: (name, languageVersion) => {\n const text = files.get(name);\n return text === undefined ? undefined : ts.createSourceFile(name, text, languageVersion, true);\n },\n readFile: (name) => files.get(name),\n useCaseSensitiveFileNames: () => true,\n writeFile: () => undefined,\n };\n const program = ts.createProgram([sourceName, \"bounded-lib.d.ts\"], options, host);\n return ts.getPreEmitDiagnostics(program).filter((item) => item.file?.fileName !== \"bounded-lib.d.ts\");\n}\n\nexport function formatTypeDiagnostic(diagnostic: ts.Diagnostic): string {\n return ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\");\n}\n", "import ts from \"typescript\";\nimport type { FrontendDiagnostic } from \"./ir\";\nimport { callLeaf } from \"./lower/static\";\nimport { propertyName, unwrapCall } from \"./syntax\";\n\nexport type TypeDiagnosticSite = {\n code: \"E_SCHEMA_INVALID\" | \"E_EFFECT_TYPE\" | \"E_EFFECT_THEN_ARGS\" | \"E_ARGS_TYPE\" | \"E_OPAQUE\";\n family: FrontendDiagnostic[\"family\"];\n guide: string;\n};\n\nexport function typeDiagnosticSite(node: ts.Node, file: string): TypeDiagnosticSite {\n if (file === \"schema.ts\" || file.endsWith(\"/schema.ts\")) {\n return { code: \"E_SCHEMA_INVALID\", family: \"schema\", guide: \"schema/project\" };\n }\n const declaration = ancestor(node, ts.isVariableDeclaration);\n const call = declaration?.initializer && unwrapCall(declaration.initializer);\n const kind = call && callLeaf(call);\n if (kind === \"effect\") {\n const property = ancestor(node, ts.isPropertyAssignment);\n return property && propertyName(property.name) === \"then\"\n ? { code: \"E_EFFECT_THEN_ARGS\", family: \"effect\", guide: \"effects/authoring\" }\n : { code: \"E_EFFECT_TYPE\", family: \"effect\", guide: \"effects/authoring\" };\n }\n if (call && (kind === \"query\" || kind === \"mutation\")) {\n const args = call.arguments[0];\n if (args && node.getStart() >= args.getStart() && node.getEnd() <= args.getEnd()) {\n return { code: \"E_ARGS_TYPE\", family: \"args\", guide: \"programs/args\" };\n }\n }\n return { code: \"E_OPAQUE\", family: \"opaque\", guide: \"opaque/subset\" };\n}\n\nfunction ancestor<T extends ts.Node>(node: ts.Node, guard: (value: ts.Node) => value is T): T | undefined {\n let current: ts.Node | undefined = node;\n while (current) {\n if (guard(current)) return current;\n current = current.parent;\n }\n return undefined;\n}\n", "import ts from \"typescript\";\nimport { expressionProperty, propertyName, snapbackCallName, unwrapCall, unwrapExpression } from \"../syntax\";\n\nexport function callLeaf(node: ts.Expression | undefined): string | undefined {\n if (!node) return undefined;\n const call = unwrapCall(node);\n if (!call) return undefined;\n const snapback = snapbackCallName(call);\n if (snapback) return snapback;\n const leaf = ts.isIdentifier(call.expression)\n ? call.expression.text\n : ts.isPropertyAccessExpression(call.expression) ? call.expression.name.text : undefined;\n return leaf && [\"query\", \"mutation\", \"effect\", \"channel\", \"table\", \"schema\", \"seed\", \"emit\"].includes(leaf)\n ? undefined\n : leaf;\n}\n\nexport function callOf(node: ts.Expression | undefined, name: string): ts.CallExpression | undefined {\n const call = node && unwrapCall(node);\n return call && callLeaf(call) === name ? call : undefined;\n}\n\nexport function objectOf(node: ts.Expression | undefined): ts.ObjectLiteralExpression | undefined {\n const value = node && unwrapExpression(node);\n return value && ts.isObjectLiteralExpression(value) ? value : undefined;\n}\n\nexport function property(object: ts.ObjectLiteralExpression, name: string): ts.Expression | undefined {\n return expressionProperty(object, name);\n}\n\nexport function propertyEntries(object: ts.ObjectLiteralExpression): Array<{ name: string; value: ts.Expression; node: ts.Node }> {\n const entries: Array<{ name: string; value: ts.Expression; node: ts.Node }> = [];\n for (const item of object.properties) {\n if (ts.isPropertyAssignment(item)) {\n const name = propertyName(item.name);\n if (name) entries.push({ name, value: item.initializer, node: item });\n } else if (ts.isShorthandPropertyAssignment(item)) {\n entries.push({ name: item.name.text, value: item.name, node: item });\n }\n }\n return entries;\n}\n\nexport function stringValue(node: ts.Expression | undefined): string | undefined {\n const value = node && unwrapExpression(node);\n return value && ts.isStringLiteralLike(value) ? value.text : undefined;\n}\n\nexport function numberValue(node: ts.Expression | undefined): number | undefined {\n const value = node && unwrapExpression(node);\n if (value && ts.isNumericLiteral(value)) return Number(value.text);\n if (value && ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.MinusToken\n && ts.isNumericLiteral(value.operand)) return -Number(value.operand.text);\n return undefined;\n}\n\nexport function booleanValue(node: ts.Expression | undefined): boolean | undefined {\n const value = node && unwrapExpression(node);\n if (value?.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (value?.kind === ts.SyntaxKind.FalseKeyword) return false;\n return undefined;\n}\n\nexport function stringArray(node: ts.Expression | undefined): string[] | undefined {\n const value = node && unwrapExpression(node);\n if (!value || !ts.isArrayLiteralExpression(value)) return undefined;\n const result = value.elements.map((item) => stringValue(item));\n return result.every((item): item is string => item !== undefined) ? result : undefined;\n}\n\nexport function staticJson(node: ts.Expression, constants: Map<string, unknown> = new Map()): unknown | undefined {\n const value = unwrapExpression(node);\n if (value.kind === ts.SyntaxKind.NullKeyword) return null;\n const bool = booleanValue(value);\n if (bool !== undefined) return bool;\n const number = numberValue(value);\n if (number !== undefined) return number;\n const string = stringValue(value);\n if (string !== undefined) return string;\n if (ts.isIdentifier(value)) return constants.get(value.text);\n if (ts.isArrayLiteralExpression(value)) {\n const output: unknown[] = [];\n for (const item of value.elements) {\n if (ts.isSpreadElement(item)) return undefined;\n const lowered = staticJson(item, constants);\n if (lowered === undefined) return undefined;\n output.push(lowered);\n }\n return output;\n }\n if (ts.isObjectLiteralExpression(value)) {\n const output: Record<string, unknown> = Object.create(null);\n for (const item of value.properties) {\n if (ts.isSpreadAssignment(item)) {\n const spread = staticJson(item.expression, constants);\n if (!spread || typeof spread !== \"object\" || Array.isArray(spread)) return undefined;\n Object.assign(output, spread);\n continue;\n }\n const entry = ts.isPropertyAssignment(item)\n ? { name: propertyName(item.name), value: item.initializer }\n : ts.isShorthandPropertyAssignment(item) ? { name: item.name.text, value: item.name } : undefined;\n if (!entry?.name) return undefined;\n const lowered = staticJson(entry.value, constants);\n if (lowered === undefined) return undefined;\n output[entry.name] = lowered;\n }\n return output;\n }\n return undefined;\n}\n\nexport function moduleJsonConstants(sourceFile: ts.SourceFile): Map<string, unknown> {\n const constants = new Map<string, unknown>();\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const value = staticJson(declaration.initializer, constants);\n if (value !== undefined) constants.set(declaration.name.text, value);\n }\n }\n return constants;\n}\n", "import ts from \"typescript\";\nimport { authoredTypeFromColumn, requiredType, unknownType, type AuthoredType } from \"../authored-types\";\nimport { diagnostic } from \"../diagnostics\";\nimport { IR_CONTRACT, type FrontendDiagnostic, type RetentionPolicy, type SchemaJson, type TableJson, type Value } from \"../ir\";\nimport type { TableInfo } from \"../compiler\";\nimport { expandedNumericLiteral, hasExport, propertyName, staticMemberPath, unwrapCall, unwrapExpression } from \"../syntax\";\nimport {\n booleanValue,\n callLeaf,\n numberValue,\n objectOf,\n property,\n propertyEntries,\n staticJson,\n stringArray,\n stringValue,\n} from \"./static\";\nimport { validateMaintainRuleTypes, validateRuleTypes } from \"./rule-types\";\n\n// @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 schema descriptors lower by exported name; id/byId are implicit.\n\ntype SchemaModule = { sourceFile: ts.SourceFile; source: string; fileName: string };\ntype LoweredSchema = {\n schema: SchemaJson;\n tables: Map<string, TableInfo>;\n channels: Set<string>;\n diagnostics: FrontendDiagnostic[];\n};\n\nexport function lowerSchema(source: string, fileName: string): LoweredSchema {\n const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.ES2022, true);\n const module = { sourceFile, source, fileName };\n const diagnostics: FrontendDiagnostic[] = [];\n const tableCalls = new Map<string, ts.CallExpression>();\n const channelCalls = new Map<string, ts.CallExpression>();\n let defaultCall: ts.CallExpression | undefined;\n\n for (const statement of sourceFile.statements) {\n if (ts.isExportAssignment(statement) && !statement.isExportEquals) {\n const call = unwrapCall(statement.expression);\n if (call && callLeaf(call) === \"schema\") defaultCall = call;\n else diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_DEFAULT_EXPORT\", statement, \"schema.ts must default-export schema({...})\"));\n continue;\n }\n if (!ts.isVariableStatement(statement) || !hasExport(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const call = unwrapCall(declaration.initializer);\n if (!call) continue;\n if (callLeaf(call) === \"table\") tableCalls.set(declaration.name.text, call);\n if (callLeaf(call) === \"channel\") channelCalls.set(declaration.name.text, call);\n }\n }\n\n if (!defaultCall) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_DEFAULT_EXPORT\", sourceFile, \"schema.ts must default-export schema({...})\"));\n }\n\n const tables = new Map<string, TableInfo>();\n for (const name of tableCalls.keys()) {\n if (name.startsWith(\"_\")) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_RESERVED\", tableCalls.get(name)!, `table ${name} uses the reserved _ prefix`));\n }\n tables.set(name, { name, private: true });\n }\n\n const tableJson: Record<string, TableJson> = Object.create(null);\n for (const [name, call] of tableCalls) {\n const lowered = lowerTable(module, name, call, tables, diagnostics);\n if (lowered) {\n tableJson[name] = lowered.value;\n tables.set(name, {\n name,\n private: lowered.private,\n columns: lowered.columns,\n indexes: lowered.indexes,\n readRule: lowered.readRule,\n });\n }\n }\n\n const channelJson: Record<string, unknown> = Object.create(null);\n for (const [name, call] of channelCalls) {\n const lowered = lowerChannel(module, call, tables, diagnostics);\n if (lowered) channelJson[name] = lowered;\n }\n\n validateRuleTypes(module, tableCalls, channelCalls, tableJson, channelJson, diagnostics);\n\n const root = defaultCall ? objectOf(defaultCall.arguments[0]) : undefined;\n if (defaultCall && !root) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_DEFAULT_EXPORT\", defaultCall, \"schema() requires one object literal\"));\n }\n if (root) {\n validateKnownKeys(module, root, [\"auth\", \"tables\", \"maintains\", \"channels\"], \"schema\", \"E_SCHEMA_INVALID\", diagnostics);\n validateRootRefs(module, root, \"tables\", tableCalls, diagnostics);\n validateRootRefs(module, root, \"channels\", channelCalls, diagnostics);\n }\n\n const maintains = root ? lowerMaintains(module, property(root, \"maintains\"), tables, tableJson, diagnostics) : [];\n if (root) validateMaintainRuleTypes(module, property(root, \"maintains\"), tableJson, diagnostics);\n for (const item of maintains) {\n const value = item as { source: string; target: string };\n const info = tables.get(value.target);\n if (info) info.maintainedFrom = value.source;\n }\n const authObject = root && objectOf(property(root, \"auth\"));\n if (authObject) validateKnownKeys(module, authObject, [\"password\", \"guests\"], \"auth\", \"E_SCHEMA_INVALID\", diagnostics);\n if (root && property(root, \"auth\") && !authObject) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", property(root, \"auth\")!, \"auth must be an object\"));\n }\n for (const key of [\"password\", \"guests\"]) {\n const node = authObject && property(authObject, key);\n if (node && booleanValue(node) === undefined) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", node, `auth.${key} must be boolean`));\n }\n }\n const auth = {\n password: booleanValue(authObject && property(authObject, \"password\")) ?? false,\n guests: booleanValue(authObject && property(authObject, \"guests\")) ?? false,\n };\n\n return {\n schema: { tables: tableJson, maintains, channels: channelJson, auth, effects: [] },\n tables,\n channels: new Set(channelCalls.keys()),\n diagnostics,\n };\n}\n\nfunction lowerTable(\n module: SchemaModule,\n name: string,\n call: ts.CallExpression,\n tables: Map<string, TableInfo>,\n diagnostics: FrontendDiagnostic[],\n): {\n value: TableJson;\n private: boolean;\n columns: Record<string, AuthoredType>;\n indexes: Record<string, { columns: string[]; types: AuthoredType[] }>;\n readRule: unknown;\n} | undefined {\n const config = objectOf(call.arguments[0]);\n if (!config) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", call, `table ${name} requires an object literal`));\n return undefined;\n }\n const columnsObject = objectOf(property(config, \"columns\"));\n if (!columnsObject) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", config, `table ${name} requires columns`));\n return undefined;\n }\n validateKnownKeys(module, config, [\"columns\", \"indexes\", \"rules\", \"constraints\", \"retain\"], `table ${name}`, \"E_SCHEMA_INVALID\", diagnostics);\n validateRecordShape(module, columnsObject, `columns for ${name}`, \"E_SCHEMA_INVALID\", diagnostics);\n const columns: Record<string, unknown> = Object.assign(Object.create(null), { id: \"Id\" });\n for (const entry of propertyEntries(columnsObject)) {\n if (entry.name === \"id\") {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_ID_RESERVED\", entry.node, `column ${name}.id is implicit; remove it`));\n continue;\n }\n const lowered = lowerColumn(module, entry.value, tables, diagnostics);\n if (lowered !== undefined) columns[entry.name] = lowered;\n }\n const authoredColumns = Object.fromEntries(\n Object.entries(columns).map(([column, value]) => [column, authoredTypeFromColumn(value)]),\n );\n\n const indexes: Record<string, unknown> = Object.assign(Object.create(null), { byId: { columns: [\"id\"], unique: true } });\n const indexesObject = objectOf(property(config, \"indexes\"));\n if (property(config, \"indexes\") && !indexesObject) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", property(config, \"indexes\")!, `indexes for ${name} must be an object`));\n }\n if (indexesObject) {\n validateRecordShape(module, indexesObject, `indexes for ${name}`, \"E_SCHEMA_INVALID\", diagnostics);\n for (const entry of propertyEntries(indexesObject)) {\n const value = objectOf(entry.value);\n const names = value && stringArray(property(value, \"columns\"));\n if (!value || !names) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", entry.node, `index ${name}.${entry.name} requires columns`));\n continue;\n }\n if (names.length === 0 || new Set(names).size !== names.length) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INDEX_COLUMN\", entry.node, `index ${name}.${entry.name} columns must be non-empty and unique`));\n }\n if (names.length > 8) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INDEX_COLUMN\", entry.node, `index ${name}.${entry.name} has ${names.length} columns; indexes support at most 8`));\n }\n const before = diagnostics.length;\n validateKnownKeys(module, value, [\"columns\", \"unique\"], `index ${name}.${entry.name}`, \"E_SCHEMA_INDEX_OPTION\", diagnostics);\n const uniqueNode = property(value, \"unique\");\n const unique = uniqueNode ? booleanValue(uniqueNode) : false;\n if (uniqueNode && unique === undefined) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INDEX_OPTION\", uniqueNode, `index ${name}.${entry.name} unique must be boolean`));\n }\n if (entry.name === \"byId\") {\n if (names.length !== 1 || names[0] !== \"id\" || unique !== true || diagnostics.length !== before) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_ID_RESERVED\", entry.node, `index ${name}.byId is implicit as { columns: ['id'], unique: true }; remove or match it`));\n }\n continue;\n }\n for (const column of names) {\n if (!Object.hasOwn(columns, column)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INDEX_COLUMN\", entry.node, `index ${name}.${entry.name} names unknown column ${column}`));\n } else if (!indexableColumnDescriptor(columns[column])) {\n // @ref LLP 1006#1-the-move \u2014 asset records have no scalar ordering and therefore cannot enter an index.\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_INDEX_COLUMN\",\n entry.node,\n `index ${name}.${entry.name} column ${column} has non-indexable type ${columnDescriptorName(columns[column])}`,\n ));\n }\n }\n indexes[entry.name] = { columns: names, unique: unique ?? false };\n }\n }\n const authoredIndexes = Object.fromEntries(Object.entries(indexes).map(([index, descriptor]) => {\n const indexColumns = [...(descriptor as { columns: string[] }).columns];\n return [index, {\n columns: indexColumns,\n types: indexColumns.map((column) => authoredColumns[column] ?? unknownType),\n unique: (descriptor as { unique?: boolean }).unique ?? false,\n }];\n }));\n const tableInfo = tables.get(name);\n if (tableInfo) {\n tableInfo.columns = authoredColumns;\n tableInfo.indexes = authoredIndexes;\n }\n\n const rulesObject = objectOf(property(config, \"rules\"));\n if (property(config, \"rules\") && !rulesObject) {\n diagnostics.push(ruleDiagnostic(module, property(config, \"rules\")!, `rules for ${name} must be an object`));\n }\n if (rulesObject) validateKnownKeys(module, rulesObject, [\"read\", \"insert\", \"update\", \"delete\"], `rules for ${name}`, \"E_RULE_INVALID\", diagnostics);\n const rules: Record<string, unknown> = Object.create(null);\n for (const side of [\"read\", \"insert\", \"update\", \"delete\"]) {\n const node = rulesObject && property(rulesObject, side);\n rules[side] = node ? lowerRule(module, node, tables, diagnostics, authoredColumns) ?? \"Deny\" : \"Deny\";\n }\n const retainNode = property(config, \"retain\");\n const authoredRetention = retainNode && stringValue(retainNode);\n const retain = authoredRetention && IR_CONTRACT.retentionPolicies.includes(authoredRetention as RetentionPolicy)\n ? authoredRetention as RetentionPolicy\n : \"until-revoked\";\n if (retainNode && !IR_CONTRACT.retentionPolicies.includes(authoredRetention as RetentionPolicy)) {\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_INVALID\",\n retainNode,\n `table ${name} retain must be until-revoked or delivered-history`,\n 'retain: \"until-revoked\"',\n ));\n }\n const constraints = lowerConstraints(module, property(config, \"constraints\"), columns, indexes, diagnostics);\n return {\n value: { columns, indexes, rules, constraints, retain },\n private: !isPublicRule(rules.read),\n columns: authoredColumns,\n indexes: authoredIndexes,\n readRule: rules.read,\n };\n}\n\nfunction lowerColumn(\n module: SchemaModule,\n node: ts.Expression,\n tables: Map<string, TableInfo>,\n diagnostics: FrontendDiagnostic[],\n): unknown | undefined {\n const call = unwrapCall(node);\n const name = call && callLeaf(call);\n if (!call || !name) {\n const detail = invalidDescriptorRefusal(node);\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_COLUMN\", detail.node, detail.message, detail.rewrite));\n return undefined;\n }\n if (name === \"id\" && call.arguments.length === 0) return \"Id\";\n if (name === \"principal\" && call.arguments.length === 0) return \"Principal\";\n if (name === \"int\" && call.arguments.length === 0) return \"Int\";\n if (name === \"bool\" && call.arguments.length === 0) return \"Bool\";\n if (name === \"time\" && call.arguments.length === 0) return \"Time\";\n if (name === \"enum\" && call.arguments.length === 1) {\n const variants = stringArray(call.arguments[0]);\n if (validEnumVariants(variants)) {\n return { Enum: { variants } };\n }\n }\n if (name === \"decimal\" && call.arguments.length === 1) {\n const scale = numberValue(call.arguments[0]);\n if (validScale(scale)) return { Decimal: { scale } };\n }\n if (name === \"money\" && (call.arguments.length === 1 || call.arguments.length === 2)) {\n const currency = stringValue(call.arguments[0]);\n const scale = call.arguments[1] ? numberValue(call.arguments[1]) : 2;\n if (currency && /^[A-Z]{3}$/.test(currency) && validScale(scale)) {\n return { Money: { currency, scale } };\n }\n }\n if (name === \"text\") {\n const max = numberValue(call.arguments[0]);\n if (call.arguments.length === 1 && validPositiveInteger(max)) return { Text: { max } };\n }\n if (name === \"bytes\") {\n const max = numberValue(call.arguments[0]);\n if (call.arguments.length === 1 && validPositiveInteger(max)) return { Bytes: { max } };\n }\n if (name === \"image\" || name === \"video\") {\n const max = numberValue(call.arguments[0]);\n if (call.arguments.length === 1 && validPositiveInteger(max)) {\n // @ref LLP 1006#3-authoring-surface \u2014 the byte bound is preserved in the externally tagged engine descriptor.\n return { [name === \"image\" ? \"Image\" : \"Video\"]: { max } };\n }\n }\n if (name === \"json\") {\n const maxBytes = numberValue(call.arguments[0]);\n if (call.arguments.length === 1 && validPositiveInteger(maxBytes)) return { Json: { max_bytes: maxBytes } };\n }\n if (name === \"ref\" && call.arguments.length === 1) {\n const target = call.arguments[0];\n const table = target && ts.isIdentifier(unwrapExpression(target)) ? (unwrapExpression(target) as ts.Identifier).text : undefined;\n if (!table || !tables.has(table)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_UNKNOWN_TABLE\", target ?? call, `unknown table ${table ?? target?.getText() ?? \"<missing>\"}`));\n return undefined;\n }\n return { Ref: { table: tables.get(table)!.name } };\n }\n if (name === \"optional\" && call.arguments.length === 1 && call.arguments[0]) {\n const inner = lowerColumn(module, call.arguments[0], tables, diagnostics);\n return inner === undefined ? undefined : { Optional: inner };\n }\n if (name === \"list\" && call.arguments.length === 2 && call.arguments[0]) {\n const inner = lowerColumn(module, call.arguments[0], tables, diagnostics);\n if (inner === undefined) return undefined;\n const options = objectOf(call.arguments[1]);\n const max = options && numberValue(property(options, \"max\"));\n if (options) validateKnownKeys(module, options, [\"max\"], \"list options\", \"E_SCHEMA_INVALID\", diagnostics);\n if (inner !== undefined && validPositiveInteger(max)) return { List: { of: inner, max } };\n }\n const detail = invalidDescriptorRefusal(node);\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_COLUMN\", detail.node, detail.message, detail.rewrite));\n return undefined;\n}\n\nfunction lowerRule(\n module: SchemaModule,\n node: ts.Expression,\n tables: Map<string, TableInfo>,\n diagnostics: FrontendDiagnostic[],\n columns?: Record<string, AuthoredType>,\n): unknown | undefined {\n const call = unwrapCall(node);\n const name = call && callLeaf(call);\n if (!call || !name) {\n diagnostics.push(ruleDiagnostic(module, node, \"rule must be a rule.* descriptor\"));\n return undefined;\n }\n if (name === \"public\" && call.arguments.length === 1 && stringValue(call.arguments[0])) {\n return { Public: { reason: stringValue(call.arguments[0])! } };\n }\n if (name === \"allow\" && call.arguments.length === 0) return \"Allow\";\n if (name === \"deny\" && call.arguments.length === 0) return \"Deny\";\n if (name === \"system\" && call.arguments.length === 0) {\n return { Eq: [\"Viewer\", { Literal: { Id: IR_CONTRACT.systemPrincipalId } }] };\n }\n if (name === \"viewerIs\" && call.arguments.length === 1 && stringValue(call.arguments[0])) {\n return { Eq: [{ Field: stringValue(call.arguments[0])! }, \"Viewer\"] };\n }\n if ((name === \"eq\" || name === \"ne\") && call.arguments.length === 2) {\n const leftExpected = call.arguments[1] && ruleFieldType(call.arguments[1], columns);\n const rightExpected = call.arguments[0] && ruleFieldType(call.arguments[0], columns);\n const left = call.arguments[0] && lowerTerm(module, call.arguments[0], diagnostics, leftExpected);\n const right = call.arguments[1] && lowerTerm(module, call.arguments[1], diagnostics, rightExpected);\n if (left !== undefined && right !== undefined) return { [name === \"eq\" ? \"Eq\" : \"Ne\"]: [left, right] };\n return undefined;\n }\n if (name === \"and\" || name === \"or\") {\n if (call.arguments.length === 0) {\n diagnostics.push(ruleDiagnostic(module, node, `rule.${name} requires at least one rule`));\n return undefined;\n }\n const values = call.arguments.map((item) => lowerRule(module, item, tables, diagnostics, columns)).filter((item) => item !== undefined);\n return { [name === \"and\" ? \"And\" : \"Or\"]: values };\n }\n if (name === \"not\" && call.arguments.length === 1 && call.arguments[0]) {\n const value = lowerRule(module, call.arguments[0], tables, diagnostics, columns);\n return value === undefined ? undefined : { Not: value };\n }\n if ((name === \"exists\" || name === \"created\") && call.arguments.length === 3) {\n const target = call.arguments[0];\n const tableName = target && ts.isIdentifier(unwrapExpression(target)) ? (unwrapExpression(target) as ts.Identifier).text : undefined;\n if (!tableName || !tables.has(tableName)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_UNKNOWN_TABLE\", target ?? call, `unknown table ${tableName ?? \"<missing>\"}`));\n return undefined;\n }\n const index = stringValue(call.arguments[1]);\n const keyNode = call.arguments[2] && unwrapExpression(call.arguments[2]);\n if (!index || !keyNode || !ts.isArrayLiteralExpression(keyNode)) {\n diagnostics.push(ruleDiagnostic(module, call, `rule.${name} requires table, index, and a key array`));\n return undefined;\n }\n const expected = tables.get(tableName)!.indexes?.[index]?.types;\n const key: unknown[] = [];\n let failed = false;\n keyNode.elements.forEach((item, position) => {\n const term = lowerTerm(module, item, diagnostics, expected?.[position]);\n if (term === undefined) failed = true;\n else key.push(term);\n });\n if (failed) return undefined;\n return {\n [name === \"exists\" ? \"Exists\" : \"Created\"]: {\n table: tables.get(tableName)!.name,\n index,\n key,\n provenance: ruleProvenance(key),\n },\n };\n }\n if (name === \"exists\" && call.arguments.length === 4) {\n diagnostics.push(ruleDiagnostic(\n module,\n call.arguments[3]!,\n \"rule.exists visibility is derived from the referenced table policy; remove the options argument\",\n ));\n return undefined;\n }\n diagnostics.push(ruleDiagnostic(module, node, `unsupported rule.${name}`));\n return undefined;\n}\n\nfunction lowerTerm(\n module: SchemaModule,\n node: ts.Expression,\n diagnostics: FrontendDiagnostic[],\n expected?: AuthoredType,\n): unknown | undefined {\n const value = unwrapExpression(node);\n if (ts.isPropertyAccessExpression(value) && value.expression.getText() === \"rule\" && value.name.text === \"viewer\") return \"Viewer\";\n const call = unwrapCall(value);\n const name = call && callLeaf(call);\n if (call && name === \"field\" && call.arguments.length === 1 && stringValue(call.arguments[0])) {\n return { Field: stringValue(call.arguments[0])! };\n }\n if (call && (name === \"oldField\" || name === \"nextField\")\n && call.arguments.length === 1 && stringValue(call.arguments[0])) {\n return { [name === \"oldField\" ? \"OldField\" : \"NextField\"]: stringValue(call.arguments[0])! };\n }\n if (call && name === \"literal\" && call.arguments[0]) {\n const target = expected && requiredType(expected);\n if (target?.kind === \"decimal\") {\n const scaled = scaledRuleLiteral(call.arguments[0], target.scale);\n if (scaled !== undefined) return { Literal: { Int: scaled } };\n if (numericRuleLiteral(call.arguments[0])) {\n diagnostics.push(diagnostic(\n module,\n \"E_DECIMAL_SCALE\",\n call.arguments[0],\n `numeric rule literal must fit Decimal scale ${target.scale} and the safe integer range`,\n module.source.slice(0, call.arguments[0].getStart(module.sourceFile))\n + \"0\" + module.source.slice(call.arguments[0].getEnd()),\n ));\n return undefined;\n }\n }\n const fractional = findFractionalLiteral(call.arguments[0]);\n if (fractional) {\n diagnostics.push(diagnostic(\n module,\n \"E_DECIMAL_SCALE\",\n fractional,\n `fractional literal ${fractional.text} has no Decimal target in a rule literal`,\n module.source.slice(0, fractional.getStart(module.sourceFile)) + fractional.text.replace(\".\", \"\") + module.source.slice(fractional.getEnd()),\n ));\n return undefined;\n }\n const literal = staticJson(call.arguments[0]);\n if (literal !== undefined) {\n const encoded = encodeValue(literal, expected);\n if (encoded !== undefined) return { Literal: encoded };\n diagnostics.push(ruleDiagnostic(\n module,\n call.arguments[0],\n target?.kind === \"bytes\"\n ? \"Bytes rule literal must be exactly { Bytes: canonicalLowercaseBase16 }\"\n : \"a { Bytes: ... } rule literal requires a Bytes schema position\",\n ));\n return undefined;\n }\n }\n diagnostics.push(ruleDiagnostic(module, node, \"rule term must be field(), oldField(), nextField(), viewer, or literal()\"));\n return undefined;\n}\n\nfunction ruleFieldType(node: ts.Expression, columns?: Record<string, AuthoredType>): AuthoredType | undefined {\n const call = unwrapCall(node);\n if (!call || callLeaf(call) !== \"field\" || call.arguments.length !== 1) return undefined;\n const name = stringValue(call.arguments[0]);\n return name && columns && Object.hasOwn(columns, name) ? columns[name] : undefined;\n}\n\nfunction numericRuleLiteral(node: ts.Expression): { text: string; negative: boolean } | undefined {\n const value = unwrapExpression(node);\n if (ts.isNumericLiteral(value)) return { text: value.text, negative: false };\n if (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.MinusToken\n && ts.isNumericLiteral(unwrapExpression(value.operand))) {\n return { text: (unwrapExpression(value.operand) as ts.NumericLiteral).text, negative: true };\n }\n return undefined;\n}\n\nfunction scaledRuleLiteral(node: ts.Expression, scale: number): number | undefined {\n const numeric = numericRuleLiteral(node);\n const expanded = numeric && expandedNumericLiteral(numeric.text);\n if (!expanded || expanded.fraction.length > scale) return undefined;\n const magnitude = BigInt(expanded.whole) * (10n ** BigInt(scale))\n + BigInt(expanded.fraction.padEnd(scale, \"0\") || \"0\");\n const signed = numeric.negative ? -magnitude : magnitude;\n return signed >= -9_007_199_254_740_991n && signed <= 9_007_199_254_740_991n\n ? Number(signed)\n : undefined;\n}\n\nfunction findFractionalLiteral(node: ts.Node): ts.NumericLiteral | undefined {\n let found: ts.NumericLiteral | undefined;\n const visit = (value: ts.Node) => {\n if (found) return;\n if (ts.isNumericLiteral(value) && value.text.includes(\".\")) found = value;\n else ts.forEachChild(value, visit);\n };\n visit(node);\n return found;\n}\n\nfunction lowerConstraints(\n module: SchemaModule,\n node: ts.Expression | undefined,\n columns: Record<string, unknown>,\n indexes: Record<string, unknown>,\n diagnostics: FrontendDiagnostic[],\n): unknown[] {\n const value = node && unwrapExpression(node);\n if (!value) return [];\n if (!ts.isArrayLiteralExpression(value)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", value, \"constraints must be an array\"));\n return [];\n }\n const output: unknown[] = [];\n for (const item of value.elements) {\n const object = objectOf(item);\n if (!object) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, \"constraint must be an object with exactly one supported form\"));\n continue;\n }\n const entries = propertyEntries(object);\n if (entries.length !== 1 || object.properties.length !== 1) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, \"constraint must have exactly one of unique, cap, appendOnly, immutable, text, or finalExistsOnInsert\"));\n continue;\n }\n const unique = stringValue(property(object, \"unique\"));\n if (unique) {\n if (!Object.hasOwn(indexes, unique)) diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INDEX_COLUMN\", item, `constraint names unknown index ${unique}`));\n output.push({ Unique: { index: unique } });\n continue;\n }\n const cap = objectOf(property(object, \"cap\"));\n if (cap) {\n validateKnownKeys(module, cap, [\"by\", \"max\"], \"cap constraint\", \"E_SCHEMA_CONSTRAINT\", diagnostics);\n const by = stringArray(property(cap, \"by\"));\n const max = numberValue(property(cap, \"max\"));\n if (by && by.length > 0 && max !== undefined && Number.isInteger(max) && max > 0) {\n for (const field of by) {\n if (!Object.hasOwn(columns, field)) diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, `cap constraint names unknown column ${field}`));\n }\n output.push({ Cap: { by, max } });\n } else {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, \"cap constraint requires non-empty by and a positive integer max\"));\n }\n continue;\n }\n if (property(object, \"appendOnly\")) {\n if (booleanValue(property(object, \"appendOnly\")) === true) output.push(\"AppendOnly\");\n else diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, \"appendOnly constraint must be true\"));\n continue;\n }\n const immutable = stringArray(property(object, \"immutable\"));\n if (immutable && immutable.length > 0) {\n for (const field of immutable) {\n if (!Object.hasOwn(columns, field)) diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, `immutable constraint names unknown column ${field}`));\n }\n output.push({ Immutable: { fields: immutable } });\n continue;\n }\n const text = objectOf(property(object, \"text\"));\n if (text) {\n validateKnownKeys(module, text, [\"field\", \"min\", \"format\"], \"text constraint\", \"E_SCHEMA_CONSTRAINT\", diagnostics);\n const field = stringValue(property(text, \"field\"));\n const min = property(text, \"min\") ? numberValue(property(text, \"min\")) : 0;\n const format = property(text, \"format\") ? stringValue(property(text, \"format\")) : undefined;\n if (!field || !(field in columns)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, `text constraint names unknown column ${field ?? \"<missing>\"}`));\n continue;\n }\n const max = textDescriptorMax(columns[field]);\n if (max === undefined) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, `text constraint names non-text column ${field}`));\n continue;\n }\n if (min === undefined || !Number.isInteger(min) || min < 0) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, \"text constraint min must be a non-negative integer\"));\n continue;\n }\n if (min > max) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, `text constraint min ${min} exceeds ${field}'s maximum ${max}`));\n continue;\n }\n if (format !== undefined && format !== \"handle\" && format !== \"url\") {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, \"text constraint format must be handle or url\"));\n continue;\n }\n if (min === 0 && format === undefined) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, \"text constraint must declare min or format\"));\n continue;\n }\n output.push({ Text: { field, min, ...(format === undefined ? {} : { format }) } });\n continue;\n }\n // @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 the static table name breaks the source/target declaration cycle without weakening deferred catalog checks.\n const finalNode = property(object, \"finalExistsOnInsert\");\n if (finalNode) {\n const finalExists = objectOf(finalNode);\n if (!finalExists) {\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_CONSTRAINT\",\n finalNode,\n \"finalExistsOnInsert must be an object with table, index, and key\",\n finalExistsRewrite(),\n ));\n continue;\n }\n validateKnownKeys(module, finalExists, [\"table\", \"index\", \"key\"], \"finalExistsOnInsert constraint\", \"E_SCHEMA_CONSTRAINT\", diagnostics);\n const table = stringValue(property(finalExists, \"table\"));\n const index = stringValue(property(finalExists, \"index\"));\n const keyNode = property(finalExists, \"key\") && unwrapExpression(property(finalExists, \"key\")!);\n if (!table || !index || !keyNode || !ts.isArrayLiteralExpression(keyNode)) {\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_CONSTRAINT\",\n finalExists,\n \"finalExistsOnInsert requires a static table-name string, index string, and key array\",\n finalExistsRewrite(),\n ));\n continue;\n }\n const loweredTerms = keyNode.elements.map((term) => lowerTerm(module, term, diagnostics));\n if (loweredTerms.some((term) => term === undefined)) continue;\n output.push({ FinalExistsOnInsert: { table, index, key: loweredTerms } });\n continue;\n }\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_CONSTRAINT\", item, \"unknown or malformed constraint; use unique, cap, appendOnly, immutable, text, or finalExistsOnInsert\"));\n }\n return output;\n}\n\nfunction textDescriptorMax(value: unknown): number | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const descriptor = value as Record<string, any>;\n if (descriptor.Text && typeof descriptor.Text.max === \"number\") return descriptor.Text.max;\n return \"Optional\" in descriptor ? textDescriptorMax(descriptor.Optional) : undefined;\n}\n\nfunction finalExistsRewrite(): string {\n return '{ finalExistsOnInsert: { table: \"memberships\", index: \"byConversationPrincipalRole\", key: [rule.field(\"id\"), rule.field(\"creatorId\"), rule.literal(\"admin\")] } }';\n}\n\nfunction lowerMaintains(\n module: SchemaModule,\n node: ts.Expression | undefined,\n tables: Map<string, TableInfo>,\n tableJson: Record<string, unknown>,\n diagnostics: FrontendDiagnostic[],\n): unknown[] {\n // @ref LLP 1001#4-generation-and-runtime-registryrs-successorrs \u2014 authored\n // maintains use the same closed, single-owner projection contract as raw IR.\n // @ref LLP 1004#money-and-decimal-worked-out-2026-09-03 \u2014 sum values preserve the source's exact int/decimal/money descriptor.\n const value = node && unwrapExpression(node);\n if (!value) return [];\n if (!ts.isArrayLiteralExpression(value)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", value, \"maintains must be an array\"));\n return [];\n }\n const output: unknown[] = [];\n const targetOwners = new Map<string, number>();\n const dependencyEdges: Array<{ source: string; target: string; item: ts.Expression }> = [];\n for (const [position, item] of value.elements.entries()) {\n const object = objectOf(item);\n if (!object) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, \"maintain must be an object\"));\n continue;\n }\n validateKnownKeys(module, object, [\"count\", \"sum\", \"by\", \"into\", \"readable\"], \"maintain\", \"E_SCHEMA_MAINTAIN\", diagnostics);\n const count = stringValue(property(object, \"count\"));\n const sumObject = objectOf(property(object, \"sum\"));\n if (sumObject) validateKnownKeys(module, sumObject, [\"source\", \"of\"], \"sum maintain\", \"E_SCHEMA_MAINTAIN\", diagnostics);\n const source = count ?? (sumObject && stringValue(property(sumObject, \"source\")));\n const target = stringValue(property(object, \"into\"));\n const by = stringArray(property(object, \"by\"));\n const validKind = !!count !== !!sumObject;\n const sumField = sumObject && stringValue(property(sumObject, \"of\"));\n if (!validKind || !source || !target || !by || by.length === 0 || (sumObject && !sumField)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, \"maintain requires exactly one count/sum form, non-empty by, and into\"));\n continue;\n }\n if (!tables.has(source) || !tables.has(target)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_UNKNOWN_TABLE\", item, \"maintain names an unknown source or target table\"));\n continue;\n }\n const firstOwner = targetOwners.get(target);\n if (firstOwner !== undefined) {\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_MAINTAIN\",\n item,\n `maintain target ${target} is owned by both maintains[${firstOwner}] and maintains[${position}]`,\n ));\n } else {\n targetOwners.set(target, position);\n }\n const sourceColumns = loweredTableColumns(tableJson[source]) ?? {};\n const targetColumns = loweredTableColumns(tableJson[target]) ?? {};\n const groupFields = new Set<string>();\n for (const field of by) {\n if (groupFields.has(field)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, `maintain.by repeats source column ${field}`));\n continue;\n }\n groupFields.add(field);\n if (field === \"id\" || field === \"value\") {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, `maintain.by cannot use reserved source column ${field}`));\n continue;\n }\n if (!(field in sourceColumns)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, `maintain names unknown source column ${source}.${field}`));\n } else if (assetColumnDescriptor(sourceColumns[field])) {\n // @ref LLP 1006#2a-one-asset-one-home-author-ruling-2026-09-01 \u2014 maintained grouping would silently copy one affine asset into another row.\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_ASSET_MAINTAIN\",\n item,\n `maintain.by cannot use asset-typed source column ${source}.${field}`,\n ));\n }\n }\n if (sumField) {\n if (!(sumField in sourceColumns)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, `sum maintain names unknown source column ${source}.${sumField}`));\n } else if (!numericMaintainDescriptor(sourceColumns[sumField])) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, `sum maintain source column ${source}.${sumField} must be Int, Decimal, or Money`));\n }\n }\n if (targetColumns.id !== \"Id\") {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, `maintain target ${target}.id must be the intrinsic Id column`));\n }\n const expectedValue = sumField ? sourceColumns[sumField] : \"Int\";\n if (expectedValue !== undefined && !sameColumnDescriptor(targetColumns.value, expectedValue)) {\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_MAINTAIN\",\n item,\n `maintain target ${target}.value type ${columnDescriptorName(targetColumns.value)} must equal source ${source}.${sumField ?? \"count\"} type ${columnDescriptorName(expectedValue)}`,\n ));\n }\n const allowedTargetColumns = new Set([\"id\", \"value\"]);\n for (const field of groupFields) {\n if (field === \"id\" || field === \"value\") continue;\n allowedTargetColumns.add(field);\n if (field in sourceColumns && !sameColumnDescriptor(sourceColumns[field], targetColumns[field])) {\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_MAINTAIN\",\n item,\n `maintain target ${target}.${field} must exactly match source ${source}.${field}`,\n ));\n }\n }\n const extra = Object.keys(targetColumns).filter((field) => !allowedTargetColumns.has(field));\n if (extra.length > 0) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_MAINTAIN\", item, `maintain target ${target} has non-aggregate columns ${extra.join(\", \")}`));\n }\n const readableNode = property(object, \"readable\");\n output.push({\n kind: count ? \"Count\" : { Sum: { of: sumField! } },\n source,\n by,\n target,\n readable: readableNode ? lowerRule(module, readableNode, tables, diagnostics) ?? null : null,\n });\n dependencyEdges.push({ source, target, item });\n }\n const maintainSources = new Set(dependencyEdges.map((edge) => edge.source));\n for (const edge of dependencyEdges) {\n if (maintainSources.has(edge.target)) {\n diagnostics.push(schemaDiagnostic(\n module,\n \"E_SCHEMA_MAINTAIN\",\n edge.item,\n `maintain target ${edge.target} cannot also be a maintain source`,\n ));\n }\n }\n return output;\n}\n\nfunction loweredTableColumns(table: unknown): Record<string, unknown> | undefined {\n if (!table || typeof table !== \"object\" || Array.isArray(table)) return undefined;\n const columns = (table as Record<string, unknown>).columns;\n return columns && typeof columns === \"object\" && !Array.isArray(columns)\n ? columns as Record<string, unknown>\n : undefined;\n}\n\nfunction numericMaintainDescriptor(value: unknown): boolean {\n return value === \"Int\"\n || !!value && typeof value === \"object\" && !Array.isArray(value)\n && (\"Decimal\" in value || \"Money\" in value);\n}\n\nfunction columnDescriptorName(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return \"missing\";\n const [name, detail] = Object.entries(value as Record<string, unknown>)[0] ?? [\"unknown\", undefined];\n return detail === undefined ? name : `${name} ${JSON.stringify(detail)}`;\n}\n\nfunction indexableColumnDescriptor(value: unknown): boolean {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return true;\n const descriptor = value as Record<string, unknown>;\n if (\"Optional\" in descriptor) return indexableColumnDescriptor(descriptor.Optional);\n return !(\"List\" in descriptor || \"Image\" in descriptor || \"Video\" in descriptor);\n}\n\nfunction assetColumnDescriptor(value: unknown): boolean {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const descriptor = value as Record<string, any>;\n if (\"Optional\" in descriptor) return assetColumnDescriptor(descriptor.Optional);\n if (descriptor.List) return assetColumnDescriptor(descriptor.List.of);\n return \"Image\" in descriptor || \"Video\" in descriptor;\n}\n\nfunction sameColumnDescriptor(left: unknown, right: unknown): boolean {\n if (left === right) return true;\n if (!left || !right || typeof left !== \"object\" || typeof right !== \"object\"\n || Array.isArray(left) !== Array.isArray(right)) return false;\n if (Array.isArray(left) && Array.isArray(right)) {\n return left.length === right.length && left.every((value, index) => sameColumnDescriptor(value, right[index]));\n }\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const leftKeys = Object.keys(leftRecord).sort();\n const rightKeys = Object.keys(rightRecord).sort();\n return leftKeys.length === rightKeys.length\n && leftKeys.every((key, index) => key === rightKeys[index]\n && sameColumnDescriptor(leftRecord[key], rightRecord[key]));\n}\n\nfunction lowerChannel(\n module: SchemaModule,\n call: ts.CallExpression,\n tables: Map<string, TableInfo>,\n diagnostics: FrontendDiagnostic[],\n): unknown | undefined {\n const config = objectOf(call.arguments[0]);\n const argsObject = config && objectOf(property(config, \"args\"));\n if (!config || !argsObject) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", call, \"channel requires args, publish, subscribe, and ttlMs\"));\n return undefined;\n }\n validateKnownKeys(module, config, [\"args\", \"publish\", \"subscribe\", \"ttlMs\"], \"channel\", \"E_SCHEMA_INVALID\", diagnostics);\n validateRecordShape(module, argsObject, \"channel args\", \"E_SCHEMA_INVALID\", diagnostics);\n const args: Record<string, unknown> = Object.create(null);\n const authoredArgs: Record<string, AuthoredType> = Object.create(null);\n for (const entry of propertyEntries(argsObject)) {\n const lowered = lowerArgDescriptor(entry.value, tables);\n if (lowered === undefined) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", entry.node, `invalid channel argument descriptor ${entry.name}`));\n } else {\n args[entry.name] = lowered;\n authoredArgs[entry.name] = authoredTypeFromColumn(lowered);\n }\n }\n const publishNode = property(config, \"publish\");\n const subscribeNode = property(config, \"subscribe\");\n const ttl = numberValue(property(config, \"ttlMs\"));\n if (!publishNode || !subscribeNode || !validPositiveInteger(ttl)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", config, \"channel requires publish, subscribe, and ttlMs\"));\n return undefined;\n }\n return {\n args,\n publish: lowerRule(module, publishNode, tables, diagnostics, authoredArgs) ?? \"Deny\",\n subscribe: lowerRule(module, subscribeNode, tables, diagnostics, authoredArgs) ?? \"Deny\",\n ttl_ms: ttl,\n };\n}\n\nexport function lowerArgDescriptor(\n node: ts.Expression,\n tables?: Map<string, TableInfo>,\n): unknown | undefined {\n const call = unwrapCall(node);\n if (call && callLeaf(call) === \"list\") {\n const options = objectOf(call.arguments[1]);\n const max = numberValue(options && property(options, \"max\"));\n const known = options && propertyEntries(options).every((entry) => entry.name === \"max\")\n && options.properties.length === propertyEntries(options).length;\n const of = call.arguments[0] && lowerArgDescriptor(call.arguments[0], tables);\n return call.arguments.length === 2 && of !== undefined && known && validPositiveInteger(max)\n ? { List: { of, max } }\n : undefined;\n }\n if (call && callLeaf(call) === \"optional\" && call.arguments[0]) {\n const inner = lowerArgDescriptor(call.arguments[0], tables);\n return call.arguments.length === 1 && inner !== undefined ? { Optional: inner } : undefined;\n }\n if (call && callLeaf(call) === \"enum\") {\n const variants = stringArray(call.arguments[0]);\n return call.arguments.length === 1 && validEnumVariants(variants)\n ? { Enum: { variants } }\n : undefined;\n }\n if (call && callLeaf(call) === \"decimal\") {\n const scale = numberValue(call.arguments[0]);\n return call.arguments.length === 1 && validScale(scale) ? { Decimal: { scale } } : undefined;\n }\n if (call && callLeaf(call) === \"money\") {\n const currency = stringValue(call.arguments[0]);\n const scale = call.arguments[1] ? numberValue(call.arguments[1]) : 2;\n return (call.arguments.length === 1 || call.arguments.length === 2) && currency && /^[A-Z]{3}$/.test(currency) && validScale(scale)\n ? { Money: { currency, scale } }\n : undefined;\n }\n if (!call || !validArgDescriptor(node)) return undefined;\n switch (callLeaf(call)) {\n case \"cursor\": return \"Cursor\";\n case \"id\": return \"Id\";\n case \"principal\": return \"Principal\";\n case \"ref\": {\n if (!tables) return \"Id\";\n const path = call.arguments[0] && staticMemberPath(call.arguments[0]);\n const table = path && tables.get(path);\n return table ? { Ref: { table: table.name } } : undefined;\n }\n case \"int\": return \"Int\";\n case \"bool\": return \"Bool\";\n case \"time\": return \"Time\";\n case \"text\": return { Text: { max: numberValue(call.arguments[0]) } };\n case \"bytes\": return { Bytes: { max: numberValue(call.arguments[0]) } };\n case \"image\": return { Image: { max: numberValue(call.arguments[0]) } };\n case \"video\": return { Video: { max: numberValue(call.arguments[0]) } };\n case \"json\": return { Json: { max_bytes: numberValue(call.arguments[0]) } };\n default: return undefined;\n }\n}\n\nexport function lowerLegacyArgDescriptor(node: ts.Expression): unknown | undefined {\n const call = unwrapCall(node);\n if (!call) return undefined;\n const options = callLeaf(call) === \"list\" && objectOf(call.arguments[1]);\n const max = options && numberValue(property(options, \"max\"));\n return typeof max === \"number\" ? { List: { max } } : \"Scalar\";\n}\n\nfunction validArgDescriptor(node: ts.Expression): boolean {\n const call = unwrapCall(node);\n const name = call && callLeaf(call);\n if (!call || !name) return false;\n if ([\"cursor\", \"id\", \"principal\", \"int\", \"bool\", \"time\"].includes(name)) return call.arguments.length === 0;\n if ([\"text\", \"bytes\", \"image\", \"video\", \"json\"].includes(name)) {\n return call.arguments.length === 1 && validPositiveInteger(numberValue(call.arguments[0]));\n }\n if (name === \"ref\") return call.arguments.length === 1;\n if (name === \"optional\") return call.arguments.length === 1 && !!call.arguments[0] && validArgDescriptor(call.arguments[0]);\n if (name === \"enum\") {\n const variants = stringArray(call.arguments[0]);\n return call.arguments.length === 1 && validEnumVariants(variants);\n }\n if (name === \"decimal\") return call.arguments.length === 1 && validScale(numberValue(call.arguments[0]));\n if (name === \"money\") {\n const currency = stringValue(call.arguments[0]);\n const scale = call.arguments[1] ? numberValue(call.arguments[1]) : 2;\n return (call.arguments.length === 1 || call.arguments.length === 2) && !!currency && /^[A-Z]{3}$/.test(currency) && validScale(scale);\n }\n if (name === \"list\") return lowerArgDescriptor(node) !== undefined;\n return false;\n}\n\nfunction validateRootRefs(\n module: SchemaModule,\n root: ts.ObjectLiteralExpression,\n field: string,\n declarations: Map<string, ts.CallExpression>,\n diagnostics: FrontendDiagnostic[],\n): void {\n const object = objectOf(property(root, field));\n if (!object) {\n if (declarations.size > 0) diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", root, `schema() must list its ${field}`));\n return;\n }\n const included = new Set<string>();\n for (const entry of propertyEntries(object)) {\n const value = unwrapExpression(entry.value);\n const exported = ts.isIdentifier(value) ? value.text : undefined;\n if (!exported || !declarations.has(exported)) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_UNKNOWN_TABLE\", entry.node, `${field} entry ${entry.name} is not a named schema export`));\n } else if (entry.name !== exported) {\n diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", entry.node, `${field} entry ${entry.name} must use its export name ${exported}`));\n } else {\n included.add(exported);\n }\n }\n for (const [name, call] of declarations) {\n if (!included.has(name)) diagnostics.push(schemaDiagnostic(module, \"E_SCHEMA_INVALID\", call, `${field} omits exported ${name}`));\n }\n}\n\nfunction encodeValue(value: unknown, expected?: AuthoredType): Value | undefined {\n if (expected?.kind === \"optional\" && value === null) return \"Null\";\n const target = expected && requiredType(expected);\n if (target?.kind === \"bytes\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const entries = Object.entries(value as Record<string, unknown>);\n return entries.length === 1 && entries[0][0] === \"Bytes\"\n && typeof entries[0][1] === \"string\" && /^(?:[0-9a-f]{2})*$/.test(entries[0][1])\n ? { Bytes: entries[0][1] }\n : undefined;\n }\n if (value === null) return \"Null\";\n if (typeof value === \"boolean\") return { Bool: value };\n if (typeof value === \"number\") return { Int: value };\n if (typeof value === \"string\") return { String: value };\n if (Array.isArray(value)) {\n const itemExpected = target?.kind === \"list\" ? target.of : target?.kind === \"json\" ? target : undefined;\n const items = value.map((item) => encodeValue(item, itemExpected));\n return items.every((item): item is Value => item !== undefined) ? { Array: items } : undefined;\n }\n if (value && typeof value === \"object\" && Object.keys(value).length === 1\n && typeof (value as Record<string, unknown>).Bytes === \"string\"\n && /^(?:[0-9a-f]{2})*$/.test((value as Record<string, string>).Bytes)) {\n return target?.kind === \"json\" ? {\n Map: { Bytes: { String: (value as Record<string, string>).Bytes } },\n } : undefined;\n }\n const itemExpected = target?.kind === \"json\" ? target : undefined;\n const entries = Object.entries(value as Record<string, unknown>)\n .map(([key, item]) => [key, encodeValue(item, itemExpected)] as const);\n return entries.every((entry): entry is readonly [string, Value] => entry[1] !== undefined)\n ? { Map: Object.fromEntries(entries) }\n : undefined;\n}\n\nfunction ruleProvenance(key: unknown[]): \"Arg\" | \"Viewer\" | \"Const\" | \"Shape\" | \"Computed\" {\n if (key.some((item) => typeof item === \"object\" && item !== null\n && [\"Field\", \"OldField\", \"NextField\"].some((term) => term in item))) return \"Shape\";\n if (key.some((item) => item === \"Viewer\")) return \"Viewer\";\n if (key.every((item) => typeof item === \"object\" && item !== null && \"Literal\" in item)) return \"Const\";\n return \"Computed\";\n}\n\nfunction isPublicRule(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && \"Public\" in value;\n}\n\nfunction validScale(value: number | undefined): value is number {\n return value !== undefined && Number.isInteger(value) && value >= 0 && value <= 12;\n}\n\nfunction validEnumVariants(value: string[] | undefined): value is string[] {\n return !!value?.length && value.every((variant) => variant.length > 0) && new Set(value).size === value.length;\n}\n\nexport function invalidDescriptorRefusal(node: ts.Expression): { node: ts.Expression; message: string; rewrite: string } {\n const call = unwrapCall(node);\n const name = call && callLeaf(call);\n if (call && (name === \"optional\" || name === \"list\") && call.arguments[0]\n && lowerArgDescriptor(call.arguments[0]) === undefined) {\n return invalidDescriptorRefusal(call.arguments[0]);\n }\n const callee = call?.expression.getText() ?? \"t.text\";\n const sibling = (descriptor: string) => {\n const dot = callee.lastIndexOf(\".\");\n return `${dot >= 0 ? callee.slice(0, dot + 1) : \"t.\"}${descriptor}`;\n };\n if (name === \"decimal\") {\n const scale = correctedScale(numberValue(call!.arguments[0]));\n return { node, message: \"t.decimal(scale) requires an integer scale from 0 through 12\", rewrite: `${callee}(${scale})` };\n }\n if (name === \"money\") {\n const authored = stringValue(call!.arguments[0]);\n const currency = authored && /^[A-Za-z]{3}$/.test(authored) ? authored.toUpperCase() : \"USD\";\n const scale = call!.arguments[1] ? `, ${correctedScale(numberValue(call!.arguments[1]))}` : \"\";\n return {\n node,\n message: \"t.money(currency, scale?) requires an uppercase ISO-4217-shaped three-letter currency and a scale from 0 through 12\",\n rewrite: `${callee}(${JSON.stringify(currency)}${scale})`,\n };\n }\n if (name === \"enum\") {\n const variants = [...new Set((stringArray(call!.arguments[0]) ?? []).filter((variant) => variant.length > 0))];\n if (variants.length === 0) variants.push(\"value\");\n return {\n node,\n message: \"t.enum(variants) requires at least one unique, non-empty string variant\",\n rewrite: `${callee}(${JSON.stringify(variants)})`,\n };\n }\n const rewrites: Record<string, string> = {\n id: `${callee}()`, principal: `${callee}()`, int: `${callee}()`, bool: `${callee}()`, time: `${callee}()`,\n text: `${callee}(100)`, bytes: `${callee}(100)`, image: `${callee}(5000000)`, video: `${callee}(50000000)`, json: `${callee}(1000)`, ref: `${callee}(table)`,\n optional: `${callee}(${sibling(\"text\")}(100))`,\n list: `${callee}(${sibling(\"text\")}(100), { max: 10 })`,\n };\n return {\n node,\n message: name ? `t.${name} arguments do not form a valid descriptor` : \"column type must be a t.* descriptor\",\n rewrite: rewrites[name ?? \"\"] ?? `${sibling(\"text\")}(100)`,\n };\n}\n\nexport function invalidNativeDescriptorRefusal(node: ts.Expression): ReturnType<typeof invalidDescriptorRefusal> | undefined {\n const call = unwrapCall(node);\n if (!call || !nativeDescriptorName(call)) return undefined;\n return invalidDescriptorRefusal(node);\n}\n\nfunction nativeDescriptorName(call: ts.CallExpression): string | undefined {\n const name = callLeaf(call);\n if (!name || ![\"id\", \"principal\", \"text\", \"bytes\", \"image\", \"video\", \"int\", \"bool\", \"time\", \"ref\", \"json\", \"optional\", \"list\", \"enum\", \"decimal\", \"money\"].includes(name)\n || !ts.isPropertyAccessExpression(call.expression)) return undefined;\n const owner = call.expression.expression.getText();\n if (owner === \"t\" || owner.endsWith(\".t\")) return name;\n for (const statement of call.getSourceFile().statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)\n || statement.moduleSpecifier.text !== \"snapback2\") continue;\n const bindings = statement.importClause?.namedBindings;\n if (bindings && ts.isNamedImports(bindings) && bindings.elements.some((item) =>\n (item.propertyName?.text ?? item.name.text) === \"t\" && item.name.text === owner)) return name;\n }\n return undefined;\n}\n\nfunction correctedScale(value: number | undefined): number {\n return value === undefined || !Number.isFinite(value) ? 2 : Math.max(0, Math.min(12, Math.trunc(value)));\n}\n\nfunction validPositiveInteger(value: number | undefined): value is number {\n return value !== undefined && Number.isInteger(value) && value > 0 && value <= 0xffff_ffff;\n}\n\nfunction validateRecordShape(\n module: SchemaModule,\n object: ts.ObjectLiteralExpression,\n label: string,\n code: \"E_SCHEMA_INVALID\" | \"E_SCHEMA_INDEX_OPTION\" | \"E_SCHEMA_CONSTRAINT\" | \"E_SCHEMA_MAINTAIN\" | \"E_RULE_INVALID\",\n diagnostics: FrontendDiagnostic[],\n): void {\n if (propertyEntries(object).length !== object.properties.length) {\n diagnostics.push(schemaDiagnostic(module, code, object, `${label} uses an unsupported spread, method, or computed property`));\n }\n}\n\nfunction validateKnownKeys(\n module: SchemaModule,\n object: ts.ObjectLiteralExpression,\n allowed: string[],\n label: string,\n code: \"E_SCHEMA_INVALID\" | \"E_SCHEMA_INDEX_OPTION\" | \"E_SCHEMA_CONSTRAINT\" | \"E_SCHEMA_MAINTAIN\" | \"E_RULE_INVALID\",\n diagnostics: FrontendDiagnostic[],\n): void {\n validateRecordShape(module, object, label, code, diagnostics);\n for (const entry of propertyEntries(object)) {\n if (!allowed.includes(entry.name)) {\n diagnostics.push(schemaDiagnostic(module, code, entry.node, `${label} has unknown option ${entry.name}; use ${allowed.join(\", \")}`));\n }\n }\n}\n\nfunction schemaDiagnostic(\n module: SchemaModule,\n code: \"E_SCHEMA_RESERVED\" | \"E_SCHEMA_ID_RESERVED\" | \"E_SCHEMA_UNKNOWN_TABLE\" | \"E_SCHEMA_INDEX_COLUMN\" | \"E_SCHEMA_ASSET_MAINTAIN\"\n | \"E_SCHEMA_INDEX_OPTION\" | \"E_SCHEMA_CONSTRAINT\" | \"E_SCHEMA_MAINTAIN\" | \"E_SCHEMA_DEFAULT_EXPORT\"\n | \"E_SCHEMA_COLUMN\" | \"E_SCHEMA_INVALID\" | \"E_RULE_INVALID\",\n node: ts.Node,\n message: string,\n replacement?: string,\n): FrontendDiagnostic {\n const rewrite = replacement ?? (code === \"E_SCHEMA_ID_RESERVED\"\n ? \"columns: {}\"\n : code === \"E_SCHEMA_CONSTRAINT\"\n ? \"{ appendOnly: true }\"\n : code === \"E_SCHEMA_INDEX_OPTION\"\n ? \"indexes: {}\"\n : code === \"E_SCHEMA_MAINTAIN\" || code === \"E_SCHEMA_ASSET_MAINTAIN\"\n ? \"maintains: []\"\n : schemaDeclarationRewrite(node));\n return diagnostic(module, code, node, message, rewrite);\n}\n\nfunction ruleDiagnostic(module: SchemaModule, node: ts.Node, message: string): FrontendDiagnostic {\n return diagnostic(module, \"E_RULE_INVALID\", node, message, \"rule.deny()\");\n}\n\nfunction schemaDeclarationRewrite(node: ts.Node): string {\n let current: ts.Node | undefined = node;\n while (current) {\n if (ts.isVariableDeclaration(current) && ts.isIdentifier(current.name)) {\n const call = current.initializer && unwrapCall(current.initializer);\n const kind = call && callLeaf(call);\n const callee = call?.expression.getText() ?? kind;\n if (kind === \"channel\") {\n const prefix = callee?.endsWith(\".channel\") ? callee.slice(0, -\"channel\".length) : \"\";\n return `export const ${current.name.text} = ${callee}({ args: {}, publish: ${prefix}rule.allow(), subscribe: ${prefix}rule.allow(), ttlMs: 4000 });`;\n }\n if (kind === \"table\") {\n const name = current.name.text.startsWith(\"_\") ? \"rows\" : current.name.text;\n return `export const ${name} = ${callee}({ columns: {} });`;\n }\n }\n if (ts.isExportAssignment(current)) {\n const call = unwrapCall(current.expression);\n return `export default ${call?.expression.getText() ?? \"schema\"}({ tables: {} });`;\n }\n current = current.parent;\n }\n return \"export default schema({ tables: {} });\";\n}\n", "{\n \"systemPrincipalId\": \"system\",\n \"retentionPolicies\": [\"until-revoked\", \"delivered-history\"],\n \"valueModelVersion\": \"i53-codepoint-bytes-v2\"\n}\n", "export type ProgramKind = \"Query\" | \"Mutation\";\nexport type Provenance = \"Arg\" | \"Viewer\" | \"Const\" | \"Shape\" | \"Computed\";\nexport type Order = \"Asc\" | \"Desc\";\nexport type RetentionPolicy = \"until-revoked\" | \"delivered-history\";\n\nimport coreIrContract from \"../../../crates/snapback2-core/ir-contract.json\" with { type: \"json\" };\n\nexport const IR_CONTRACT = Object.freeze({\n systemPrincipalId: coreIrContract.systemPrincipalId,\n retentionPolicies: coreIrContract.retentionPolicies as readonly RetentionPolicy[],\n});\n\nexport type Value =\n | \"Null\"\n | { Bool: boolean }\n | { Int: number }\n | { String: string }\n | { Id: string }\n | { Bytes: string }\n | { Array: Value[] }\n | { Row: Record<string, Value> }\n | { Map: Record<string, Value> };\n\nexport type Expr =\n | { Literal: Value }\n | { Variable: string }\n | { Input: \"Viewer\" | \"Now\" | \"NewId\" | \"ReadTime\" }\n | { Field: { base: Expr; name: string } }\n | { Array: Expr[] }\n | { Object: Record<string, Expr> }\n | { Binary: { op: string; left: Expr; right: Expr } }\n | { Unary: { op: \"Not\" | \"Neg\"; value: Expr } }\n | { Builtin: { builtin: string | Record<string, unknown>; args: Expr[] } }\n | { Get: Read }\n | { Exists: Read }\n | { Scan: Scan };\n\nexport type Read = {\n site: string;\n table: string;\n index: string;\n key: Expr[];\n provenance: Provenance;\n};\n\nexport type Scan = {\n site: string;\n table: string;\n index: string;\n prefix: Expr[];\n order: Order;\n take: { Literal: number } | { Arg: { name: string; max: number } };\n after: Expr | null;\n before: Expr | null;\n range: { gt: Expr | null; gte: Expr | null; lt: Expr | null; lte: Expr | null } | null;\n opaque_cursor?: boolean;\n merge_site?: string | null;\n provenance: Provenance;\n};\n\nexport type LoopDomain =\n | { Page: Scan }\n | { LiteralRange: { start: number; end_exclusive: number } }\n | { ArgList: { name: string; max: number } }\n | { DerivedArray: { value: Expr; max: number; bound_source: string } }\n | {\n Recurse: {\n site: string;\n table: string;\n index: string;\n seed: Expr;\n next_field: string;\n depth: number;\n fanout: number;\n provenance: Provenance;\n };\n };\n\nexport type Stmt =\n | { Const: { name: string; value: Expr } }\n | { Let: { name: string; value: Expr } }\n | { Assign: { name: string; value: Expr } }\n | { Push: { target: string; value: Expr } }\n | { If: { condition: Expr; then_body: Stmt[]; else_body: Stmt[] } }\n | { For: { binding: string; domain: LoopDomain; body: Stmt[] } }\n | { Require: { condition: Expr; code: string } }\n | { Insert: { table: string; row: Expr } }\n | { Update: { table: string; key: Expr; patch: Expr } }\n | { Upsert: { table: string; key: Expr; row: Expr } }\n | { Delete: { table: string; key: Expr } }\n | { Emit: { effect: string; payload: Expr } }\n | { Return: Expr }\n | \"Break\"\n | \"Continue\";\n\nexport type ArgType =\n | \"Cursor\"\n | \"Id\"\n | \"Principal\"\n | { Ref: { table: string } }\n | \"Int\"\n | \"Bool\"\n | \"Time\"\n | \"Scalar\"\n | { Text: { max: number } }\n | { Bytes: { max: number } }\n | { Image: { max: number } }\n | { Video: { max: number } }\n | { Json: { max_bytes: number } }\n | { Optional: ArgType }\n | { List: { of: ArgType; max: number } }\n | { Enum: { variants: string[] } }\n | { Decimal: { scale: number } }\n | { Money: { currency: string; scale: number } };\n\nexport type Program = {\n name: string;\n kind: ProgramKind;\n args: Record<string, ArgType>;\n read_time_granularity_ms: number | null;\n result_page_site?: string | null;\n body: Stmt[];\n};\n\nexport type Span = {\n file: string;\n start: number;\n end: number;\n line: number;\n column: number;\n};\n\nexport type DiagnosticCode =\n | \"E_UNBOUND_SCAN\"\n | \"E_UNBOUND_LOOP\"\n | \"E_UNBOUND_COUNT\"\n | \"E_STRUCTURAL_COUNT\"\n | \"E_AMBIENT_TIME\"\n | \"E_OPAQUE\"\n | \"E_BOUND\"\n | \"E_ARGS_SPREAD\"\n | \"E_ARGS_DESCRIPTOR\"\n | \"E_ARGS_TYPE\"\n | \"E_ARGS_CURSOR_INDEX\"\n | \"E_ARGS_CURSOR_SHAPE\"\n | \"E_ARGS_ID_SCALAR\"\n | \"E_ARGS_ID_TEXT\"\n | \"E_OP_INVALID\"\n | \"E_OP_NONE\"\n | \"E_OP_RESERVED\"\n | \"E_OP_MODULE_BASENAME\"\n | \"E_PROVENANCE_AMBIGUOUS\"\n | \"E_DIAG_TRUNCATED\"\n | \"E_SCHEMA_RESERVED\"\n | \"E_SCHEMA_ID_RESERVED\"\n | \"E_SCHEMA_UNKNOWN_TABLE\"\n | \"E_SCHEMA_INDEX_COLUMN\"\n | \"E_SCHEMA_ASSET_MAINTAIN\"\n | \"E_SCHEMA_ASSET_SEED\"\n | \"E_SCHEMA_INDEX_OPTION\"\n | \"E_SCHEMA_CONSTRAINT\"\n | \"E_SCHEMA_MAINTAIN\"\n | \"E_SCHEMA_DEFAULT_EXPORT\"\n | \"E_SCHEMA_COLUMN\"\n | \"E_SCHEMA_INVALID\"\n | \"E_RULE_INVALID\"\n | \"E_DECIMAL_SCALE\"\n | \"E_ENUM_VARIANT\"\n | \"E_SEED_INVALID\"\n | \"E_SEED_PERSONA\"\n | \"E_SEED_TABLE\"\n | \"E_SEED_ROW\"\n | \"E_SEED_SHAPE\"\n | \"E_SEED_VALUE\"\n | \"E_EFFECT_CLOSURE\"\n | \"E_EFFECT_TYPE\"\n | \"E_EFFECT_IMPORT\"\n | \"E_EFFECT_GRANT\"\n | \"E_EFFECT_THEN_ARGS\"\n | \"E_EFFECT_UNKNOWN\"\n | \"E_EMIT_IN_QUERY\"\n | \"E_QUARRY_SYNTAX\"\n | \"E_QUARRY_UNKNOWN\"\n | \"E_QUARRY_AMBIGUOUS\"\n | \"E_QUARRY_UNSUPPORTED\"\n | \"E_QUARRY_PLACEMENT\"\n | \"E_QUARRY_TYPE\"\n | \"E_QUARRY_RETAIN\"\n | \"E_QUARRY_ONLY\";\n\nexport type RefusalFamily = \"bound\" | \"opaque\" | \"schema\" | \"rule\" | \"effect\" | \"args\" | \"op\" | \"input\" | \"quarry\";\n\nexport type FrontendDiagnostic = {\n code: DiagnosticCode;\n family: RefusalFamily;\n message: string;\n site: string;\n rule?: string;\n rewrite: string;\n guide: string;\n};\n\nexport type TableJson = {\n retain: RetentionPolicy;\n [key: string]: unknown;\n};\n\nexport type SchemaJson = {\n tables: Record<string, TableJson>;\n maintains: unknown[];\n channels: Record<string, unknown>;\n auth: { password: boolean; guests: boolean };\n effects: string[];\n};\n\nexport type EffectJson = {\n name: string;\n grants: string[];\n source: string;\n then: string | null;\n};\n\nexport type ProjectJson = {\n schema: SchemaJson;\n programs: Program[];\n effects: EffectJson[];\n};\n\nexport type SourceSite = { file: string; line: number; col: number };\nexport type QuarryGenerated = { file: string; generated: string; source: string };\n\nexport type ProjectResult =\n | { ok: true; project: ProjectJson; sources: Record<string, SourceSite>; apiDts: string; quarry: QuarryGenerated[]; ms: number }\n | { ok: false; diagnostics: FrontendDiagnostic[]; ms: number };\n\nexport type LowerResult =\n | { ok: true; programs: Program[] }\n | { ok: false; diagnostics: FrontendDiagnostic[] };\n", "import ts from \"typescript\";\nimport { diagnostic } from \"../diagnostics\";\nimport type { FrontendDiagnostic } from \"../ir\";\nimport { unwrapCall, unwrapExpression } from \"../syntax\";\nimport { callLeaf, objectOf, property, staticJson, stringValue } from \"./static\";\n\ntype SchemaModule = { sourceFile: ts.SourceFile; source: string; fileName: string };\ntype RuleSubject = { label: string; table?: string; columns: Record<string, unknown> };\ntype RuleTableShape = RuleSubject & { indexes: Record<string, { columns?: string[] }> };\n// @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 row-image terms and created-row probes are scoped to the mutation effect that defines them.\ntype RuleEffect = \"read\" | \"insert\" | \"update\" | \"delete\";\ntype RuleUse = { kind: \"table\"; effect: RuleEffect } | { kind: \"other\" };\nconst RULE_TYPE_REWRITE = \"declare authority axes as Principal and align rule terms with the referenced index columns\";\ntype RuleType =\n | { kind: \"principal\" }\n | { kind: \"id\" }\n | { kind: \"ref\"; table: string }\n | { kind: \"text\" }\n | { kind: \"int\" }\n | { kind: \"bool\" }\n | { kind: \"time\" }\n | { kind: \"bytes\" }\n | { kind: \"json\" }\n | { kind: \"enum\"; variants: string[] }\n | { kind: \"decimal\"; scale: number }\n | { kind: \"money\"; currency: string; scale: number }\n | { kind: \"optional\"; of: RuleType }\n | { kind: \"list\"; of: RuleType }\n | { kind: \"scalar\" }\n | { kind: \"null-literal\" }\n | { kind: \"text-literal\"; value: string }\n | { kind: \"int-literal\" }\n | { kind: \"bool-literal\" }\n | { kind: \"array-literal\"; values: RuleType[] }\n | { kind: \"json-literal\" };\n\n// @ref LLP 1001#6-identity-identityrs \u2014 Viewer comparisons are authority comparisons,\n// so their schema axis must be nominal Principal rather than an application row id.\nexport function validateRuleTypes(\n module: SchemaModule,\n tableCalls: Map<string, ts.CallExpression>,\n channelCalls: Map<string, ts.CallExpression>,\n tableJson: Record<string, unknown>,\n channelJson: Record<string, unknown>,\n diagnostics: FrontendDiagnostic[],\n): void {\n const catalog = ruleTableCatalog(tableJson);\n for (const [name, call] of tableCalls) {\n const config = objectOf(call.arguments[0]);\n const rules = config && objectOf(property(config, \"rules\"));\n const subject = catalog.get(name);\n for (const side of [\"read\", \"insert\", \"update\", \"delete\"] as const) {\n const node = rules && property(rules, side);\n if (node) validateRuleType(module, node, subject, { kind: \"table\", effect: side }, catalog, diagnostics);\n }\n if (config && subject) validateFinalExistsTypes(module, config, name, subject, catalog, diagnostics);\n }\n for (const [name, call] of channelCalls) {\n const config = objectOf(call.arguments[0]);\n const lowered = channelJson[name];\n const args = lowered && typeof lowered === \"object\" && !Array.isArray(lowered)\n ? (lowered as Record<string, unknown>).args\n : undefined;\n const subject: RuleSubject | undefined = args && typeof args === \"object\" && !Array.isArray(args)\n ? { label: `channel ${name}`, columns: args as Record<string, unknown> }\n : undefined;\n for (const side of [\"publish\", \"subscribe\"]) {\n const node = config && property(config, side);\n if (node) validateRuleType(module, node, subject, { kind: \"other\" }, catalog, diagnostics);\n }\n }\n}\n\nexport function validateMaintainRuleTypes(\n module: SchemaModule,\n node: ts.Expression | undefined,\n tableJson: Record<string, unknown>,\n diagnostics: FrontendDiagnostic[],\n): void {\n const value = node && unwrapExpression(node);\n if (!value || !ts.isArrayLiteralExpression(value)) return;\n const catalog = ruleTableCatalog(tableJson);\n for (const item of value.elements) {\n const config = objectOf(item);\n const readable = config && property(config, \"readable\");\n if (!readable) continue;\n const target = stringValue(property(config, \"into\"));\n validateRuleType(module, readable, target ? catalog.get(target) : undefined, { kind: \"other\" }, catalog, diagnostics);\n }\n}\n\nfunction ruleTableCatalog(tableJson: Record<string, unknown>): Map<string, RuleTableShape> {\n const catalog = new Map<string, RuleTableShape>();\n for (const [name, value] of Object.entries(tableJson)) {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) continue;\n const record = value as Record<string, unknown>;\n const columns = record.columns && typeof record.columns === \"object\" && !Array.isArray(record.columns)\n ? record.columns as Record<string, unknown>\n : {};\n const indexes = record.indexes && typeof record.indexes === \"object\" && !Array.isArray(record.indexes)\n ? record.indexes as Record<string, { columns?: string[] }>\n : {};\n catalog.set(name, { label: `table ${name}`, table: name, columns, indexes });\n }\n return catalog;\n}\n\nfunction validateRuleType(\n module: SchemaModule,\n node: ts.Expression,\n subject: RuleSubject | undefined,\n ruleUse: RuleUse,\n catalog: Map<string, RuleTableShape>,\n diagnostics: FrontendDiagnostic[],\n): void {\n const call = unwrapCall(node);\n const name = call && callLeaf(call);\n if (!call || !name) return;\n if (name === \"viewerIs\" && call.arguments.length === 1 && call.arguments[0]) {\n const field = stringValue(call.arguments[0]);\n if (field) {\n const actual = ruleFieldType(module, call.arguments[0], subject, field, diagnostics);\n if (actual && !compatible(actual, { kind: \"principal\" })) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n call.arguments[0],\n `${subject?.label ?? \"unknown rule subject\"}.${field} is ${ruleTypeLabel(actual)}; fields compared with rule.viewer must be Principal`,\n ));\n }\n }\n return;\n }\n if ((name === \"eq\" || name === \"ne\") && call.arguments.length === 2) {\n const left = call.arguments[0] && ruleTermType(module, call.arguments[0], subject, ruleUse, diagnostics);\n const right = call.arguments[1] && ruleTermType(module, call.arguments[1], subject, ruleUse, diagnostics);\n if (left && right && !compatible(left, right)) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n call,\n `rule.${name} compares ${ruleTypeLabel(left)} with ${ruleTypeLabel(right)}; rule terms must have compatible scalar types`,\n ));\n }\n return;\n }\n if (name === \"and\" || name === \"or\") {\n for (const item of call.arguments) validateRuleType(module, item, subject, ruleUse, catalog, diagnostics);\n return;\n }\n if (name === \"not\" && call.arguments[0]) {\n validateRuleType(module, call.arguments[0], subject, ruleUse, catalog, diagnostics);\n return;\n }\n if (name !== \"exists\" && name !== \"created\") return;\n if (name === \"created\" && !(ruleUse.kind === \"table\" && ruleUse.effect === \"insert\")) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n call,\n \"created-row probes are valid only in table insert rules\",\n ));\n }\n if (call.arguments.length !== 3) return;\n const probe = name;\n const target = call.arguments[0] && unwrapExpression(call.arguments[0]);\n const tableName = target && ts.isIdentifier(target) ? target.text : undefined;\n const indexName = stringValue(call.arguments[1]);\n const key = call.arguments[2] && unwrapExpression(call.arguments[2]);\n const targetShape = tableName ? catalog.get(tableName) : undefined;\n if (!tableName || !targetShape) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n call.arguments[0] ?? call,\n `rule.${probe} references unresolved table ${tableName ?? call.arguments[0]?.getText() ?? \"<missing>\"}`,\n ));\n return;\n }\n if (!indexName) return;\n const index = indexName ? targetShape?.indexes[indexName] : undefined;\n if (!index) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n call.arguments[1] ?? call,\n `rule.${probe} references unresolved index ${tableName}.${indexName}`,\n ));\n return;\n }\n if (!key || !ts.isArrayLiteralExpression(key)) return;\n const columns = index.columns;\n if (!Array.isArray(columns)) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n call.arguments[1] ?? call,\n `rule.${probe} index ${tableName}.${indexName} has an unresolved column list`,\n ));\n return;\n }\n if (key.elements.length !== columns.length) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n key,\n `rule.${probe} key for ${tableName}.${indexName} has ${key.elements.length} terms; expected ${columns.length}`,\n ));\n }\n for (const [position, term] of key.elements.entries()) {\n const column = columns[position];\n if (!column) continue;\n const expected = ruleTypeFromDescriptor(targetShape.columns[column]);\n if (!expected) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n term,\n `rule.${probe} index ${tableName}.${indexName} references unresolved column ${column}`,\n ));\n continue;\n }\n const actual = ruleTermType(module, term, subject, ruleUse, diagnostics);\n if (!actual || compatibleExists(\n actual,\n expected,\n tableName,\n column,\n ruleUse.kind === \"table\" ? subject?.table : undefined,\n term,\n )) continue;\n diagnostics.push(ruleTypeDiagnostic(\n module,\n term,\n `rule.${probe} term for ${tableName}.${indexName}.${column} is ${ruleTypeLabel(actual)}; expected ${ruleTypeLabel(expected)}`,\n ));\n }\n}\n\nfunction validateFinalExistsTypes(\n module: SchemaModule,\n config: ts.ObjectLiteralExpression,\n sourceTable: string,\n subject: RuleSubject,\n catalog: Map<string, RuleTableShape>,\n diagnostics: FrontendDiagnostic[],\n): void {\n const constraints = property(config, \"constraints\");\n const value = constraints && unwrapExpression(constraints);\n if (!value || !ts.isArrayLiteralExpression(value)) return;\n for (const item of value.elements) {\n const constraint = objectOf(item);\n const finalNode = constraint && property(constraint, \"finalExistsOnInsert\");\n const finalExists = finalNode && objectOf(finalNode);\n if (!finalExists) continue;\n const tableNode = property(finalExists, \"table\");\n const tableName = stringValue(tableNode);\n if (!tableName) continue;\n const target = catalog.get(tableName);\n if (!target) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n tableNode ?? finalNode,\n `final-exists constraint references unknown table ${tableName}`,\n ));\n continue;\n }\n const indexNode = property(finalExists, \"index\");\n const indexName = stringValue(indexNode);\n if (!indexName) continue;\n const index = target.indexes[indexName];\n if (!index) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n indexNode ?? finalNode,\n `final-exists constraint references unknown index ${tableName}.${indexName}`,\n ));\n continue;\n }\n const keyNode = property(finalExists, \"key\");\n const key = keyNode && unwrapExpression(keyNode);\n if (!key || !ts.isArrayLiteralExpression(key)) continue;\n const columns = index.columns;\n if (!Array.isArray(columns)) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n indexNode ?? finalNode,\n `final-exists index ${tableName}.${indexName} has an unresolved column list`,\n ));\n continue;\n }\n if (key.elements.length !== columns.length) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n key,\n `final-exists key for ${tableName}.${indexName} has ${key.elements.length} terms; expected ${columns.length}`,\n ));\n }\n for (const [position, term] of key.elements.entries()) {\n const column = columns[position];\n if (!column) continue;\n const expected = ruleTypeFromDescriptor(target.columns[column]);\n if (!expected) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n term,\n `final-exists index ${tableName}.${indexName} references unresolved column ${column}`,\n ));\n continue;\n }\n const actual = ruleTermType(module, term, subject, { kind: \"other\" }, diagnostics);\n if (!actual || compatibleFinalExists(\n actual,\n expected,\n sourceTable,\n tableName,\n column,\n term,\n )) continue;\n diagnostics.push(ruleTypeDiagnostic(\n module,\n term,\n `final-exists term for ${tableName}.${indexName}.${column} is ${ruleTypeLabel(actual)}; expected ${ruleTypeLabel(expected)}`,\n ));\n }\n }\n}\n\nfunction ruleTermType(\n module: SchemaModule,\n node: ts.Expression,\n subject: RuleSubject | undefined,\n ruleUse: RuleUse,\n diagnostics: FrontendDiagnostic[],\n): RuleType | undefined {\n const value = unwrapExpression(node);\n if (ts.isPropertyAccessExpression(value)\n && value.expression.getText() === \"rule\"\n && value.name.text === \"viewer\") return { kind: \"principal\" };\n const call = unwrapCall(value);\n const name = call && callLeaf(call);\n if (call && name === \"field\" && call.arguments.length === 1 && call.arguments[0]) {\n const field = stringValue(call.arguments[0]);\n if (field) return ruleFieldType(module, call.arguments[0], subject, field, diagnostics);\n }\n if (call && (name === \"oldField\" || name === \"nextField\")\n && call.arguments.length === 1 && call.arguments[0]) {\n if (!(ruleUse.kind === \"table\" && ruleUse.effect === \"update\")) {\n diagnostics.push(ruleTypeDiagnostic(\n module,\n call,\n `${name === \"oldField\" ? \"old\" : \"next\"}-row fields are valid only in table update rules`,\n ));\n return undefined;\n }\n const field = stringValue(call.arguments[0]);\n if (field) return ruleFieldType(module, call.arguments[0], subject, field, diagnostics);\n }\n if (call && name === \"literal\" && call.arguments.length === 1 && call.arguments[0]) {\n const literal = staticJson(call.arguments[0]);\n if (literal !== undefined) return ruleLiteralType(literal);\n }\n return undefined;\n}\n\nfunction ruleFieldType(\n module: SchemaModule,\n node: ts.Expression,\n subject: RuleSubject | undefined,\n field: string,\n diagnostics: FrontendDiagnostic[],\n): RuleType | undefined {\n const kind = ruleTypeFromDescriptor(subject?.columns[field]);\n if (kind) return kind;\n diagnostics.push(ruleTypeDiagnostic(\n module, node,\n `rule references unknown or untyped field ${field} on ${subject?.label ?? \"its unresolved outer subject\"}`,\n ));\n return undefined;\n}\n\nfunction ruleTypeFromDescriptor(value: unknown): RuleType | undefined {\n if (value === \"Principal\") return { kind: \"principal\" };\n if (value === \"Id\") return { kind: \"id\" };\n if (value === \"Int\") return { kind: \"int\" };\n if (value === \"Bool\") return { kind: \"bool\" };\n if (value === \"Time\") return { kind: \"time\" };\n if (value === \"Scalar\") return { kind: \"scalar\" };\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const descriptor = value as Record<string, any>;\n if (descriptor.Ref && typeof descriptor.Ref.table === \"string\") return { kind: \"ref\", table: descriptor.Ref.table };\n if (descriptor.Text) return { kind: \"text\" };\n if (descriptor.Bytes) return { kind: \"bytes\" };\n if (descriptor.Json) return { kind: \"json\" };\n if (descriptor.Enum && Array.isArray(descriptor.Enum.variants)) {\n return { kind: \"enum\", variants: [...descriptor.Enum.variants] };\n }\n if (descriptor.Decimal && typeof descriptor.Decimal.scale === \"number\") {\n return { kind: \"decimal\", scale: descriptor.Decimal.scale };\n }\n if (descriptor.Money && typeof descriptor.Money.currency === \"string\" && typeof descriptor.Money.scale === \"number\") {\n return { kind: \"money\", currency: descriptor.Money.currency, scale: descriptor.Money.scale };\n }\n if (\"Optional\" in descriptor) {\n const inner = ruleTypeFromDescriptor(descriptor.Optional);\n return inner ? { kind: \"optional\", of: inner } : undefined;\n }\n if (descriptor.List) {\n const inner = ruleTypeFromDescriptor(descriptor.List.of ?? \"Scalar\");\n return inner ? { kind: \"list\", of: inner } : undefined;\n }\n return undefined;\n}\n\nfunction ruleLiteralType(value: unknown): RuleType {\n if (value === null) return { kind: \"null-literal\" };\n if (typeof value === \"boolean\") return { kind: \"bool-literal\" };\n if (typeof value === \"number\") return { kind: \"int-literal\" };\n if (typeof value === \"string\") return { kind: \"text-literal\", value };\n if (Array.isArray(value)) return { kind: \"array-literal\", values: value.map(ruleLiteralType) };\n return { kind: \"json-literal\" };\n}\n\nfunction compatible(left: RuleType, right: RuleType): boolean {\n if (sameRuleType(left, right)) return true;\n if (left.kind === \"optional\") return right.kind === \"null-literal\" || compatible(left.of, right);\n if (right.kind === \"optional\") return left.kind === \"null-literal\" || compatible(left, right.of);\n if (left.kind === \"text\" && right.kind === \"text-literal\") return true;\n if (right.kind === \"text\" && left.kind === \"text-literal\") return true;\n if (left.kind === \"enum\" && right.kind === \"text-literal\") return left.variants.includes(right.value);\n if (right.kind === \"enum\" && left.kind === \"text-literal\") return right.variants.includes(left.value);\n if ([\"int\", \"time\"].includes(left.kind) && right.kind === \"int-literal\") return true;\n if ([\"int\", \"time\"].includes(right.kind) && left.kind === \"int-literal\") return true;\n // Numeric rule literals at Decimal/Money schema positions are scaled and\n // range-checked by lowerTerm before IR is emitted.\n if ([\"decimal\", \"money\"].includes(left.kind) && right.kind === \"int-literal\") return true;\n if ([\"decimal\", \"money\"].includes(right.kind) && left.kind === \"int-literal\") return true;\n if (left.kind === \"bool\" && right.kind === \"bool-literal\") return true;\n if (right.kind === \"bool\" && left.kind === \"bool-literal\") return true;\n // The schema-position-aware lowerer validates the exact canonical tagged Bytes object.\n if (left.kind === \"bytes\" && right.kind === \"json-literal\") return true;\n if (right.kind === \"bytes\" && left.kind === \"json-literal\") return true;\n if (left.kind === \"json\" && jsonLiteral(right)) return true;\n if (right.kind === \"json\" && jsonLiteral(left)) return true;\n if (left.kind === \"array-literal\" && right.kind === \"array-literal\") {\n return left.values.every(jsonLiteral) && right.values.every(jsonLiteral);\n }\n if (left.kind === \"list\" && right.kind === \"array-literal\") {\n return right.values.every((value) => compatible(left.of, value));\n }\n if (right.kind === \"list\" && left.kind === \"array-literal\") {\n return left.values.every((value) => compatible(value, right.of));\n }\n return false;\n}\n\nfunction jsonLiteral(value: RuleType): boolean {\n if ([\"null-literal\", \"text-literal\", \"int-literal\", \"bool-literal\", \"json-literal\"].includes(value.kind)) {\n return true;\n }\n return value.kind === \"array-literal\" && value.values.every(jsonLiteral);\n}\n\nfunction compatibleExists(\n actual: RuleType,\n expected: RuleType,\n targetTable: string,\n targetColumn: string,\n subjectTable?: string,\n term?: ts.Expression,\n): boolean {\n const termCall = term && unwrapCall(term);\n return compatible(actual, expected)\n || (actual.kind === \"ref\" && actual.table === targetTable\n && expected.kind === \"id\" && targetColumn === \"id\")\n || (actual.kind === \"id\" && expected.kind === \"ref\"\n && expected.table === subjectTable\n && callLeaf(termCall) === \"field\"\n && stringValue(termCall?.arguments[0]) === \"id\");\n}\n\nfunction compatibleFinalExists(\n actual: RuleType,\n expected: RuleType,\n sourceTable: string,\n targetTable: string,\n targetColumn: string,\n term: ts.Expression,\n): boolean {\n if (compatibleExists(actual, expected, targetTable, targetColumn)) return true;\n const expectedRef = expected.kind === \"ref\"\n ? expected.table\n : expected.kind === \"optional\" && expected.of.kind === \"ref\"\n ? expected.of.table\n : undefined;\n const call = unwrapCall(term);\n return actual.kind === \"id\"\n && expectedRef === sourceTable\n && callLeaf(call) === \"field\"\n && stringValue(call?.arguments[0]) === \"id\";\n}\n\nfunction sameRuleType(left: RuleType, right: RuleType): boolean {\n if (left.kind !== right.kind) return false;\n if (left.kind === \"ref\" && right.kind === \"ref\") return left.table === right.table;\n if (left.kind === \"enum\" && right.kind === \"enum\") {\n return JSON.stringify(left.variants) === JSON.stringify(right.variants);\n }\n if (left.kind === \"decimal\" && right.kind === \"decimal\") return left.scale === right.scale;\n if (left.kind === \"money\" && right.kind === \"money\") {\n return left.currency === right.currency && left.scale === right.scale;\n }\n if (left.kind === \"optional\" && right.kind === \"optional\") return sameRuleType(left.of, right.of);\n if (left.kind === \"list\" && right.kind === \"list\") return sameRuleType(left.of, right.of);\n if (left.kind === \"array-literal\" && right.kind === \"array-literal\") {\n return left.values.length === right.values.length\n && left.values.every((value, index) => sameRuleType(value, right.values[index]!));\n }\n return true;\n}\n\nfunction ruleTypeLabel(value: RuleType): string {\n switch (value.kind) {\n case \"principal\": return \"Principal\";\n case \"id\": return \"Id\";\n case \"ref\": return `Ref<${value.table}>`;\n case \"text\": return \"Text\";\n case \"int\": return \"Int\";\n case \"bool\": return \"Bool\";\n case \"time\": return \"Time\";\n case \"bytes\": return \"Bytes\";\n case \"json\": return \"Json\";\n case \"enum\": return `Enum<${value.variants.join(\"|\")}>`;\n case \"decimal\": return `Decimal<${value.scale}>`;\n case \"money\": return `Money<${value.currency},${value.scale}>`;\n case \"optional\": return `Optional<${ruleTypeLabel(value.of)}>`;\n case \"list\": return `List<${ruleTypeLabel(value.of)}>`;\n case \"scalar\": return \"Scalar\";\n case \"null-literal\": return \"null literal\";\n case \"text-literal\": return `text literal ${JSON.stringify(value.value)}`;\n case \"int-literal\": return \"integer literal\";\n case \"bool-literal\": return \"boolean literal\";\n case \"array-literal\": return \"array literal\";\n case \"json-literal\": return \"json literal\";\n }\n}\n\nfunction ruleTypeDiagnostic(\n module: SchemaModule,\n node: ts.Node,\n message: string,\n): FrontendDiagnostic {\n return diagnostic(module, \"E_RULE_INVALID\", node, message, RULE_TYPE_REWRITE);\n}\n", "import ts from \"typescript\";\nimport type { DiagnosticModule } from \"./diagnostics\";\nimport { propertyName, walk } from \"./syntax\";\n\ntype FunctionLike = ts.FunctionDeclaration | ts.ArrowFunction | ts.FunctionExpression;\ntype IdentifierBindingElement = ts.BindingElement & { name: ts.Identifier };\ntype DuplicateHandlerBinding = {\n property: \"args\" | \"ctx\";\n elements: IdentifierBindingElement[];\n};\n\n// @ref LLP 1002#2-the-authored-surface-the-snapback2-module \u2014 operation composites have one lexical handler binding; aliases are ordinary locals.\nexport function duplicateHandlerBinding(handler: FunctionLike): DuplicateHandlerBinding | undefined {\n const pattern = handler.parameters[0]?.name;\n if (!pattern || !ts.isObjectBindingPattern(pattern)) return undefined;\n const bindings = new Map<\"args\" | \"ctx\", IdentifierBindingElement[]>();\n for (const element of pattern.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const property = element.propertyName ? propertyName(element.propertyName) : element.name.text;\n if (property !== \"args\" && property !== \"ctx\") continue;\n const elements = bindings.get(property) ?? [];\n elements.push(element as IdentifierBindingElement);\n bindings.set(property, elements);\n }\n for (const [property, elements] of bindings) {\n if (elements.length > 1) return { property, elements };\n }\n return undefined;\n}\n\nexport function duplicateHandlerBindingRewrite(\n module: DiagnosticModule,\n handler: FunctionLike,\n duplicate: DuplicateHandlerBinding,\n): string {\n const parameter = handler.parameters[0];\n const body = handler.body;\n if (!parameter || !ts.isObjectBindingPattern(parameter.name) || !body) return module.source;\n const winner = duplicate.elements.at(-1)!;\n const winnerName = winner.name.text;\n const duplicateSet = new Set<ts.BindingElement>(duplicate.elements);\n const pattern = `{ ${parameter.name.elements\n .filter((element) => !duplicateSet.has(element) || element === winner)\n .map((element) => element.getText(module.sourceFile))\n .join(\", \")} }`;\n const aliases = duplicate.elements.slice(0, -1)\n .map((element) => element.name.text)\n .filter((name) => name !== winnerName)\n .map((name) => `const ${name} = ${winnerName};`)\n .join(\" \");\n const edits: Array<{ start: number; end: number; text: string }> = [{\n start: parameter.name.getStart(module.sourceFile),\n end: parameter.name.getEnd(),\n text: pattern,\n }];\n if (ts.isBlock(body)) {\n const bodyStart = body.getStart(module.sourceFile) + 1;\n edits.push({ start: bodyStart, end: bodyStart, text: ` ${aliases}` });\n } else {\n edits.push({\n start: body.getStart(module.sourceFile),\n end: body.getEnd(),\n text: `{ ${aliases} return ${body.getText(module.sourceFile)}; }`,\n });\n }\n let rewritten = module.source;\n for (const edit of edits.sort((left, right) => right.start - left.start)) {\n rewritten = `${rewritten.slice(0, edit.start)}${edit.text}${rewritten.slice(edit.end)}`;\n }\n return rewritten;\n}\n\nexport function nestedHandlerBinding(handler: FunctionLike): ts.BindingElement | undefined {\n const pattern = handler.parameters[0]?.name;\n return pattern && ts.isObjectBindingPattern(pattern)\n ? pattern.elements.find((element) => !ts.isIdentifier(element.name))\n : undefined;\n}\n\nexport function nestedHandlerDestructuringRewrite(module: DiagnosticModule, handler: FunctionLike): string {\n const parameter = handler.parameters[0];\n const body = handler.body;\n if (!parameter || !ts.isObjectBindingPattern(parameter.name) || !body) return module.source;\n const occupied = new Set<string>();\n walk(handler, (node) => {\n if (ts.isIdentifier(node)) occupied.add(node.text);\n });\n const aliases = new Map<ts.BindingElement, string>();\n const declarations: string[] = [];\n for (const element of parameter.name.elements) {\n if (ts.isIdentifier(element.name)) continue;\n const property = element.propertyName ? propertyName(element.propertyName) : undefined;\n const base = property === \"args\" ? \"packed\" : `${property ?? \"composite\"}Packed`;\n let alias = base;\n for (let suffix = 2; occupied.has(alias); suffix += 1) alias = `${base}${suffix}`;\n occupied.add(alias);\n aliases.set(element, alias);\n const root = element.initializer\n ? `(${alias} ?? ${element.initializer.getText(module.sourceFile)})`\n : alias;\n collectDeclarations(element.name, root, module.sourceFile, declarations);\n }\n const edits: Array<{ start: number; end: number; text: string }> = [];\n for (const [element, alias] of aliases) {\n const property = element.propertyName ? element.propertyName.getText(module.sourceFile) : alias;\n const defaultText = element.initializer ? ` = ${element.initializer.getText(module.sourceFile)}` : \"\";\n edits.push({\n start: element.getStart(module.sourceFile),\n end: element.getEnd(),\n text: `${property}: ${alias}${defaultText}`,\n });\n }\n const prefix = declarations.map((declaration) => `const ${declaration};`).join(\" \");\n if (ts.isBlock(body)) {\n const bodyStart = body.getStart(module.sourceFile) + 1;\n edits.push({ start: bodyStart, end: bodyStart, text: ` ${prefix}` });\n } else {\n edits.push({\n start: body.getStart(module.sourceFile),\n end: body.getEnd(),\n text: `{ ${prefix} return ${body.getText(module.sourceFile)}; }`,\n });\n }\n let rewritten = module.source;\n for (const edit of edits.sort((left, right) => right.start - left.start)) {\n rewritten = `${rewritten.slice(0, edit.start)}${edit.text}${rewritten.slice(edit.end)}`;\n }\n return rewritten;\n}\n\nfunction collectDeclarations(\n name: ts.BindingName,\n access: string,\n sourceFile: ts.SourceFile,\n declarations: string[],\n): void {\n if (ts.isIdentifier(name)) {\n declarations.push(`${name.text} = ${access}`);\n return;\n }\n name.elements.forEach((element, index) => {\n if (!ts.isBindingElement(element)) return;\n if (element.dotDotDotToken) {\n for (const binding of bindingNames(element.name)) {\n declarations.push(`${binding} = __snapback2_rewrite_rest_binding_explicitly__()`);\n }\n return;\n }\n const selected = ts.isObjectBindingPattern(name)\n ? objectMemberAccess(access, element.propertyName, element.name, sourceFile)\n : `${access}[${index}]`;\n if (!selected) return;\n const value = element.initializer ? `(${selected} ?? ${element.initializer.getText(sourceFile)})` : selected;\n collectDeclarations(element.name, value, sourceFile, declarations);\n });\n}\n\nfunction objectMemberAccess(\n base: string,\n property: ts.PropertyName | undefined,\n name: ts.BindingName,\n sourceFile: ts.SourceFile,\n): string | undefined {\n if (!property) return ts.isIdentifier(name) ? `${base}.${name.text}` : undefined;\n if (ts.isIdentifier(property)) return `${base}.${property.text}`;\n if (ts.isComputedPropertyName(property)) return `${base}[${property.expression.getText(sourceFile)}]`;\n return `${base}[${property.getText(sourceFile)}]`;\n}\n\nfunction bindingNames(name: ts.BindingName): string[] {\n if (ts.isIdentifier(name)) return [name.text];\n return name.elements.flatMap((element) => ts.isBindingElement(element) ? bindingNames(element.name) : []);\n}\n", "import ts from \"typescript\";\nimport type { TableInfo } from \"../authored-types\";\nimport type { FunctionLike, LowerSourceOptions } from \"../compiler\";\nimport { snapbackCallName, stringArgument, unwrapCall } from \"../syntax\";\n\nexport type ModuleInfo = {\n sourceFile: ts.SourceFile;\n source: string;\n fileName: string;\n tables: Map<string, TableInfo>;\n effects: Map<string, string>;\n helpers: Map<string, FunctionLike>;\n};\n\nexport function inspectModule(\n sourceFile: ts.SourceFile,\n source: string,\n fileName: string,\n options: LowerSourceOptions,\n): ModuleInfo {\n const tables = new Map(options.tables ?? []);\n const effects = new Map(options.effects ?? []);\n const helpers = new Map<string, FunctionLike>();\n for (const statement of sourceFile.statements) {\n if (ts.isFunctionDeclaration(statement) && statement.name) {\n helpers.set(statement.name.text, statement);\n continue;\n }\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const name = declaration.name.text;\n const call = unwrapCall(declaration.initializer);\n const imported = call && snapbackCallName(call, sourceFile);\n const localHelper = call && ts.isIdentifier(call.expression) && [\"privateTable\", \"maintained\"].includes(call.expression.text)\n ? call.expression.text\n : undefined;\n const callee = imported ?? localHelper;\n if (!call || !callee) {\n if (ts.isArrowFunction(declaration.initializer) || ts.isFunctionExpression(declaration.initializer)) {\n helpers.set(name, declaration.initializer);\n }\n continue;\n }\n if (callee === \"table\" || callee === \"privateTable\" || callee === \"maintained\") {\n const tableName = stringArgument(call.arguments[0]) ?? name;\n const maintainedFrom = callee === \"maintained\" && ts.isIdentifier(call.arguments[1])\n ? call.arguments[1].text\n : undefined;\n tables.set(name, { name: tableName, private: callee === \"privateTable\", maintainedFrom });\n } else if (callee === \"effect\") {\n if (!effects.has(name)) effects.set(name, name);\n } else if (ts.isArrowFunction(declaration.initializer) || ts.isFunctionExpression(declaration.initializer)) {\n helpers.set(name, declaration.initializer);\n }\n }\n }\n return { sourceFile, source, fileName, tables, effects, helpers };\n}\n", "import ts from \"typescript\";\nimport { boundedDiagnostics, refuse, type DiagnosticModule } from \"./diagnostics\";\nimport type { FrontendDiagnostic } from \"./ir\";\nimport { replaceNode } from \"./syntax\";\n\ntype Module = { sourceFile: ts.SourceFile };\n\nexport function boundOperationDiagnostics(\n diagnostics: FrontendDiagnostic[],\n operations: Array<{ name: string; call: ts.CallExpression }>,\n module: Module,\n): FrontendDiagnostic[] {\n const assigned = new Set<number>();\n const result: FrontendDiagnostic[] = [];\n operations.forEach(({ name, call }) => {\n const selected = diagnostics.filter((item, index) => {\n const match = item.site.match(/:(\\d+):(\\d+)$/);\n if (!match) return false;\n const position = module.sourceFile.getPositionOfLineAndCharacter(Number(match[1]) - 1, Number(match[2]) - 1);\n if (position < call.getStart(module.sourceFile) || position > call.getEnd()) return false;\n assigned.add(index);\n return true;\n });\n result.push(...boundedDiagnostics(selected, 20, `refusals in operation ${name}`));\n });\n diagnostics.forEach((item, index) => {\n if (!assigned.has(index)) result.push(item);\n });\n return result;\n}\n\nexport function localConstructorShadow(sourceFile: ts.SourceFile): { name: string; node: ts.Node } | undefined {\n const constructors = new Set([\"query\", \"mutation\", \"effect\", \"channel\", \"table\", \"schema\", \"seed\", \"emit\"]);\n for (const statement of sourceFile.statements) {\n if (ts.isFunctionDeclaration(statement) && statement.name && constructors.has(statement.name.text)) {\n return { name: statement.name.text, node: statement };\n }\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && constructors.has(declaration.name.text)) return { name: declaration.name.text, node: declaration };\n }\n }\n return undefined;\n}\n\nexport function refuseReservedAuthCode(\n module: DiagnosticModule,\n node: ts.Expression | undefined,\n code: string,\n): void {\n if (!node || !code.startsWith(\"E_AUTH_\")) return;\n refuse(\n module,\n \"E_OP_RESERVED\",\n node,\n `application refusal code ${code} uses the reserved E_AUTH_* namespace`,\n replaceNode(module.source, node, '\"ACCESS_DENIED\"'),\n );\n}\n", "import type { Expr, LoopDomain, Program, Stmt } from \"./ir\";\n\n// @ref LLP 1011#b1-opaque-cursors \u2014 Paging provenance follows a scan or merge\n// through bindings and a one-to-one shape, independent of its retyped value.\n\ntype Origin = string | undefined;\ntype NodeStmt = Exclude<Stmt, string>;\n\nfunction node(statement: Stmt): statement is NodeStmt {\n return typeof statement === \"object\";\n}\n\nfunction builtinKind(value: string | Record<string, unknown>): [string, any] {\n if (typeof value === \"string\") return [value, undefined];\n const entry = Object.entries(value)[0];\n return entry ? [entry[0], entry[1]] : [\"\", undefined];\n}\n\nfunction expressionOrigin(expr: Expr, bindings: Map<string, Origin>): Origin {\n if (\"Variable\" in expr) return bindings.get(expr.Variable);\n if (\"Scan\" in expr && expr.Scan.opaque_cursor) return expr.Scan.merge_site ?? expr.Scan.site;\n if (\"Builtin\" in expr) {\n const [kind, data] = builtinKind(expr.Builtin.builtin);\n if (kind === \"DedupeById\") return data?.site;\n if ([\"Slice\", \"Sort\"].includes(kind)) {\n return expr.Builtin.args[0] && expressionOrigin(expr.Builtin.args[0], bindings);\n }\n }\n return undefined;\n}\n\nfunction domainOrigin(domain: LoopDomain, bindings: Map<string, Origin>): Origin {\n if (\"Page\" in domain && domain.Page.opaque_cursor) return domain.Page.merge_site ?? domain.Page.site;\n if (\"DerivedArray\" in domain) return expressionOrigin(domain.DerivedArray.value, bindings);\n return undefined;\n}\n\nfunction directPushTargets(body: Stmt[]): string[] {\n return body.flatMap((statement) => node(statement) && \"Push\" in statement ? [statement.Push.target] : []);\n}\n\n/**\n * Tracks one result page through IR bindings and one-to-one shape loops. A\n * branch-local return, nesting, or consumption by an authored loop is not a\n * result-page certificate.\n */\nexport function resultPageSite(program: Program): string | undefined {\n const bindings = new Map<string, Origin>();\n const returned: Origin[] = [];\n let conditionalReturn = false;\n\n const containsReturn = (body: Stmt[]): boolean => body.some((statement) => node(statement) && (\n \"Return\" in statement\n || (\"If\" in statement && (containsReturn(statement.If.then_body) || containsReturn(statement.If.else_body)))\n || (\"For\" in statement && containsReturn(statement.For.body))));\n\n for (const statement of program.body) {\n if (!node(statement)) continue;\n if (\"Const\" in statement || \"Let\" in statement || \"Assign\" in statement) {\n const binding = \"Const\" in statement ? statement.Const : \"Let\" in statement ? statement.Let : statement.Assign;\n bindings.set(binding.name, expressionOrigin(binding.value, bindings));\n } else if (\"For\" in statement) {\n if (containsReturn(statement.For.body)) conditionalReturn = true;\n const origin = domainOrigin(statement.For.domain, bindings);\n const targets = directPushTargets(statement.For.body);\n if (origin && targets.length === 1) bindings.set(targets[0]!, origin);\n } else if (\"If\" in statement) {\n if (containsReturn(statement.If.then_body) || containsReturn(statement.If.else_body)) {\n conditionalReturn = true;\n }\n } else if (\"Return\" in statement) {\n returned.push(expressionOrigin(statement.Return, bindings));\n }\n }\n return !conditionalReturn && returned.length === 1 ? returned[0] : undefined;\n}\n\nexport function attachResultPageSite(program: Program): Program {\n const site = program.kind === \"Query\" ? resultPageSite(program) : undefined;\n return site ? { ...program, result_page_site: site } : program;\n}\n", "import ts from \"typescript\";\nimport { expandArgumentObject } from \"../args\";\nimport { diagnostic } from \"../diagnostics\";\nimport type { EffectJson, FrontendDiagnostic } from \"../ir\";\nimport { hasExport, staticMemberPath, unwrapCall, unwrapExpression, walk } from \"../syntax\";\nimport { callLeaf, moduleJsonConstants, objectOf, property, staticJson, stringArray } from \"./static\";\n\n// @ref LLP 1003#1-authoring \u2014 effects carry validated grants, closed ES2020 source, and an optional typed then mutation.\n\nexport type SourceModule = {\n moduleName: string;\n fileName: string;\n source: string;\n sourceFile: ts.SourceFile;\n};\n\nexport type OperationDecl = {\n name: string;\n moduleName: string;\n exportName: string;\n kind: \"query\" | \"mutation\";\n call: ts.CallExpression;\n};\n\nexport type EffectCatalog = Map<string, { module: SourceModule; exportName: string; call: ts.CallExpression }>;\n\nexport function collectEffectCatalog(modules: SourceModule[]): EffectCatalog {\n const catalog: EffectCatalog = new Map();\n for (const module of modules) {\n for (const statement of module.sourceFile.statements) {\n if (!ts.isVariableStatement(statement) || !hasExport(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const call = unwrapCall(declaration.initializer);\n if (call && callLeaf(call) === \"effect\") {\n const name = `${module.moduleName}.${declaration.name.text}`;\n catalog.set(name, { module, exportName: declaration.name.text, call });\n }\n }\n }\n }\n return catalog;\n}\n\nexport function effectBindings(module: SourceModule, catalog: EffectCatalog): Map<string, string> {\n const bindings = new Map<string, string>();\n for (const [name, item] of catalog) {\n if (item.module.moduleName === module.moduleName) bindings.set(item.exportName, name);\n }\n for (const statement of module.sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)\n || !statement.moduleSpecifier.text.startsWith(\".\")) continue;\n const targetModule = moduleNameFromSpecifier(statement.moduleSpecifier.text);\n const imports = statement.importClause?.namedBindings;\n if (!imports) continue;\n if (ts.isNamespaceImport(imports)) {\n for (const [qualified, effect] of catalog) {\n if (effect.module.moduleName === targetModule) bindings.set(`${imports.name.text}.${effect.exportName}`, qualified);\n }\n continue;\n }\n for (const item of imports.elements) {\n const imported = item.propertyName?.text ?? item.name.text;\n const qualified = `${targetModule}.${imported}`;\n if (catalog.has(qualified)) bindings.set(item.name.text, qualified);\n }\n }\n return bindings;\n}\n\nexport function lowerEffects(\n catalog: EffectCatalog,\n operations: Map<string, OperationDecl>,\n): { effects: EffectJson[]; diagnostics: FrontendDiagnostic[] } {\n const effects: EffectJson[] = [];\n const diagnostics: FrontendDiagnostic[] = [];\n for (const [name, item] of [...catalog].sort(([left], [right]) => left.localeCompare(right))) {\n const lowered = lowerEffect(name, item.module, item.call, operations, diagnostics);\n if (lowered) effects.push(lowered);\n }\n return { effects, diagnostics };\n}\n\nfunction lowerEffect(\n name: string,\n module: SourceModule,\n call: ts.CallExpression,\n operations: Map<string, OperationDecl>,\n diagnostics: FrontendDiagnostic[],\n): EffectJson | undefined {\n const config = objectOf(call.arguments[0]);\n const grants = config && stringArray(property(config, \"grants\"));\n if (!config || !grants || grants.length === 0 || grants.some((grant) => !validGrant(grant))) {\n diagnostics.push(effectDiagnostic(module, \"E_EFFECT_GRANT\", call, \"grants must be a non-empty list of https:// or http://127.0.0.1 origins\"));\n return undefined;\n }\n const runNode = property(config, \"run\");\n const run = runNode && unwrapExpression(runNode);\n if (!run || (!ts.isArrowFunction(run) && !ts.isFunctionExpression(run))) {\n diagnostics.push(effectDiagnostic(module, \"E_EFFECT_CLOSURE\", config, \"effect run must be an arrow or function expression\"));\n return undefined;\n }\n const closure = validateClosure(module, run);\n if (closure) diagnostics.push(closure);\n\n let then: string | null = null;\n const thenNode = property(config, \"then\");\n if (thenNode) {\n const resolved = resolveOperation(module, thenNode, operations);\n if (!resolved || resolved.kind !== \"mutation\" || !validThenArgs(resolved.call)) {\n diagnostics.push(effectDiagnostic(\n module,\n \"E_EFFECT_THEN_ARGS\",\n thenNode,\n \"then must name a mutation with outboxId, effect, and result arguments matching run's result\",\n ));\n } else {\n then = resolved.name;\n }\n }\n if (closure || (thenNode && then === null)) return undefined;\n\n const transpiled = ts.transpileModule(`(${run.getText(module.sourceFile)})`, {\n compilerOptions: {\n target: ts.ScriptTarget.ES2020,\n module: ts.ModuleKind.None,\n removeComments: true,\n },\n }).outputText.trim().replace(/;$/, \"\");\n const constants = [...moduleJsonConstants(module.sourceFile)]\n .map(([constant, value]) => `const ${constant} = ${JSON.stringify(value)};`)\n .join(\" \");\n const source = constants ? `(() => { ${constants} return ${transpiled}; })()` : transpiled;\n return { name, grants, source, then };\n}\n\nfunction validateClosure(module: SourceModule, run: ts.ArrowFunction | ts.FunctionExpression): FrontendDiagnostic | undefined {\n const roots: ts.Node[] = [...run.parameters, run.body];\n let imported: ts.Node | undefined;\n for (const root of roots) {\n walk(root, (node) => {\n if (imported) return;\n if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === \"require\") imported = node;\n if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) imported = node;\n });\n }\n if (imported) return effectDiagnostic(module, \"E_EFFECT_IMPORT\", imported, \"effect run cannot import or require modules\");\n\n const bindings: Array<{ name: string; owner: ts.Node }> = [];\n for (const parameter of run.parameters) collectScopedBindings(parameter.name, run, bindings);\n walk(run.body, (node) => {\n if (ts.isVariableDeclaration(node)) collectScopedBindings(node.name, bindingOwner(node, run), bindings);\n if (isScopedFunction(node)) {\n for (const parameter of node.parameters) collectScopedBindings(parameter.name, node, bindings);\n if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) && node.name) {\n bindings.push({ name: node.name.text, owner: ts.isFunctionDeclaration(node) ? bindingOwner(node, run) : node });\n }\n }\n if (ts.isCatchClause(node) && node.variableDeclaration) collectScopedBindings(node.variableDeclaration.name, node, bindings);\n });\n const constants = moduleJsonConstants(module.sourceFile);\n const allowed = new Set([\n ...constants.keys(),\n \"fetch\", \"meta\", \"console\", \"JSON\", \"Math\", \"Date\", \"URL\", \"TextEncoder\", \"TextDecoder\",\n \"btoa\", \"atob\", \"setTimeout\", \"Promise\", \"Error\", \"crypto\", \"undefined\", \"NaN\", \"Infinity\",\n ]);\n let escaped: ts.Identifier | undefined;\n for (const root of roots) {\n walk(root, (node) => {\n if (escaped || !ts.isIdentifier(node) || !isReferenceIdentifier(node)) return;\n if (!allowed.has(node.text) && !bindings.some((binding) => binding.name === node.text && isWithin(node, binding.owner))) escaped = node;\n });\n }\n if (!escaped) return undefined;\n const spread = invalidConstantSpread(module.sourceFile, escaped.text, constants);\n return spread\n ? effectDiagnostic(module, \"E_EFFECT_CLOSURE\", spread, `effect JSON constant spread ${spread.expression.getText(module.sourceFile)} is not statically JSON`)\n : effectDiagnostic(module, \"E_EFFECT_CLOSURE\", escaped, `effect run closes over non-JSON value ${escaped.text}`);\n}\n\nfunction isScopedFunction(node: ts.Node): node is ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction | ts.MethodDeclaration {\n return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node);\n}\n\nfunction invalidConstantSpread(\n sourceFile: ts.SourceFile,\n name: string,\n constants: Map<string, unknown>,\n): ts.SpreadAssignment | undefined {\n let invalid: ts.SpreadAssignment | undefined;\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;\n const declaration = statement.declarationList.declarations.find((item) => ts.isIdentifier(item.name) && item.name.text === name);\n if (!declaration?.initializer) continue;\n walk(declaration.initializer, (node) => {\n if (invalid || !ts.isSpreadAssignment(node)) return;\n const value = staticJson(node.expression, constants);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) invalid = node;\n });\n }\n return invalid;\n}\n\nfunction collectScopedBindings(name: ts.BindingName, owner: ts.Node, output: Array<{ name: string; owner: ts.Node }>): void {\n if (ts.isIdentifier(name)) output.push({ name: name.text, owner });\n else for (const item of name.elements) if (ts.isBindingElement(item)) collectScopedBindings(item.name, owner, output);\n}\n\nfunction bindingOwner(node: ts.Node, fallback: ts.Node): ts.Node {\n let current = node.parent;\n while (current && current !== fallback) {\n if (ts.isBlock(current) || isScopedFunction(current) || ts.isCatchClause(current)) return current;\n current = current.parent;\n }\n return fallback;\n}\n\nfunction isWithin(node: ts.Node, owner: ts.Node): boolean {\n let current: ts.Node | undefined = node;\n while (current) {\n if (current === owner) return true;\n current = current.parent;\n }\n return false;\n}\n\nfunction isReferenceIdentifier(node: ts.Identifier): boolean {\n const parent = node.parent;\n if (ts.isPropertyAccessExpression(parent) && parent.name === node) return false;\n if (ts.isPropertyAssignment(parent) && parent.name === node && parent.initializer !== node) return false;\n if (ts.isMethodDeclaration(parent) && parent.name === node) return false;\n if (ts.isPropertySignature(parent) || ts.isTypeReferenceNode(parent) || ts.isTypeParameterDeclaration(parent)) return false;\n if (ts.isBindingElement(parent) && (parent.name === node || parent.propertyName === node)) return false;\n if (ts.isVariableDeclaration(parent) && parent.name === node) return false;\n if (ts.isParameter(parent) && parent.name === node) return false;\n if (ts.isFunctionDeclaration(parent) && parent.name === node) return false;\n return !isInsideType(node);\n}\n\nfunction isInsideType(node: ts.Node): boolean {\n let current: ts.Node | undefined = node.parent;\n while (current) {\n if (ts.isTypeNode(current)) return true;\n if (ts.isExpression(current) || ts.isStatement(current)) return false;\n current = current.parent;\n }\n return false;\n}\n\nfunction resolveOperation(module: SourceModule, node: ts.Expression, operations: Map<string, OperationDecl>): OperationDecl | undefined {\n const path = staticMemberPath(node);\n if (!path) return undefined;\n const local = !path.includes(\".\") ? operations.get(`${module.moduleName}.${path}`) : undefined;\n if (local) return local;\n for (const statement of module.sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)\n || !statement.moduleSpecifier.text.startsWith(\".\")) continue;\n const bindings = statement.importClause?.namedBindings;\n if (!bindings) continue;\n if (ts.isNamespaceImport(bindings)) {\n const prefix = `${bindings.name.text}.`;\n if (path.startsWith(prefix) && !path.slice(prefix.length).includes(\".\")) {\n return operations.get(`${moduleNameFromSpecifier(statement.moduleSpecifier.text)}.${path.slice(prefix.length)}`);\n }\n continue;\n }\n const item = bindings.elements.find((entry) => entry.name.text === path);\n if (!item) continue;\n const exported = item.propertyName?.text ?? item.name.text;\n return operations.get(`${moduleNameFromSpecifier(statement.moduleSpecifier.text)}.${exported}`);\n }\n return undefined;\n}\n\nfunction validThenArgs(call: ts.CallExpression): boolean {\n const args = objectOf(call.arguments[0]);\n if (!args) return false;\n const entries = expandArgumentObject(args).entries;\n if (entries.map((item) => item.name).sort().join(\",\") !== \"effect,outboxId,result\") return false;\n const descriptors = new Map(entries.map((item) => [item.name, callLeaf(item.value)]));\n return [\"id\", \"text\"].includes(descriptors.get(\"outboxId\") ?? \"\")\n && descriptors.get(\"effect\") === \"text\"\n && descriptors.has(\"result\");\n}\n\nfunction validGrant(grant: string): boolean {\n try {\n const url = new URL(grant);\n if (url.origin !== grant || url.username || url.password) return false;\n return url.protocol === \"https:\" || (url.protocol === \"http:\" && url.hostname === \"127.0.0.1\");\n } catch {\n return false;\n }\n}\n\nfunction moduleNameFromSpecifier(specifier: string): string {\n const part = specifier.split(\"/\").filter(Boolean).at(-1) ?? specifier;\n return part.replace(/\\.[cm]?[jt]s$/, \"\");\n}\n\nfunction effectDiagnostic(\n module: SourceModule,\n code: \"E_EFFECT_CLOSURE\" | \"E_EFFECT_IMPORT\" | \"E_EFFECT_GRANT\" | \"E_EFFECT_THEN_ARGS\",\n node: ts.Node,\n message: string,\n): FrontendDiagnostic {\n let current: ts.Node | undefined = node;\n while (current && !ts.isVariableDeclaration(current)) current = current.parent;\n const name = current && ts.isVariableDeclaration(current) && ts.isIdentifier(current.name)\n ? current.name.text\n : \"effectName\";\n const call = current && ts.isVariableDeclaration(current) && current.initializer\n ? unwrapCall(current.initializer)\n : undefined;\n const callee = call?.expression.getText(module.sourceFile) ?? \"effect\";\n const rewrite = `export const ${name} = ${callee}({ grants: [\"https://api.example.com\"], run: async (_payload: null) => null });`;\n return diagnostic(module, code, node, message, rewrite);\n}\n", "import { basename } from \"node:path\";\nimport type { Document, QuarryDiagnostic, RuleDecl, ScalarType, Site, TableCatalog, TableDecl } from \"./ast\";\nimport { buildCatalog } from \"./catalog\";\nimport { QuarryError } from \"./diagnostics\";\nimport { expandDocuments } from \"./expand\";\nimport { parseDocument } from \"./parser\";\nimport { emitPrograms } from \"./program\";\nimport { emitSchema } from \"./schema\";\nimport { whereRepairDiagnostics } from \"./where-repair\";\nimport type { FrontendDiagnostic, QuarryGenerated, SourceSite } from \"../ir\";\n\nexport type QuarryInput = { path: string; fileName: string; source: string };\nexport type QuarryVirtualModule = {\n path: string;\n fileName: string;\n source: string;\n authored: string;\n authoredSource: string;\n lineMap: Array<SourceSite | undefined>;\n};\nexport type QuarryCompileResult =\n | { ok: true; schema: QuarryVirtualModule; modules: QuarryVirtualModule[] }\n | { ok: false; diagnostics: FrontendDiagnostic[] };\n\n// @ref LLP 1004#what-default-binds \u2014 Quarry is a compiler front end whose\n// generated TypeScript exists only in memory and retains authored source sites.\nexport function compileQuarry(inputs: QuarryInput[]): QuarryCompileResult {\n const diagnostics: QuarryDiagnostic[] = [];\n let documents: Document[] = [];\n for (const input of inputs) {\n const parsed = parseDocument(input.fileName, input.source);\n documents.push(parsed.document);\n diagnostics.push(...parsed.diagnostics);\n }\n diagnostics.push(...placementDiagnostics(documents));\n if (diagnostics.length > 0) return { ok: false, diagnostics: diagnostics.map(frontend) };\n const expansion = expandDocuments(documents);\n documents = expansion.documents;\n diagnostics.push(...expansion.diagnostics);\n if (diagnostics.length > 0) return { ok: false, diagnostics: diagnostics.map(frontend) };\n\n let catalog: TableCatalog;\n try {\n materializeMaintains(documents);\n catalog = buildCatalog(documents);\n } catch (error) {\n return { ok: false, diagnostics: [frontend(caughtDiagnostic(error, inputs[0]?.fileName))] };\n }\n diagnostics.push(...whereRepairDiagnostics(documents, catalog));\n if (diagnostics.length > 0) return { ok: false, diagnostics: diagnostics.map(frontend) };\n\n const schemaDocument = documents.find((document) => basename(document.file) === \"schema.q\")!;\n const schemaInput = inputs.find((input) => input.fileName === schemaDocument.file)!;\n let schemaSource = \"\";\n try {\n schemaSource = emitSchema(documents, catalog, schemaDocument.file);\n } catch (error) {\n diagnostics.push(caughtDiagnostic(error, schemaDocument.file));\n }\n const moduleSources = new Map<string, string>();\n for (const document of documents.filter((item) => basename(item.file) !== \"schema.q\")) {\n let valid = true;\n for (const program of document.programs) {\n try {\n emitPrograms([program], catalog, document.file, document.effects);\n } catch (error) {\n valid = false;\n diagnostics.push(caughtDiagnostic(error, document.file));\n }\n }\n if (valid) moduleSources.set(document.file, emitPrograms(document.programs, catalog, document.file, document.effects));\n }\n if (diagnostics.length > 0) return { ok: false, diagnostics: diagnostics.map(frontend) };\n\n const schema = virtualModule(schemaInput.path.replace(/\\.q$/, \".ts\"), schemaDocument.file, schemaSource, schemaInput.source);\n const modules = documents\n .filter((document) => basename(document.file) !== \"schema.q\")\n .map((document) => {\n const input = inputs.find((item) => item.fileName === document.file)!;\n return virtualModule(input.path.replace(/\\.q$/, \".ts\"), document.file, moduleSources.get(document.file)!, input.source);\n });\n return { ok: true, schema, modules };\n}\n\nexport function remapVirtualDiagnostic(\n diagnostic: FrontendDiagnostic,\n virtual: QuarryVirtualModule,\n generatedTypeError = false,\n): FrontendDiagnostic {\n const site = parseSite(diagnostic.site);\n const authored = site && mapGeneratedLine(virtual, site.line);\n if (!authored) return diagnostic;\n return {\n ...diagnostic,\n site: `${authored.file}:${authored.line}:${authored.col}`,\n message: generatedTypeError ? `in code generated from ${authored.file}: ${diagnostic.message}` : diagnostic.message,\n rewrite: diagnostic.code === \"E_DECIMAL_SCALE\"\n ? quarryDecimalRewrite(virtual.authoredSource, authored.line, diagnostic.message)\n : generatedTypeError && diagnostic.message.includes(\"undefined\")\n ? \"add ! else CODE to assert the possibly absent Quarry value before using it here\"\n : virtual.authoredSource,\n };\n}\n\nexport function remapVirtualSource(site: SourceSite, virtual: QuarryVirtualModule): SourceSite {\n return mapGeneratedLine(virtual, site.line) ?? site;\n}\n\nexport function quarryInspection(modules: QuarryVirtualModule[]): QuarryGenerated[] {\n return modules.map((module) => ({ file: module.authored, generated: basename(module.path), source: module.source }));\n}\n\nfunction placementDiagnostics(documents: Document[]): QuarryDiagnostic[] {\n const diagnostics: QuarryDiagnostic[] = [];\n const schema = documents.find((document) => basename(document.file) === \"schema.q\");\n if (!schema) {\n diagnostics.push(placement(documents[0]?.file ?? \"snapback/schema.q\", 1, 1, \"a Quarry project requires snapback/schema.q\", \"create snapback/schema.q and move schema declarations into it\"));\n }\n for (const document of documents) {\n const isSchema = basename(document.file) === \"schema.q\";\n const declarationSite = document.tables[0]?.site ?? document.maintains[0]?.site ?? document.channels[0]?.site\n ?? (document.identity ? { file: document.file, line: 1, col: 1 } : undefined);\n if (!isSchema && declarationSite) diagnostics.push(placement(document.file, declarationSite.line, declarationSite.col, \"tables, maintains, channels, and use identity belong in schema.q\", \"move this declaration to snapback/schema.q\"));\n if (isSchema && document.shapes.length > 0) {\n const site = document.shapes[0]!.site;\n diagnostics.push(placement(document.file, site.line, site.col, \"shape declarations belong in an operations .q module, not schema.q\", \"move this shape declaration to snapback/<module>.q\"));\n }\n if (isSchema && (document.programs.length > 0 || document.effects.length > 0)) {\n const site = document.programs[0]?.site ?? document.effects[0]!.site;\n diagnostics.push(placement(document.file, site.line, site.col, \"schema.q holds declarations only; query, mutation, and effect declarations belong in a program module\", \"move this declaration to snapback/<module>.q\"));\n }\n if (!isSchema && document.programs.length === 0) diagnostics.push(placement(document.file, 1, 1, `${basename(document.file)} must declare at least one query or mutation`, \"add a query or mutation, or remove the empty module\"));\n const stem = basename(document.file).slice(0, -2);\n if (!/^[A-Za-z_$][A-Za-z0-9_$-]*$/.test(stem)) diagnostics.push(placement(document.file, 1, 1, `file stem ${stem} cannot become an API namespace`, \"rename the module to an identifier-like stem\"));\n }\n if (schema && schema.tables.length === 0) diagnostics.push(placement(schema.file, 1, 1, \"schema.q must declare at least one table\", \"add a table declaration\"));\n return diagnostics;\n}\n\nfunction materializeMaintains(documents: Document[]): void {\n const schema = documents.find((document) => basename(document.file) === \"schema.q\")!;\n // @ref LLP 1004#money-and-decimal-worked-out-2026-09-03 \u2014 a sum target inherits the source's exact numeric descriptor.\n for (const declaration of schema.maintains) {\n if (schema.tables.some((table) => table.name === declaration.name)) throw new QuarryError(declaration.site, `maintain target ${declaration.name} duplicates a table`);\n const source = schema.tables.find((table) => table.name === declaration.source);\n if (!source) throw new QuarryError(declaration.site, `maintain ${declaration.name} names unknown source table ${declaration.source}`);\n const columns = declaration.by.map((name) => {\n const sourceColumn = source.columns.find((column) => column.name === name);\n if (!sourceColumn) throw new QuarryError(declaration.site, `maintain ${declaration.name} names unknown source column ${declaration.source}.${name}`);\n return { name, type: structuredClone(sourceColumn.type), site: declaration.site };\n });\n if (declaration.aggregate === \"sum\") {\n const summed = source.columns.find((column) => column.name === declaration.column);\n if (!summed || ![\"int\", \"decimal\", \"money\"].includes(summed.type.kind)) {\n throw new QuarryError(declaration.site, `sum maintain ${declaration.name} requires an int, decimal, or money source column`);\n }\n }\n const summed = declaration.aggregate === \"sum\"\n ? source.columns.find((column) => column.name === declaration.column)!.type\n : { kind: \"int\", optional: false } satisfies ScalarType;\n columns.push({ name: \"value\", type: structuredClone(summed), site: declaration.site });\n const indexName = `by${declaration.by.map((column) => title(column.endsWith(\"Id\") && column.length > 2 ? column.slice(0, -2) : column)).join(\"\")}`;\n const deny = (effect: RuleDecl[\"effect\"]): RuleDecl => ({\n effect,\n bindings: [\"r\"],\n value: { kind: \"name\", name: \"deny\", site: declaration.site },\n site: declaration.site,\n });\n const assetGrouped = columns.some((column) => containsAsset(column.type));\n const target: TableDecl = {\n name: declaration.name,\n columns,\n // @ref LLP 1006#2a-one-asset-one-home-author-ruling-2026-09-01 \u2014 the\n // authored maintain refusal owns this error; do not also diagnose the\n // synthetic target index materialized only by the Quarry lowering.\n indexes: assetGrouped ? [] : [{ name: indexName, columns: [...declaration.by], unique: true, site: declaration.site }],\n rules: [declaration.read, deny(\"insert\"), deny(\"update\"), deny(\"delete\")],\n immutable: [],\n finalExists: [],\n site: declaration.site,\n };\n schema.tables.push(target);\n }\n}\n\nfunction containsAsset(type: ScalarType): boolean {\n if (type.kind === \"image\" || type.kind === \"video\") return true;\n return type.kind === \"list\" && containsAsset(type.item);\n}\n\nfunction virtualModule(path: string, authored: string, source: string, authoredSource: string): QuarryVirtualModule {\n const lineMap: Array<SourceSite | undefined> = [];\n let previous: SourceSite | undefined;\n for (const line of source.split(\"\\n\")) {\n const match = line.match(/\\/\\/ q:(.+):(\\d+):(\\d+)\\s*$/);\n if (match) previous = { file: match[1]!, line: Number(match[2]), col: Number(match[3]) };\n lineMap.push(previous);\n }\n return { path, fileName: path, source, authored, authoredSource, lineMap };\n}\n\nfunction frontend(item: QuarryDiagnostic): FrontendDiagnostic {\n return {\n code: item.code,\n family: \"quarry\",\n message: item.message,\n site: `${item.file}:${item.line}:${item.col}`,\n rewrite: `-- ${item.rewrite.replace(/\\n/g, \" \")}`,\n guide: item.guide,\n };\n}\n\nfunction caughtDiagnostic(error: unknown, file = \"snapback/schema.q\"): QuarryDiagnostic {\n return error instanceof QuarryError\n ? error.diagnostic\n : {\n file,\n line: 1,\n col: 1,\n code: \"E_QUARRY_UNKNOWN\",\n message: error instanceof Error ? error.message : String(error),\n rewrite: \"fix the named Quarry declaration\",\n guide: \"quarry/names\",\n };\n}\n\nfunction placement(file: string, line: number, col: number, message: string, rewrite: string): QuarryDiagnostic {\n return { file, line, col, code: \"E_QUARRY_PLACEMENT\", message, rewrite, guide: \"quarry/projects\" };\n}\n\nfunction parseSite(site: string): SourceSite | undefined {\n const match = site.match(/^(.*):(\\d+):(\\d+)$/);\n return match ? { file: match[1]!, line: Number(match[2]), col: Number(match[3]) } : undefined;\n}\n\nfunction mapGeneratedLine(module: QuarryVirtualModule, line: number): SourceSite | undefined {\n for (let offset = Math.min(line - 1, module.lineMap.length - 1); offset >= 0; offset -= 1) {\n const mapped = module.lineMap[offset];\n if (mapped) return mapped;\n }\n return undefined;\n}\n\nfunction quarryDecimalRewrite(source: string, line: number, message: string): string {\n const authoredLine = source.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\")[line - 1]?.trimEnd();\n return authoredLine ? `${authoredLine} -- ${message}` : `-- ${message}`;\n}\n\nfunction title(value: string): string { return value.length === 0 ? value : value[0]!.toUpperCase() + value.slice(1); }\n", "import type { QuarryCode, QuarryDiagnostic, Site } from \"./ast\";\n\nexport class QuarryError extends Error {\n readonly diagnostic: QuarryDiagnostic;\n\n constructor(site: Site, message: string, code: QuarryCode = \"E_QUARRY_UNKNOWN\", rewrite = \"fix the named Quarry declaration\", guide = guideFor(code)) {\n const expanded = site.expandedFrom;\n const contextualMessage = expanded\n ? `${message} (from a named shape used at ${expanded.file}:${expanded.line}:${expanded.col})`\n : message;\n super(contextualMessage);\n this.diagnostic = { ...site, code, message: contextualMessage, rewrite, guide };\n }\n}\n\nexport function refuse(site: Site, message: string, rewrite?: string): never {\n throw new QuarryError(site, message, \"E_QUARRY_UNKNOWN\", rewrite ?? \"fix the named Quarry declaration\");\n}\n\nexport function syntax(site: Site, message: string, rewrite = \"fix this Quarry declaration and rerun snapback2 check\"): never {\n throw new QuarryError(site, message, \"E_QUARRY_SYNTAX\", rewrite);\n}\n\nexport function unsupported(site: Site, construct: string, alternative: string): never {\n throw new QuarryError(\n site,\n `${construct} is not part of the Snapback 2 platform`,\n \"E_QUARRY_UNSUPPORTED\",\n alternative,\n );\n}\n\nexport function ambiguous(site: Site, message: string, rewrite: string): never {\n throw new QuarryError(site, message, \"E_QUARRY_AMBIGUOUS\", rewrite);\n}\n\nexport function placement(site: Site, message: string, rewrite: string): never {\n throw new QuarryError(site, message, \"E_QUARRY_PLACEMENT\", rewrite);\n}\n\nexport function typeError(site: Site, message: string, rewrite: string): never {\n throw new QuarryError(site, message, \"E_QUARRY_TYPE\", rewrite);\n}\n\nexport function retention(site: Site, message: string): never {\n throw new QuarryError(\n site,\n message,\n \"E_QUARRY_RETAIN\",\n \"retain until-revoked -- alternatively: retain delivered-history\",\n );\n}\n\nexport function formatDiagnostic(item: QuarryDiagnostic): string {\n return `${item.file}:${item.line}:${item.col} \u2014 ${item.message}`;\n}\n\nfunction guideFor(code: QuarryCode): string {\n if (code === \"E_QUARRY_SYNTAX\") return \"quarry/grammar\";\n if (code === \"E_QUARRY_AMBIGUOUS\") return \"quarry/indexes\";\n if (code === \"E_QUARRY_UNSUPPORTED\") return \"quarry/refusals\";\n if (code === \"E_QUARRY_PLACEMENT\") return \"quarry/projects\";\n if (code === \"E_QUARRY_TYPE\") return \"quarry/types\";\n if (code === \"E_QUARRY_RETAIN\") return \"quarry/grammar\";\n return \"quarry/names\";\n}\n", "import type { Document, Expr, IndexDecl, KeyPart, ScalarType, Site, TableCatalog, TableDecl } from \"./ast\";\nimport { ambiguous, refuse, typeError } from \"./diagnostics\";\n\nexport function buildCatalog(documents: Document[]): TableCatalog {\n const catalog: TableCatalog = new Map();\n for (const document of documents) {\n for (const table of document.tables) {\n if (catalog.has(table.name)) refuse(table.site, `duplicate table ${table.name}`);\n const columns = new Map<string, ScalarType>();\n for (const column of table.columns) {\n if (column.name === \"id\") refuse(column.site, `table ${table.name} gets id implicitly; remove the id column`);\n if (columns.has(column.name)) refuse(column.site, `duplicate column ${table.name}.${column.name}`);\n columns.set(column.name, column.type);\n }\n const indexes: IndexDecl[] = [{ name: \"byId\", columns: [\"id\"], unique: true, site: table.site }, ...table.indexes];\n const indexNames = new Set<string>();\n for (const index of indexes) {\n if (indexNames.has(index.name)) refuse(index.site, `duplicate index ${table.name}.${index.name}; name one ordering explicitly`);\n indexNames.add(index.name);\n if (index.columns.length === 0) refuse(index.site, `index ${table.name}.${index.name} needs at least one column`);\n if (new Set(index.columns).size !== index.columns.length) refuse(index.site, `index ${table.name}.${index.name} repeats a column`);\n for (const column of index.columns) {\n if (column !== \"id\" && !columns.has(column)) refuse(index.site, `index ${table.name}.${index.name} names unknown column ${column}`);\n }\n }\n const ruleEffects = new Set<string>();\n for (const rule of table.rules) {\n if (ruleEffects.has(rule.effect)) refuse(rule.site, `duplicate ${rule.effect} rule on ${table.name}`);\n ruleEffects.add(rule.effect);\n }\n catalog.set(table.name, { declaration: table, columns, indexes });\n }\n }\n for (const info of catalog.values()) {\n for (const column of info.declaration.columns) validateType(column.type, catalog, column.site);\n }\n for (const document of documents) {\n const channelNames = new Set<string>();\n for (const channel of document.channels) {\n if (channelNames.has(channel.name)) refuse(channel.site, `duplicate channel ${channel.name}`);\n channelNames.add(channel.name);\n validateArgs(channel.args, catalog);\n }\n const programNames = new Set<string>();\n for (const program of document.programs) {\n if (programNames.has(program.name)) refuse(program.site, `duplicate operation ${program.name}`);\n programNames.add(program.name);\n validateArgs(program.args, catalog);\n }\n }\n return catalog;\n}\n\nfunction validateArgs(args: Array<{ name: string; type: ScalarType; site: Site }>, catalog: TableCatalog): void {\n const names = new Set<string>();\n for (const arg of args) {\n if (names.has(arg.name)) refuse(arg.site, `duplicate argument ${arg.name}`);\n names.add(arg.name);\n validateType(arg.type, catalog, arg.site);\n }\n}\n\nfunction validateType(type: ScalarType, catalog: TableCatalog, site: Site): void {\n if (type.kind === \"text\" && type.max < 1) refuse(site, \"text bounds must be positive\");\n if (type.kind === \"text\" && type.min !== undefined && (type.min < 0 || type.min > type.max)) refuse(site, \"text minimum must be between zero and its maximum\");\n if ((type.kind === \"json\" || type.kind === \"bytes\") && type.max < 1) refuse(site, `${type.kind} bounds must be positive`);\n if ((type.kind === \"image\" || type.kind === \"video\")\n && (!Number.isInteger(type.max) || type.max < 1 || type.max > 0xffff_ffff)) {\n refuse(site, `${type.kind} byte bounds must be positive integers no larger than 4294967295`);\n }\n if (type.kind === \"enum\" && (type.variants.length === 0 || new Set(type.variants).size !== type.variants.length)) refuse(site, \"enum variants must be non-empty and unique\");\n if (type.kind === \"ref\" && !catalog.has(type.table)) refuse(site, `reference names unknown table ${type.table}`);\n if (type.kind === \"list\") {\n if (type.max < 1) refuse(site, \"list bounds must be positive\");\n validateType(type.item, catalog, site);\n }\n}\n\nexport function orderedTables(catalog: TableCatalog): TableDecl[] {\n // @ref LLP 1004#what-default-binds \u2014 the TypeScript lowering is static, so\n // `export var` declarations may retain reciprocal rule/reference graphs.\n return [...catalog.values()].map((info) => info.declaration);\n}\n\nfunction dependencies(table: TableDecl): string[] {\n const result = new Set<string>();\n for (const column of table.columns) collectTypeDependencies(column.type, result);\n for (const rule of table.rules) collectExprDependencies(rule.value, result);\n return [...result];\n}\n\nfunction collectTypeDependencies(type: ScalarType, into: Set<string>): void {\n if (type.kind === \"ref\") into.add(type.table);\n if (type.kind === \"list\") collectTypeDependencies(type.item, into);\n}\n\nfunction collectExprDependencies(expr: Expr, into: Set<string>): void {\n if (expr.kind === \"read\") {\n into.add(expr.table);\n for (const key of expr.keys) collectExprDependencies(key.value, into);\n if (expr.range?.cursor) collectExprDependencies(expr.range.cursor, into);\n if (expr.range?.where) collectExprDependencies(expr.range.where.predicate, into);\n } else if (expr.kind === \"merge\") {\n into.add(expr.table);\n if (expr.cursor) collectExprDependencies(expr.cursor, into);\n for (const lane of expr.lanes) {\n for (const value of lane.prefix) collectExprDependencies(value, into);\n if (lane.loop) collectExprDependencies(lane.loop.domain, into);\n }\n } else if (expr.kind === \"exists\" || expr.kind === \"created\") {\n collectExprDependencies(expr.read, into);\n } else if (expr.kind === \"aggregate\") {\n into.add(expr.table);\n for (const key of expr.keys) collectExprDependencies(key.value, into);\n } else if (expr.kind === \"binary\") {\n collectExprDependencies(expr.left, into);\n collectExprDependencies(expr.right, into);\n } else if (expr.kind === \"unary\" || expr.kind === \"assert\") {\n collectExprDependencies(expr.value, into);\n } else if (expr.kind === \"member\") {\n collectExprDependencies(expr.base, into);\n } else if (expr.kind === \"call\") {\n for (const arg of expr.args) collectExprDependencies(arg, into);\n } else if (expr.kind === \"shapeUse\") {\n collectExprDependencies(expr.base, into);\n } else if (expr.kind === \"shape\") {\n collectExprDependencies(expr.base, into);\n for (const field of expr.fields) if (field.kind === \"field\") collectExprDependencies(field.value, into);\n } else if (expr.kind === \"walk\") {\n into.add(expr.table);\n collectExprDependencies(expr.seed, into);\n } else if (expr.kind === \"write\") {\n into.add(expr.table);\n for (const key of expr.keys) collectExprDependencies(key.value, into);\n for (const field of expr.fields) if (field.value) collectExprDependencies(field.value, into);\n } else if (expr.kind === \"array\") {\n for (const item of expr.items) collectExprDependencies(item, into);\n } else if (expr.kind === \"object\") {\n for (const field of expr.fields) if (field.value) collectExprDependencies(field.value, into);\n }\n}\n\nexport function selectIndex(\n catalog: TableCatalog,\n table: string,\n keys: KeyPart[],\n mode: \"point\" | \"range\" | \"exists\",\n explicit: string | undefined,\n infer: (expr: Expr) => ScalarType | undefined,\n site: Site,\n): IndexDecl {\n const info = catalog.get(table);\n if (!info) refuse(site, `unknown table ${table}`);\n if (explicit) {\n const selected = info.indexes.find((index) => index.name === explicit);\n if (!selected) refuse(site, `table ${table} has no index ${explicit}`);\n validateIndexKeys(info.declaration, selected, keys, mode, infer, site);\n return selected;\n }\n const named = keys.some((key) => key.column !== undefined);\n if (named && keys.some((key) => key.column === undefined)) refuse(site, \"an index key cannot mix named and positional parts\");\n let candidates = info.indexes.filter((index) => {\n if (mode === \"range\" && index.name === \"byId\") return false;\n if (mode === \"point\" && (!index.unique || index.columns.length !== keys.length)) return false;\n if ((mode === \"range\" || mode === \"exists\") && index.columns.length < keys.length) return false;\n if (named) return keys.every((key, offset) => index.columns[offset] === key.column);\n return keys.every((key, offset) => compatible(infer(key.value), columnType(info.declaration, index.columns[offset]!)));\n });\n if (mode === \"point\" && keys.length === 1 && !named) {\n const type = infer(keys[0]!.value);\n if (type?.kind === \"ref\" && (type.table === table || type.table === \"\")) candidates = candidates.filter((index) => index.name === \"byId\");\n else if (candidates.some((index) => index.name !== \"byId\")) candidates = candidates.filter((index) => index.name !== \"byId\");\n }\n if (mode !== \"range\") {\n const exact = candidates.filter((index) => index.columns.length === keys.length);\n if (exact.length > 0) candidates = exact;\n }\n if (candidates.length === 0) {\n const spelling = keys.map((key) => key.column ?? \"?\").join(\", \");\n refuse(site, `no ${mode === \"point\" ? \"unique index\" : \"ordering\"} on ${table} matches [${spelling}]; name the columns/index or add one`);\n }\n if (candidates.length > 1) ambiguous(\n site,\n `index selection for ${table}[...] is ambiguous (${candidates.map((item) => item.name).join(\", \")}); name it with by <index>`,\n `${table}[${keys.map((key) => key.value.kind === \"name\" ? key.value.name : \"key\").join(\", \")}] by ${candidates[0]!.name}`,\n );\n const selected = candidates[0]!;\n validateIndexKeys(info.declaration, selected, keys, mode, infer, site);\n return selected;\n}\n\nfunction validateIndexKeys(\n table: TableDecl,\n index: IndexDecl,\n keys: KeyPart[],\n mode: \"point\" | \"range\" | \"exists\",\n infer: (expr: Expr) => ScalarType | undefined,\n site: Site,\n): void {\n if (mode === \"point\" && (!index.unique || index.columns.length !== keys.length)) refuse(site, `${table.name}.${index.name} is not a complete unique key`);\n if ((mode === \"range\" || mode === \"exists\") && index.columns.length < keys.length) refuse(site, `${table.name}.${index.name} has no ${keys.length}-column prefix`);\n for (const [offset, key] of keys.entries()) {\n const column = index.columns[offset]!;\n if (key.column && column !== key.column) refuse(key.site, `${table.name}.${index.name} expects ${column} at key position ${offset + 1}`);\n const actual = infer(key.value);\n const expected = columnType(table, column);\n if (expected.kind === \"int\" && fractionalNumericLiteral(key.value)) {\n typeError(key.value.site, \"int positions take integer literals\", \"use an integer literal for this int index key\");\n }\n if (actual && !compatible(actual, expected)) {\n refuse(key.value.site, `${table.name}.${index.name} expects ${typeName(expected)} for ${column}, got ${typeName(actual)}`);\n }\n }\n}\n\nfunction fractionalNumericLiteral(expr: Expr): boolean {\n if (expr.kind === \"unary\" && expr.op === \"-\") return fractionalNumericLiteral(expr.value);\n return expr.kind === \"literal\" && typeof expr.value === \"number\" && expr.numericText?.includes(\".\") === true;\n}\n\nfunction columnType(table: TableDecl, name: string): ScalarType {\n if (name === \"id\") return { kind: \"ref\", table: table.name, optional: false };\n return table.columns.find((column) => column.name === name)?.type ?? { kind: \"int\", optional: false };\n}\n\nfunction compatible(actual: ScalarType | undefined, expected: ScalarType): boolean {\n if (!actual) return true;\n if (expected.kind === \"ref\") {\n if (actual.kind === \"id\") return true;\n return actual.kind === \"ref\" && (actual.table === \"\" || actual.table === expected.table);\n }\n if (expected.kind === \"id\") return actual.kind === \"ref\" || actual.kind === \"id\";\n if (expected.kind === \"principal\") return actual.kind === \"principal\";\n if (expected.kind === \"enum\" && actual.kind === \"text\") return true;\n if (expected.kind === \"decimal\") return actual.kind === \"decimal\" && actual.scale === expected.scale;\n if (expected.kind === \"money\") {\n return actual.kind === \"money\" && actual.currency === expected.currency && actual.scale === expected.scale;\n }\n return actual.kind === expected.kind;\n}\n\nfunction typeName(type: ScalarType): string {\n if (type.kind === \"ref\") return `reference to ${type.table}`;\n if (type.kind === \"list\") return \"list\";\n if (type.kind === \"decimal\") return `decimal ${type.scale}`;\n if (type.kind === \"money\") return `money ${type.currency} ${type.scale}`;\n return type.kind;\n}\n", "import type { Document, Expr, ProgramDecl, QuarryDiagnostic, ShapeDecl, ShapeField, Site, Stmt } from \"./ast\";\nimport { QuarryError } from \"./diagnostics\";\n\nconst MAX_SHAPE_DEPTH = 8;\n\n// @ref LLP 1011#b2-shape \u2014 named projections are macro-like AST data: every\n// field keeps its definition site while the generated read work belongs to the caller.\nexport function expandDocuments(documents: Document[]): { documents: Document[]; diagnostics: QuarryDiagnostic[] } {\n const diagnostics: QuarryDiagnostic[] = [];\n const expanded = documents.map((document) => {\n const definitions = new Map<string, ShapeDecl>();\n for (const shape of document.shapes) {\n if (definitions.has(shape.name)) {\n diagnostics.push(new QuarryError(\n shape.site,\n `duplicate shape ${shape.name}`,\n \"E_QUARRY_UNKNOWN\",\n `rename shape ${shape.name} or remove this declaration`,\n ).diagnostic);\n } else definitions.set(shape.name, shape);\n }\n if (diagnostics.length > 0) return document;\n\n const expander = new Expander(definitions);\n for (const shape of document.shapes) {\n try {\n expander.instantiate(shape.name, shape.site, 1, []);\n } catch (error) {\n diagnostics.push(caught(error));\n }\n }\n const programs: ProgramDecl[] = [];\n for (const program of document.programs) {\n try {\n programs.push({ ...program, body: program.body.map((statement) => expander.statement(statement)) });\n } catch (error) {\n diagnostics.push(caught(error));\n programs.push(program);\n }\n }\n return { ...document, programs };\n });\n return { documents: expanded, diagnostics: uniqueDiagnostics(diagnostics) };\n}\n\nclass Expander {\n constructor(private readonly definitions: Map<string, ShapeDecl>) {}\n\n instantiate(name: string, useSite: Site, depth: number, stack: string[]): ShapeField[] {\n const declaration = this.definitions.get(name);\n if (!declaration) {\n throw new QuarryError(\n useSite,\n `unknown shape ${name}`,\n \"E_QUARRY_UNKNOWN\",\n `define shape ${name} = { * } in this operation module`,\n );\n }\n if (stack.includes(name)) {\n throw new QuarryError(\n declaration.site,\n `shape cycle ${[...stack, name].join(\" -> \")} is not supported; shape ${name} was used at ${siteText(useSite)}`,\n \"E_QUARRY_UNSUPPORTED\",\n `remove the recursive ${name} shape use`,\n );\n }\n if (depth > MAX_SHAPE_DEPTH) {\n throw new QuarryError(\n declaration.site,\n `shape expansion exceeds depth ${MAX_SHAPE_DEPTH}; shape ${name} was used at ${siteText(useSite)}`,\n \"E_QUARRY_UNSUPPORTED\",\n `inline or split the projection so it expands through at most ${MAX_SHAPE_DEPTH} named shapes`,\n );\n }\n return this.fields(declaration.fields, useSite, depth, [...stack, name], true);\n }\n\n statement(statement: Stmt): Stmt {\n if (statement.kind === \"bind\" || statement.kind === \"expr\" || statement.kind === \"return\") {\n return { ...statement, value: this.expression(statement.value) };\n }\n if (statement.kind === \"require\") return { ...statement, condition: this.expression(statement.condition) };\n if (statement.kind === \"emit\") return { ...statement, payload: this.expression(statement.payload) };\n if (statement.kind === \"if\") return {\n ...statement,\n condition: this.expression(statement.condition),\n thenBody: statement.thenBody.map((item) => this.statement(item)),\n elseBody: statement.elseBody.map((item) => this.statement(item)),\n };\n if (statement.kind === \"for\") return {\n ...statement,\n domain: this.expression(statement.domain),\n body: statement.body.map((item) => this.statement(item)),\n };\n const read = this.expression(statement.read);\n return {\n ...statement,\n read: read as Extract<Expr, { kind: \"read\" }>,\n someBody: statement.someBody.map((item) => this.statement(item)),\n noneBody: statement.noneBody.map((item) => this.statement(item)),\n };\n }\n\n expression(expr: Expr, useSite?: Site, depth = 0, stack: string[] = []): Expr {\n const nested = (value: Expr) => this.expression(value, useSite, depth, stack);\n if (expr.kind === \"shapeUse\") {\n const outerUse = useSite ?? expr.site;\n return {\n kind: \"shape\",\n base: nested(expr.base),\n fields: this.instantiate(expr.name, outerUse, depth + 1, stack),\n authoredName: expr.name,\n site: this.site(expr.site, useSite),\n };\n }\n if (expr.kind === \"shape\") {\n const authoredFields = expr.fields.some((field) => field.kind === \"namedSpread\")\n ? structuredClone(expr.fields)\n : expr.authoredFields;\n return {\n ...expr,\n base: nested(expr.base),\n fields: this.fields(expr.fields, useSite ?? expr.site, depth, stack, !!useSite),\n ...(authoredFields ? { authoredFields } : {}),\n site: this.site(expr.site, useSite),\n };\n }\n if (expr.kind === \"unary\" || expr.kind === \"assert\") return { ...expr, value: nested(expr.value), site: this.site(expr.site, useSite) };\n if (expr.kind === \"binary\") return { ...expr, left: nested(expr.left), right: nested(expr.right), site: this.site(expr.site, useSite) };\n if (expr.kind === \"member\") return { ...expr, base: nested(expr.base), site: this.site(expr.site, useSite) };\n if (expr.kind === \"call\") return { ...expr, args: expr.args.map(nested), site: this.site(expr.site, useSite) };\n if (expr.kind === \"array\") return { ...expr, items: expr.items.map(nested), site: this.site(expr.site, useSite) };\n if (expr.kind === \"object\") return {\n ...expr,\n fields: expr.fields.map((field) => ({ ...field, value: field.value && nested(field.value), site: this.site(field.site, useSite) })),\n site: this.site(expr.site, useSite),\n };\n if (expr.kind === \"read\") return {\n ...expr,\n keys: expr.keys.map((key) => ({ ...key, value: nested(key.value), site: this.site(key.site, useSite) })),\n range: expr.range && {\n ...expr.range,\n cursor: expr.range.cursor && nested(expr.range.cursor),\n where: expr.range.where && {\n ...expr.range.where,\n predicate: nested(expr.range.where.predicate),\n site: this.site(expr.range.where.site, useSite),\n },\n site: this.site(expr.range.site, useSite),\n },\n site: this.site(expr.site, useSite),\n };\n if (expr.kind === \"merge\") return {\n ...expr,\n cursor: expr.cursor && nested(expr.cursor),\n lanes: expr.lanes.map((lane) => ({\n ...lane,\n prefix: lane.prefix.map(nested),\n loop: lane.loop && { ...lane.loop, domain: nested(lane.loop.domain) as Extract<Expr, { kind: \"read\" }> },\n site: this.site(lane.site, useSite),\n })),\n site: this.site(expr.site, useSite),\n };\n if (expr.kind === \"exists\" || expr.kind === \"created\") {\n return { ...expr, read: nested(expr.read) as Extract<Expr, { kind: \"read\" }>, site: this.site(expr.site, useSite) };\n }\n if (expr.kind === \"aggregate\") return {\n ...expr,\n keys: expr.keys.map((key) => ({ ...key, value: nested(key.value), site: this.site(key.site, useSite) })),\n site: this.site(expr.site, useSite),\n };\n if (expr.kind === \"walk\") return { ...expr, seed: nested(expr.seed), site: this.site(expr.site, useSite) };\n if (expr.kind === \"write\") return {\n ...expr,\n keys: expr.keys.map((key) => ({ ...key, value: nested(key.value), site: this.site(key.site, useSite) })),\n fields: expr.fields.map((field) => ({ ...field, value: field.value && nested(field.value), site: this.site(field.site, useSite) })),\n site: this.site(expr.site, useSite),\n };\n return { ...expr, site: this.site(expr.site, useSite) };\n }\n\n private fields(fields: ShapeField[], useSite: Site, depth: number, stack: string[], annotate: boolean): ShapeField[] {\n return fields.flatMap((field) => {\n if (field.kind === \"namedSpread\") return this.instantiate(field.name, useSite, depth + 1, stack);\n const site = this.site(field.site, annotate ? useSite : undefined);\n if (field.kind === \"field\") {\n return [{ ...field, value: this.expression(field.value, annotate ? useSite : undefined, depth, stack), site }];\n }\n return [{ ...field, site }];\n });\n }\n\n private site(site: Site, useSite: Site | undefined): Site {\n return useSite\n ? { file: site.file, line: site.line, col: site.col, expandedFrom: useSite.expandedFrom ?? useSite }\n : site;\n }\n}\n\nfunction caught(error: unknown): QuarryDiagnostic {\n if (error instanceof QuarryError) return error.diagnostic;\n throw error;\n}\n\nfunction siteText(site: Site): string { return `${site.file}:${site.line}:${site.col}`; }\n\nfunction uniqueDiagnostics(diagnostics: QuarryDiagnostic[]): QuarryDiagnostic[] {\n const seen = new Set<string>();\n return diagnostics.filter((diagnostic) => {\n const key = `${siteText(diagnostic)}\\0${diagnostic.code}\\0${diagnostic.message}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n", "import type { QuarryDiagnostic, Site } from \"./ast\";\n\nexport type TokenKind = \"word\" | \"number\" | \"string\" | \"symbol\" | \"newline\" | \"indent\" | \"dedent\" | \"eof\";\nexport type Token = Site & { kind: TokenKind; value: string };\n\nconst TWO_CHARACTER = new Set([\"<-\", \"->\", \"<=\", \">=\", \"!=\", \"??\"]);\nconst SYMBOLS = new Set(\":(),[]{}.?!#+-~*/%=<>\");\nconst HYPHENATED_WORDS = [\"until-revoked\", \"delivered-history\"];\n\nexport function lex(file: string, source: string): { tokens: Token[]; diagnostics: QuarryDiagnostic[] } {\n const tokens: Token[] = [];\n const diagnostics: QuarryDiagnostic[] = [];\n const report = (site: Site, message: string) => diagnostics.push({\n ...site,\n code: \"E_QUARRY_SYNTAX\",\n message,\n rewrite: \"fix this Quarry line and rerun snapback2 check\",\n guide: \"quarry/grammar\",\n });\n const indents = [0];\n let grouping = 0;\n const lines = source.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {\n const raw = lines[lineIndex]!;\n const line = lineIndex + 1;\n if (/^\\s*--/.test(raw) || /^\\s*$/.test(raw)) continue;\n const leading = raw.match(/^[ \\t]*/)?.[0] ?? \"\";\n if (leading.includes(\"\\t\")) report({ file, line, col: 1 }, \"tabs are not valid indentation; use spaces\");\n let offset = leading.length;\n\n if (grouping === 0) {\n const current = indents.at(-1)!;\n if (offset > current) {\n indents.push(offset);\n tokens.push(token(file, line, 1, \"indent\", \"<indent>\"));\n } else if (offset < current) {\n while (offset < indents.at(-1)!) {\n indents.pop();\n tokens.push(token(file, line, 1, \"dedent\", \"<dedent>\"));\n }\n if (offset !== indents.at(-1)) report({ file, line, col: 1 }, \"indentation does not match an enclosing block\");\n }\n }\n\n let emitted = false;\n while (offset < raw.length) {\n const char = raw[offset]!;\n if (char === \" \" || char === \"\\t\") {\n offset += 1;\n continue;\n }\n if (char === \"-\" && raw[offset + 1] === \"-\") break;\n const site = { file, line, col: offset + 1 };\n const pair = raw.slice(offset, offset + 2);\n if (TWO_CHARACTER.has(pair)) {\n tokens.push({ ...site, kind: \"symbol\", value: pair });\n offset += 2;\n emitted = true;\n continue;\n }\n if (char === \"'\" || char === '\"') {\n const quote = char;\n let value = \"\";\n offset += 1;\n let closed = false;\n while (offset < raw.length) {\n const next = raw[offset]!;\n if (next === quote) {\n offset += 1;\n closed = true;\n break;\n }\n if (next === \"\\\\\") {\n const escaped = raw[offset + 1];\n if (escaped === undefined) break;\n value += escaped === \"n\" ? \"\\n\" : escaped === \"t\" ? \"\\t\" : escaped;\n offset += 2;\n } else {\n value += next;\n offset += 1;\n }\n }\n if (!closed) report(site, \"unterminated string literal\");\n tokens.push({ ...site, kind: \"string\", value });\n emitted = true;\n continue;\n }\n if (/[0-9]/.test(char)) {\n const match = raw.slice(offset).match(/^\\d+(?:\\.\\d+)?/)![0];\n tokens.push({ ...site, kind: \"number\", value: match });\n offset += match.length;\n emitted = true;\n continue;\n }\n if (/[A-Za-z_]/.test(char)) {\n // @ref LLP 1012#5-retention-revocation-and-the-fence \u2014 the two\n // retention policies are single Quarry tokens only after `retain`,\n // without changing ordinary subtraction or declaration names.\n const prior = tokens.at(-1);\n const afterRetain = prior?.line === line && prior.value === \"retain\";\n const policyWord = HYPHENATED_WORDS.find((word) => raw.startsWith(word, offset)\n && !/[A-Za-z0-9_-]/.test(raw[offset + word.length] ?? \"\"));\n if (policyWord && !afterRetain) {\n report(site, `${policyWord} is a retention policy and is valid only after retain`);\n }\n const hyphenated = afterRetain ? policyWord : undefined;\n const match = hyphenated ?? raw.slice(offset).match(/^[A-Za-z_][A-Za-z0-9_]*/)![0];\n tokens.push({ ...site, kind: \"word\", value: match });\n offset += match.length;\n emitted = true;\n continue;\n }\n if (SYMBOLS.has(char)) {\n tokens.push({ ...site, kind: \"symbol\", value: char });\n if (\"([{\".includes(char)) grouping += 1;\n if (\")]}\".includes(char)) grouping -= 1;\n if (grouping < 0) {\n report(site, `unexpected ${char}`);\n grouping = 0;\n }\n offset += 1;\n emitted = true;\n continue;\n }\n report(site, `unexpected character ${JSON.stringify(char)}`);\n offset += 1;\n }\n if (emitted && grouping === 0) tokens.push(token(file, line, raw.length + 1, \"newline\", \"<newline>\"));\n }\n if (grouping !== 0) report({ file, line: lines.length, col: 1 }, \"unclosed grouping delimiter\");\n while (indents.length > 1) {\n indents.pop();\n tokens.push(token(file, lines.length, 1, \"dedent\", \"<dedent>\"));\n }\n tokens.push(token(file, lines.length, 1, \"eof\", \"<eof>\"));\n return { tokens, diagnostics };\n}\n\nfunction token(file: string, line: number, col: number, kind: TokenKind, value: string): Token {\n return { file, line, col, kind, value };\n}\n", "import type { Expr } from \"./ast\";\n\ntype NarrowingType = { kind: string; optional?: boolean; nullable?: boolean };\ntype NarrowingBinding = {\n type: NarrowingType;\n narrowedType?: NarrowingType;\n narrowedFields?: Set<string>;\n};\n\n// @ref LLP 1011#b4-narrowing-on-if-x--null \u2014 the fact lives on the cloned\n// binding identity. Rebinding installs a fresh object and therefore drops it.\nexport function narrowThenBindings<T extends NarrowingBinding>(condition: Expr, bindings: Map<string, T>): void {\n if (condition.kind !== \"binary\" || condition.op !== \"!=\"\n || condition.right.kind !== \"literal\" || condition.right.value !== null) return;\n const target = condition.left;\n if (target.kind === \"name\") {\n const binding = bindings.get(target.name);\n if (!binding) return;\n const current = binding.narrowedType ?? binding.type;\n if (\"optional\" in current && current.optional) binding.narrowedType = { ...current, optional: false };\n else if (\"nullable\" in current && current.nullable) binding.narrowedType = { ...current, nullable: false };\n return;\n }\n if (target.kind !== \"member\" || target.base.kind !== \"name\") return;\n const binding = bindings.get(target.base.name);\n const current = binding?.narrowedType ?? binding?.type;\n if (!binding || current?.kind !== \"row\") return;\n binding.narrowedFields = new Set(binding.narrowedFields);\n binding.narrowedFields.add(target.name);\n}\n", "import type { ChannelDecl, Document, Expr, MaintainDecl, RuleDecl, ScalarType, Site, TableCatalog, TableDecl } from \"./ast\";\nimport { orderedTables, selectIndex } from \"./catalog\";\nimport { refuse, typeError } from \"./diagnostics\";\n\ntype RuleContext = {\n names: Set<string>;\n focal?: boolean;\n effect?: RuleDecl[\"effect\"];\n old?: string;\n next?: string;\n table?: TableDecl;\n args?: Map<string, ScalarType>;\n};\n\nexport function emitSchema(documents: Document[], catalog: TableCatalog, sourceFile: string): string {\n const rootSite = documents.find((document) => document.tables.length > 0)?.tables[0]?.site\n ?? { file: sourceFile, line: 1, col: 1 };\n const lines: string[] = [withSite(header(sourceFile), rootSite)];\n lines.push(withSite('import { channel, rule, schema, table, t } from \"snapback2\";', rootSite), \"\");\n for (const table of orderedTables(catalog)) lines.push(...emitTable(table, catalog), \"\");\n const channels = documents.flatMap((document) => document.channels);\n for (const declaration of channels) lines.push(...emitChannel(declaration, catalog), \"\");\n const identity = documents.find((document) => document.identity)?.identity ?? { password: false, guests: false };\n const maintains = documents.flatMap((document) => document.maintains);\n lines.push(withSite(\"export default schema({\", rootSite));\n lines.push(withSite(` auth: { password: ${identity.password}, guests: ${identity.guests} },`, rootSite));\n lines.push(withSite(` tables: { ${[...catalog.keys()].join(\", \")} },`, rootSite));\n if (maintains.length > 0) {\n lines.push(withSite(\" maintains: [\", maintains[0]!.site));\n for (const declaration of maintains) lines.push(withSite(` ${maintainCode(declaration, catalog)},`, declaration.site));\n lines.push(withSite(\" ],\", maintains.at(-1)!.site));\n }\n lines.push(withSite(` channels: { ${channels.map((item) => item.name).join(\", \")} },`, rootSite));\n lines.push(withSite(\"});\", rootSite));\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction emitTable(declaration: TableDecl, catalog: TableCatalog): string[] {\n const lines = [withSite(`export var ${declaration.name} = table({`, declaration.site)];\n lines.push(withSite(\" columns: {\", declaration.site));\n for (const column of declaration.columns) lines.push(withSite(` ${property(column.name)}: ${typeCode(column.type)},`, column.site));\n lines.push(withSite(\" },\", declaration.site));\n // @ref LLP 1012#5-retention-revocation-and-the-fence \u2014 omission is an\n // explicit IR default; the client policy is carried once per table.\n lines.push(withSite(` retain: ${JSON.stringify(declaration.retain?.policy ?? \"until-revoked\")},`, declaration.retain?.site ?? declaration.site));\n if (declaration.indexes.length > 0) {\n lines.push(withSite(\" indexes: {\", declaration.site));\n for (const index of declaration.indexes) {\n lines.push(withSite(\n ` ${property(index.name)}: { columns: [${index.columns.map((column) => JSON.stringify(column)).join(\", \")}]${index.unique ? \", unique: true\" : \"\"} },`,\n index.site,\n ));\n }\n lines.push(withSite(\" },\", declaration.site));\n }\n const ruleLines: string[] = [];\n if (declaration.public) ruleLines.push(withSite(` read: rule.public(${JSON.stringify(declaration.public.reason)}),`, declaration.public.site));\n for (const rule of declaration.rules) {\n if (rule.effect === \"read\" && declaration.public) refuse(rule.site, `table ${declaration.name} cannot combine public with an explicit read rule`);\n ruleLines.push(withSite(` ${rule.effect}: ${emitRule(rule, catalog, declaration)},`, rule.site));\n }\n if (ruleLines.length > 0) lines.push(withSite(\" rules: {\", declaration.site), ...ruleLines, withSite(\" },\", declaration.site));\n const constraints = emitConstraints(declaration, catalog);\n if (constraints.length > 0) lines.push(withSite(\" constraints: [\", declaration.site), ...constraints, withSite(\" ],\", declaration.site));\n lines.push(withSite(\"});\", declaration.site));\n return lines;\n}\n\nfunction emitConstraints(declaration: TableDecl, catalog: TableCatalog): string[] {\n const lines: string[] = [];\n for (const index of declaration.indexes.filter((item) => item.unique)) {\n lines.push(withSite(` { unique: ${JSON.stringify(index.name)} },`, index.site));\n }\n for (const immutable of declaration.immutable) {\n lines.push(withSite(` { immutable: [${immutable.columns.map((column) => JSON.stringify(column)).join(\", \")}] },`, immutable.site));\n }\n for (const column of declaration.columns) {\n if (column.type.kind !== \"text\") continue;\n if (column.type.min !== undefined || column.type.format) {\n const fields = [`field: ${JSON.stringify(column.name)}`];\n if (column.type.min !== undefined) fields.push(`min: ${column.type.min}`);\n if (column.type.format) fields.push(`format: ${JSON.stringify(column.type.format)}`);\n lines.push(withSite(` { text: { ${fields.join(\", \")} } },`, column.site));\n }\n }\n for (const finalExists of declaration.finalExists) {\n const read = finalExists.value.read;\n const context: RuleContext = { names: new Set(), focal: true, effect: \"insert\", table: declaration };\n const index = selectIndex(catalog, read.table, read.keys, \"exists\", read.index, (value) => ruleTermType(value, context), read.site);\n const key = read.keys.map((item) => ruleTerm(item.value, context).code).join(\", \");\n lines.push(withSite(\n ` { finalExistsOnInsert: { table: ${JSON.stringify(read.table)}, index: ${JSON.stringify(index.name)}, key: [${key}] } },`,\n finalExists.site,\n ));\n }\n return lines;\n}\n\nfunction emitChannel(declaration: ChannelDecl, catalog: TableCatalog): string[] {\n const context: RuleContext = {\n names: new Set(declaration.args.map((arg) => arg.name)),\n args: new Map(declaration.args.map((arg) => [arg.name, arg.type])),\n };\n return [\n withSite(`export const ${declaration.name} = channel({`, declaration.site),\n withSite(` args: { ${declaration.args.map((arg) => `${property(arg.name)}: ${typeCode(arg.type)}`).join(\", \")} },`, declaration.site),\n withSite(` publish: ${ruleExpr(declaration.publish, catalog, context)},`, declaration.publish.site),\n withSite(` subscribe: ${ruleExpr(declaration.subscribe, catalog, context)},`, declaration.subscribe.site),\n withSite(` ttlMs: ${declaration.ttlSeconds * 1000},`, declaration.site),\n withSite(\"});\", declaration.site),\n ];\n}\n\nfunction maintainCode(declaration: MaintainDecl, catalog: TableCatalog): string {\n const kind = declaration.aggregate === \"count\"\n ? `count: ${JSON.stringify(declaration.source)}`\n : `sum: { source: ${JSON.stringify(declaration.source)}, of: ${JSON.stringify(declaration.column)} }`;\n const readable = declaration.readable\n ? `, readable: ${emitRule(declaration.readable, catalog, catalog.get(declaration.name)?.declaration)}`\n : \"\";\n return `{ ${kind}, by: [${declaration.by.map((column) => JSON.stringify(column)).join(\", \")}], into: ${JSON.stringify(declaration.name)}${readable} }`;\n}\n\nfunction emitRule(declaration: RuleDecl, catalog: TableCatalog, table?: TableDecl): string {\n const context: RuleContext = { names: new Set(declaration.bindings), focal: declaration.bindings.length === 0, effect: declaration.effect, table };\n if (declaration.effect === \"update\" && declaration.bindings.length === 2) [context.old, context.next] = declaration.bindings;\n return ruleExpr(declaration.value, catalog, context);\n}\n\nfunction ruleExpr(expr: Expr, catalog: TableCatalog, context: RuleContext): string {\n if (expr.kind === \"name\") {\n if (expr.name === \"allow\") return \"rule.allow()\";\n if (expr.name === \"deny\") return \"rule.deny()\";\n if (expr.name === \"system\") return \"rule.system()\";\n if (expr.name === \"public\") return 'rule.public(\"Quarry public rule\")';\n refuse(expr.site, `rule expression ${expr.name} is not allow, deny, public, system, or a supported predicate`);\n }\n if (expr.kind === \"unary\" && expr.op === \"not\") return `rule.not(${ruleExpr(expr.value, catalog, context)})`;\n if (expr.kind === \"binary\" && (expr.op === \"and\" || expr.op === \"or\")) {\n return `rule.${expr.op}(${flattenBoolean(expr, expr.op).map((item) => ruleExpr(item, catalog, context)).join(\", \")})`;\n }\n if (expr.kind === \"binary\" && (expr.op === \"=\" || expr.op === \"!=\")) {\n const leftType = ruleTermType(expr.left, context);\n const rightType = ruleTermType(expr.right, context);\n if (leftType?.kind === \"int\" && fractionalNumericLiteral(expr.right)\n || rightType?.kind === \"int\" && fractionalNumericLiteral(expr.left)) {\n typeError(expr.site, \"int positions take integer literals\", \"use an integer literal in the int comparison\");\n }\n if (leftType && rightType && !compatibleRuleTypes(leftType, rightType)\n && !brandedLiteralPair(leftType, expr.right) && !brandedLiteralPair(rightType, expr.left)) {\n refuse(expr.site, `cannot compare nominal ${leftType.kind} with ${rightType.kind}; fields compared with viewer must be principal`);\n }\n const left = ruleTerm(expr.left, context);\n const right = ruleTerm(expr.right, context);\n if (expr.op === \"=\" && left.kind === \"field\" && right.code === \"rule.viewer\" && left.method === \"field\") return `rule.viewerIs(${JSON.stringify(left.field)})`;\n if (expr.op === \"=\" && right.kind === \"field\" && left.code === \"rule.viewer\" && right.method === \"field\") return `rule.viewerIs(${JSON.stringify(right.field)})`;\n return `rule.${expr.op === \"=\" ? \"eq\" : \"ne\"}(${left.code}, ${right.code})`;\n }\n if (expr.kind === \"exists\" || expr.kind === \"created\") {\n const index = selectIndex(catalog, expr.read.table, expr.read.keys, \"exists\", expr.read.index, (value) => ruleTermType(value, context), expr.site);\n const keys = expr.read.keys.map((key) => ruleTerm(key.value, context).code).join(\", \");\n return `rule.${expr.kind}(${expr.read.table}, ${JSON.stringify(index.name)}, [${keys}])`;\n }\n if (expr.kind === \"member\" || expr.kind === \"read\") refuse(expr.site, \"rules cannot follow point reads or nested field chains; use a direct .field or exists/created probe\");\n if (expr.kind === \"binary\" && [\"<\", \"<=\", \">\", \">=\"].includes(expr.op)) refuse(expr.site, `the platform rule vocabulary has eq/ne but not ${expr.op}; move the bounded comparison into a mutation require`);\n refuse(expr.site, `rule expression cannot be represented by the Snapback 2 platform${context.effect ? ` for ${context.effect}` : \"\"}`);\n}\n\nfunction ruleTerm(expr: Expr, context: RuleContext): { code: string; kind: \"field\" | \"other\"; field?: string; method?: string } {\n if (expr.kind === \"name\" && expr.name === \"viewer\") return { code: \"rule.viewer\", kind: \"other\" };\n if (expr.kind === \"literal\") return { code: `rule.literal(${literalCode(expr)})`, kind: \"other\" };\n // @ref LLP 1010#a3-one-row-binder \u2014 focal .field is the candidate row;\n // only a two-image update retains named old/next terms.\n if (expr.kind === \"member\" && expr.base.kind === \"focal\" && context.focal) {\n if (context.table && expr.name !== \"id\" && !context.table.columns.some((column) => column.name === expr.name)) {\n refuse(expr.site, `table ${context.table.name} has no rule field ${expr.name}`);\n }\n return { code: `rule.field(${JSON.stringify(expr.name)})`, kind: \"field\", field: expr.name, method: \"field\" };\n }\n if (expr.kind === \"member\" && expr.base.kind === \"name\" && context.names.has(expr.base.name)) {\n if (context.table && expr.name !== \"id\" && !context.table.columns.some((column) => column.name === expr.name)) {\n refuse(expr.site, `table ${context.table.name} has no rule field ${expr.name}`);\n }\n const method = expr.base.name === context.old ? \"oldField\" : expr.base.name === context.next ? \"nextField\" : \"field\";\n return { code: `rule.${method}(${JSON.stringify(expr.name)})`, kind: \"field\", field: expr.name, method };\n }\n if (expr.kind === \"name\" && context.names.has(expr.name)) return { code: `rule.field(${JSON.stringify(expr.name)})`, kind: \"field\", field: expr.name, method: \"field\" };\n if (expr.kind === \"member\") refuse(expr.site, \"rule terms cannot follow nested field chains; use a direct .field or exists/created probe\");\n refuse(expr.site, \"rule terms may only be viewer, literals, channel arguments, or direct .fields of the ruled row\");\n}\n\nfunction ruleTermType(expr: Expr, context: RuleContext): ScalarType | undefined {\n if (expr.kind === \"name\" && expr.name === \"viewer\") return { kind: \"principal\", optional: false };\n if (expr.kind === \"literal\") {\n if (typeof expr.value === \"string\") return { kind: \"text\", max: Math.max(1, expr.value.length), optional: false };\n if (typeof expr.value === \"number\") return { kind: \"int\", optional: false };\n if (typeof expr.value === \"boolean\") return { kind: \"bool\", optional: false };\n }\n if (expr.kind === \"member\" && expr.base.kind === \"focal\" && context.focal) {\n if (expr.name === \"id\" && context.table) return { kind: \"ref\", table: context.table.name, optional: false };\n return context.table?.columns.find((column) => column.name === expr.name)?.type;\n }\n if (expr.kind === \"member\" && expr.base.kind === \"name\" && context.names.has(expr.base.name)) {\n if (expr.name === \"id\" && context.table) return { kind: \"ref\", table: context.table.name, optional: false };\n return context.table?.columns.find((column) => column.name === expr.name)?.type;\n }\n if (expr.kind === \"name\" && context.names.has(expr.name)) return context.args?.get(expr.name);\n return undefined;\n}\n\nfunction compatibleRuleTypes(left: ScalarType, right: ScalarType): boolean {\n if (left.kind === \"principal\" || right.kind === \"principal\") return left.kind === \"principal\" && right.kind === \"principal\";\n if (left.kind === \"ref\" || left.kind === \"id\") return right.kind === \"ref\" || right.kind === \"id\";\n if (right.kind === \"ref\" || right.kind === \"id\") return false;\n if ((left.kind === \"enum\" && right.kind === \"text\") || (left.kind === \"text\" && right.kind === \"enum\")) return true;\n if (left.kind === \"decimal\" || right.kind === \"decimal\") {\n return left.kind === \"decimal\" && right.kind === \"decimal\" && left.scale === right.scale;\n }\n if (left.kind === \"money\" || right.kind === \"money\") {\n return left.kind === \"money\" && right.kind === \"money\"\n && left.currency === right.currency && left.scale === right.scale;\n }\n return left.kind === right.kind;\n}\n\nfunction brandedLiteralPair(type: ScalarType, expr: Expr): boolean {\n return (type.kind === \"decimal\" || type.kind === \"money\") && numericLiteral(expr);\n}\n\nfunction numericLiteral(expr: Expr): boolean {\n return expr.kind === \"literal\" && typeof expr.value === \"number\"\n || expr.kind === \"unary\" && expr.op === \"-\" && numericLiteral(expr.value);\n}\n\nfunction fractionalNumericLiteral(expr: Expr): boolean {\n if (expr.kind === \"unary\" && expr.op === \"-\") return fractionalNumericLiteral(expr.value);\n return expr.kind === \"literal\" && typeof expr.value === \"number\" && expr.numericText?.includes(\".\") === true;\n}\n\nfunction literalCode(expr: Extract<Expr, { kind: \"literal\" }>): string {\n return typeof expr.value === \"number\" ? expr.numericText ?? JSON.stringify(expr.value) : JSON.stringify(expr.value);\n}\n\nfunction flattenBoolean(expr: Expr, op: \"and\" | \"or\"): Expr[] {\n return expr.kind === \"binary\" && expr.op === op\n ? [...flattenBoolean(expr.left, op), ...flattenBoolean(expr.right, op)]\n : [expr];\n}\n\nexport function typeCode(type: ScalarType): string {\n let code: string;\n if (type.kind === \"cursor\") code = \"t.cursor()\";\n else if (type.kind === \"text\") code = `t.text(${type.max})`;\n else if (type.kind === \"id\") code = \"t.id()\";\n else if (type.kind === \"principal\") code = \"t.principal()\";\n else if (type.kind === \"int\") code = \"t.int()\";\n else if (type.kind === \"decimal\") code = `t.decimal(${type.scale})`;\n else if (type.kind === \"money\") code = type.explicitScale\n ? `t.money(${JSON.stringify(type.currency)}, ${type.scale})`\n : `t.money(${JSON.stringify(type.currency)})`;\n else if (type.kind === \"time\") code = \"t.time()\";\n else if (type.kind === \"bool\") code = \"t.bool()\";\n else if (type.kind === \"json\") code = `t.json(${type.max})`;\n else if (type.kind === \"bytes\") code = `t.bytes(${type.max})`;\n // @ref LLP 1006#3-authoring-surface \u2014 Quarry asset bounds lower to the same unconditional descriptors as authored TypeScript.\n else if (type.kind === \"image\") code = `t.image(${type.max})`;\n else if (type.kind === \"video\") code = `t.video(${type.max})`;\n else if (type.kind === \"enum\") code = `t.enum([${type.variants.map((variant) => JSON.stringify(variant)).join(\", \")}])`;\n else if (type.kind === \"ref\") code = `t.ref(${type.table})`;\n else code = `t.list(${typeCode({ ...type.item, optional: false })}, { max: ${type.max} })`;\n return type.optional ? `t.optional(${code})` : code;\n}\n\nexport function header(file: string): string { return `// GENERATED by the Snapback 2 Quarry front end from ${file}`; }\nexport function mark(file: string, line: number, col = 1): string { return `// q:${file}:${line}:${col}`; }\nexport function siteMark(site: Site): string { return mark(site.file, site.line, site.col); }\nfunction withSite(text: string, site: Site): string { return `${text} ${siteMark(site)}`; }\nfunction property(value: string): string { return /^[A-Za-z_$][\\w$]*$/.test(value) ? value : JSON.stringify(value); }\n", "import type {\n Expr,\n EffectDecl,\n IndexDecl,\n KeyPart,\n MergeExpr,\n ObjectField,\n ProgramDecl,\n ScalarType,\n ShapeDecl,\n ShapeField,\n Site,\n Stmt,\n TableCatalog,\n} from \"./ast\";\nimport { selectIndex } from \"./catalog\";\nimport { refuse, typeError, unsupported } from \"./diagnostics\";\nimport { narrowThenBindings } from \"./narrowing\";\nimport { header, siteMark, typeCode } from \"./schema\";\n\ntype ObjectType = { kind: \"object\"; fields: Map<string, ValueType>; nullable: boolean };\ntype SequenceType = { kind: \"sequence\"; item: ValueType; max: number };\ntype NumericLiteralType = { kind: \"numeric-literal\"; fractionalDigits: number };\ntype ValueType =\n | ScalarType\n | { kind: \"row\"; table: string; nullable: boolean }\n | { kind: \"page\"; table: string }\n | SequenceType\n | ObjectType\n | NumericLiteralType\n | { kind: \"unknown\" };\ntype Binding = { code: string; type: ValueType; narrowedType?: ValueType; narrowedFields?: Set<string> };\ntype Completion = { kind: \"return\" } | { kind: \"assign\"; name: string };\ntype Emitted = Binding & { effectOnly?: boolean };\n\nclass Writer {\n readonly lines: string[] = [];\n indent = 0;\n private lastSite: Site;\n constructor(site: Site) { this.lastSite = site; }\n raw(text = \"\", site?: Site): void {\n if (site) this.lastSite = site;\n this.lines.push(text ? `${\" \".repeat(this.indent)}${text} ${siteMark(site ?? this.lastSite)}` : \"\");\n }\n statement(text: string, site: Site): void { this.raw(text, site); }\n nested(run: () => void): void { this.indent += 1; run(); this.indent -= 1; }\n}\n\nclass Environment {\n readonly bindings = new Map<string, Binding>();\n focal?: Binding;\n inlineComparisons = false;\n\n constructor(readonly catalog: TableCatalog, readonly program: ProgramDecl, readonly effects: Set<string>) {\n for (const arg of program.args) this.bindings.set(arg.name, { code: `args.${arg.name}`, type: arg.type });\n }\n\n clone(): Environment {\n const clone = new Environment(this.catalog, this.program, this.effects);\n clone.bindings.clear();\n for (const [name, binding] of this.bindings) clone.bindings.set(name, {\n ...binding,\n narrowedFields: binding.narrowedFields && new Set(binding.narrowedFields),\n });\n clone.focal = this.focal && { ...this.focal };\n clone.inlineComparisons = this.inlineComparisons;\n return clone;\n }\n}\n\nexport function emitPrograms(programs: ProgramDecl[], catalog: TableCatalog, sourceFile: string, effects: EffectDecl[] = []): string {\n const rootSite = programs[0]?.site ?? effects[0]?.site ?? { file: sourceFile, line: 1, col: 1 };\n const writer = new Writer(rootSite);\n writer.raw(header(sourceFile), rootSite);\n writer.statement(`import { deterministicShare, divmod, emit, max, mergeByIndex, mentionTokens, min, mutation, query, range, recurse, t } from \"snapback2\";`, { file: sourceFile, line: 1, col: 1 });\n if (catalog.size > 0) writer.statement(`import { ${[...catalog.keys()].join(\", \")} } from \"./schema\";`, { file: sourceFile, line: 1, col: 1 });\n for (const effect of effects) writer.statement(`import { ${effect.name} } from \"./${effect.module}\";`, effect.site);\n writer.raw();\n writer.statement(`function orderedPair(left: any, right: any): [any, any] { return [left, right]; }`, { file: sourceFile, line: 1, col: 1 });\n writer.raw();\n for (const program of programs) {\n emitProgram(program, catalog, writer, new Set(effects.map((effect) => effect.name)));\n writer.raw();\n }\n return `${writer.lines.join(\"\\n\").trimEnd()}\\n`;\n}\n\nfunction emitProgram(program: ProgramDecl, catalog: TableCatalog, writer: Writer, effects: Set<string>): void {\n const env = new Environment(catalog, program, effects);\n const args = program.args.map((arg) => `${property(arg.name)}: ${typeCode(arg.type)}`).join(\", \");\n writer.raw(`export const ${program.name} = ${program.kind}({ ${args} }, ({ db, ctx, args }) => {`, program.site);\n writer.nested(() => emitBody(program.body, env, writer, { kind: \"return\" }));\n writer.statement(`});`, program.site);\n}\n\nfunction emitBody(body: Stmt[], env: Environment, writer: Writer, completion?: Completion, discardLast = false): void {\n if (body.length === 0) {\n if (completion?.kind === \"return\") writer.statement(\"return null;\", env.program.site);\n else if (completion?.kind === \"assign\") writer.statement(`${completion.name} = null;`, env.program.site);\n return;\n }\n for (const [index, statement] of body.entries()) {\n const isLast = index === body.length - 1;\n emitStatement(statement, env, writer, isLast ? completion : undefined, isLast && discardLast);\n }\n}\n\nfunction emitStatement(statement: Stmt, env: Environment, writer: Writer, completion?: Completion, discard = false): void {\n if (statement.kind === \"bind\") {\n if (statement.names.length > 1) {\n if (statement.names.length !== 2 || statement.value.kind !== \"call\" || statement.value.name !== \"sorted\" || statement.value.args.length !== 2) {\n refuse(statement.site, \"tuple bindings are supported only as (a, b) = sorted(a, b)\");\n }\n const left = emitExpr(statement.value.args[0]!, env, writer);\n const right = emitExpr(statement.value.args[1]!, env, writer);\n writer.statement(`const [${statement.names.join(\", \")}] = orderedPair(${left.code}, ${right.code});`, statement.site);\n env.bindings.set(statement.names[0]!, { code: statement.names[0]!, type: left.type });\n env.bindings.set(statement.names[1]!, { code: statement.names[1]!, type: right.type });\n } else {\n const value = emitExpr(statement.value, env, writer);\n if (value.effectOnly) refuse(statement.site, \"update/upsert/delete do not yield a value; bind a following point read instead\");\n const name = statement.names[0]!;\n writer.statement(`const ${name} = ${value.code};`, statement.site);\n env.bindings.set(name, { code: name, type: value.type });\n }\n finishNull(completion, writer, statement.site);\n return;\n }\n if (statement.kind === \"require\") {\n const condition = emitExpr(statement.condition, env, writer);\n requireBoolean(statement.condition, condition.type, \"require\");\n writer.statement(`db.require(${condition.code}, ${JSON.stringify(statement.code)});`, statement.site);\n finishNull(completion, writer, statement.site);\n return;\n }\n if (statement.kind === \"return\") {\n const value = emitExpr(statement.value, env, writer);\n writer.statement(`return ${value.effectOnly ? \"null\" : value.code};`, statement.site);\n return;\n }\n if (statement.kind === \"emit\") {\n if (!env.effects.has(statement.effect)) refuse(statement.site, `unknown effect ${statement.effect}; declare effect ${statement.effect} from <module>`);\n const payload = emitExpr(statement.payload, env, writer);\n writer.statement(`emit(${statement.effect}, ${payload.code});`, statement.site);\n finishNull(completion, writer, statement.site);\n return;\n }\n if (statement.kind === \"expr\") {\n const value = emitExpr(statement.value, env, writer);\n if (completion) {\n const code = value.effectOnly ? \"null\" : value.code;\n if (completion.kind === \"return\") writer.statement(`return ${code};`, statement.site);\n else if (statement.value.kind === \"write\" && statement.value.op === \"insert\") {\n const inserted = temporary(\"inserted\", statement.site);\n writer.statement(`const ${inserted} = ${code};`, statement.site);\n writer.statement(`${completion.name} = ${inserted};`, statement.site);\n } else writer.statement(`${completion.name} = ${code};`, statement.site);\n } else if (discard && !value.effectOnly) {\n if (statement.value.kind === \"write\" && statement.value.op === \"insert\") writer.statement(`${value.code};`, statement.site);\n else writer.statement(`const ${temporary(\"discard\", statement.site)} = ${value.code};`, statement.site);\n } else if (!value.effectOnly) {\n if (statement.value.kind !== \"write\" || statement.value.op !== \"insert\") {\n refuse(statement.site, \"a non-final expression must be a write; bind it if its value is needed\");\n }\n writer.statement(`${value.code};`, statement.site);\n }\n return;\n }\n if (statement.kind === \"if\") {\n const condition = emitExpr(statement.condition, env, writer);\n requireBoolean(statement.condition, condition.type, \"if\");\n writer.raw(`if (${condition.code}) {`, statement.site);\n writer.nested(() => {\n const thenEnv = env.clone();\n narrowThenBindings(statement.condition, thenEnv.bindings);\n emitBody(statement.thenBody, thenEnv, writer, completion);\n });\n if (statement.elseBody.length > 0) {\n writer.raw(\"} else {\", statement.site);\n writer.nested(() => emitBody(statement.elseBody, env.clone(), writer, completion));\n } else if (completion) {\n writer.raw(\"} else {\", statement.site);\n writer.nested(() => finishNull(completion, writer, statement.site));\n }\n writer.statement(\"}\", statement.site);\n return;\n }\n if (statement.kind === \"for\") {\n const domain = emitExpr(statement.domain, env, writer);\n const itemType = domain.type.kind === \"page\"\n ? { kind: \"row\", table: domain.type.table, nullable: false } satisfies ValueType\n : domain.type.kind === \"sequence\" || domain.type.kind === \"list\" ? domain.type.item : { kind: \"unknown\" } satisfies ValueType;\n if (domain.type.kind !== \"page\" && domain.type.kind !== \"sequence\" && domain.type.kind !== \"list\" && domain.type.kind !== \"unknown\") {\n refuse(statement.domain.site, \"for domains must be a page, capped list argument, range, tokens result, or literal list\");\n }\n writer.raw(`for (const ${statement.name} of ${domain.code}) {`, statement.site);\n writer.nested(() => {\n const nested = env.clone();\n nested.bindings.set(statement.name, { code: statement.name, type: itemType });\n emitBody(statement.body, nested, writer);\n });\n writer.statement(\"}\", statement.site);\n finishNull(completion, writer, statement.site);\n return;\n }\n emitMatch(statement, env, writer, completion);\n}\n\nfunction emitMatch(statement: Extract<Stmt, { kind: \"match\" }>, env: Environment, writer: Writer, completion?: Completion): void {\n const found = emitRead(statement.read, env, writer);\n const local = temporary(\"match\", statement.site);\n writer.statement(`const ${local} = ${found.code};`, statement.site);\n const discardBranchValues = completion === undefined;\n let branchCompletion = completion;\n let result: string | undefined;\n if (completion?.kind === \"return\") {\n result = temporary(\"matchResult\", statement.site);\n writer.statement(`let ${result}: any = null;`, statement.site);\n branchCompletion = { kind: \"assign\", name: result };\n }\n writer.raw(`if (${local} !== null) {`, statement.site);\n writer.nested(() => {\n const nested = env.clone();\n nested.bindings.set(statement.someName, { code: statement.someName, type: { kind: \"row\", table: statement.read.table, nullable: false } });\n writer.statement(`const ${statement.someName} = ${local};`, statement.site);\n emitBody(statement.someBody, nested, writer, branchCompletion, discardBranchValues);\n });\n writer.raw(\"} else {\", statement.site);\n writer.nested(() => emitBody(statement.noneBody, env.clone(), writer, branchCompletion, discardBranchValues));\n writer.statement(\"}\", statement.site);\n if (result) writer.statement(`return ${result};`, statement.site);\n}\n\nfunction finishNull(completion: Completion | undefined, writer: Writer, site: Site): void {\n if (!completion) return;\n if (completion.kind === \"return\") writer.statement(\"return null;\", site);\n else writer.statement(`${completion.name} = null;`, site);\n}\n\nfunction emitExpr(expr: Expr, env: Environment, writer: Writer): Emitted {\n if (expr.kind === \"literal\") return { code: literalCode(expr), type: literalType(expr) };\n if (expr.kind === \"name\") return emitName(expr.name, expr.site, env);\n if (expr.kind === \"focal\") {\n if (!env.focal) refuse(expr.site, \". is available only inside a shape or write patch\");\n return env.focal;\n }\n if (expr.kind === \"array\") {\n const items = expr.items.map((item) => emitExpr(item, env, writer));\n const item = items[0]?.type ?? { kind: \"unknown\" } satisfies ValueType;\n return { code: `[${items.map((value) => value.code).join(\", \")}]`, type: { kind: \"list\", item: scalarOrUnknown(item), max: items.length, optional: false } };\n }\n if (expr.kind === \"object\") {\n const types = new Map<string, ValueType>();\n const fields = expr.fields.map((field) => {\n const value = emitExpr(field.value ?? { kind: \"name\", name: field.name, site: field.site }, env, writer);\n types.set(field.name, value.type);\n return `${property(field.name)}: ${value.code}`;\n });\n return { code: `{ ${fields.join(\", \")} }`, type: { kind: \"object\", fields: types, nullable: false } };\n }\n if (expr.kind === \"unary\") {\n const value = emitExpr(expr.value, env, writer);\n if (expr.op === \"not\") requireBoolean(expr.value, value.type, \"not\");\n if (expr.op === \"-\" && !numericAmountType(value.type)) {\n const optionalNumeric = [\"int\", \"decimal\", \"money\"].includes(value.type.kind) && \"optional\" in value.type && value.type.optional;\n if (optionalNumeric) typeError(expr.site, \"negation requires a present int, decimal, or money value\", \"require presence first: -(value!) or -(value ?? 0)\");\n else typeError(expr.site, \"negation requires an int, decimal, or money value\", \"negate an int, decimal, or money value\");\n }\n return { code: `${expr.op === \"not\" ? \"!\" : \"-\"}(${value.code})`, type: expr.op === \"not\" ? boolType() : value.type };\n }\n if (expr.kind === \"binary\") return emitBinary(expr, env, writer);\n if (expr.kind === \"member\") return emitMember(expr, env, writer);\n if (expr.kind === \"call\") return emitCall(expr, env, writer);\n if (expr.kind === \"read\") return emitRead(expr, env, writer);\n if (expr.kind === \"merge\") return emitMerge(expr, env, writer);\n if (expr.kind === \"exists\") {\n const read = emitRead(expr.read, env, writer, true);\n return { code: read.code, type: boolType() };\n }\n if (expr.kind === \"created\") refuse(expr.site, \"created is valid only in an insert table rule\");\n if (expr.kind === \"aggregate\") {\n const read = emitRead({ kind: \"read\", table: expr.table, keys: expr.keys, site: expr.site }, env, writer);\n const value = env.catalog.get(expr.table)?.columns.get(\"value\");\n if (!value) refuse(expr.site, `#${expr.table}[...] requires a maintained target with a value column`);\n // @ref LLP 1001#4-generation-and-runtime-registryrs-successorrs \u2014 aggregate absence becomes typed zero once, before the value enters ordinary IR expressions.\n const local = temporary(\"agg\", expr.site);\n writer.statement(`const ${local} = ${read.code}?.value ?? 0;`, expr.site);\n return { code: local, type: { ...value, optional: false } };\n }\n if (expr.kind === \"assert\") {\n const value = emitExpr(expr.value, env, writer);\n const local = temporary(\"required\", expr.site);\n writer.statement(`const ${local} = ${value.code};`, expr.site);\n writer.statement(`db.require(${local} !== null, ${JSON.stringify(expr.code)});`, expr.site);\n return { code: `${local}!`, type: nonNullable(value.type) };\n }\n if (expr.kind === \"shapeUse\") refuse(expr.site, `shape ${expr.name} was not expanded`);\n if (expr.kind === \"shape\") return emitShape(expr, env, writer);\n if (expr.kind === \"walk\") {\n const info = env.catalog.get(expr.table);\n if (!info) refuse(expr.site, `unknown table ${expr.table}`);\n const column = info.columns.get(expr.column);\n if (column?.kind !== \"ref\" || column.table !== expr.table) refuse(expr.site, `walk ${expr.table} up .${expr.column} requires a self-reference column`);\n const seed = emitExpr(expr.seed, env, writer);\n const walked = temporary(\"walk\", expr.site);\n const current = temporary(\"ancestor\", expr.site);\n writer.statement(`const ${walked}: any[] = [];`, expr.site);\n writer.raw(`for (const ${current} of recurse(${seed.code}, (current) => db.get(${expr.table}, current.${expr.column}), { depth: ${expr.depth}, fanout: 1 })) {`);\n writer.nested(() => writer.statement(`${walked}.push(${current});`, expr.site));\n writer.statement(\"}\", expr.site);\n return {\n code: walked,\n type: { kind: \"sequence\", item: { kind: \"row\", table: expr.table, nullable: false }, max: expr.depth + 1 },\n };\n }\n return emitWrite(expr, env, writer);\n}\n\nfunction emitName(name: string, site: Site, env: Environment): Emitted {\n const binding = env.bindings.get(name);\n if (binding) return { ...binding, type: binding.narrowedType ?? binding.type };\n if (name === \"viewer\") return { code: \"ctx.viewer\", type: { kind: \"principal\", optional: false } };\n if (name === \"now\") return { code: \"ctx.now()\", type: { kind: \"time\", optional: false } };\n if (name === \"commit\") return { code: \"ctx.commitTime\", type: { kind: \"time\", optional: false } };\n if (name === \"new\") return { code: \"ctx.newId()\", type: { kind: \"id\", optional: false } };\n refuse(site, `unknown name ${name}`);\n}\n\nfunction emitBinary(expr: Extract<Expr, { kind: \"binary\" }>, env: Environment, writer: Writer): Emitted {\n const left = emitExpr(expr.left, env, writer);\n const right = emitExpr(expr.right, env, writer);\n if (expr.op === \"and\" || expr.op === \"or\") {\n requireBoolean(expr.left, left.type, expr.op);\n requireBoolean(expr.right, right.type, expr.op);\n return { code: `(${left.code} ${expr.op === \"and\" ? \"&&\" : \"||\"} ${right.code})`, type: boolType() };\n }\n if (expr.op === \"??\") return { code: `(${left.code} ?? ${right.code})`, type: nonNullable(left.type) };\n const operator = expr.op === \"=\" ? \"===\" : expr.op === \"!=\" ? \"!==\" : expr.op;\n // @ref LLP 1010#a2-total-equality--program-only \u2014 program equality is total;\n // only ordered comparison requires present operands.\n if ([\"=\", \"!=\", \"<\", \"<=\", \">\", \">=\"].includes(expr.op)) {\n if ((expr.op === \"=\" || expr.op === \"!=\") && expr.right.kind === \"literal\" && expr.right.value === null) {\n // @ref LLP 1011#b4-narrowing-on-if-x--null \u2014 loose null equality is\n // intentional here: optional arguments arrive as undefined, and the\n // generated TypeScript control flow must narrow without an assertion.\n return { code: `(${left.code} ${expr.op === \"=\" ? \"==\" : \"!=\"} null)`, type: boolType() };\n }\n refuseFractionalInt(expr, left.type, right.type);\n const branded = brandedType(left.type) ?? brandedType(right.type);\n const other = branded === left.type ? right : left;\n const otherExpr = branded === left.type ? expr.right : expr.left;\n if (branded && !brandedType(other.type) && !numericLiteral(otherExpr)) {\n typeError(\n expr.site,\n `cannot compare nominal ${brandedName(branded)} with ${valueTypeName(other.type)}`,\n `compare ${simpleExpr(branded === left.type ? expr.left : expr.right)} with the same ${brandedName(branded)} type`,\n );\n }\n if (!branded && isScalar(left.type) && isScalar(right.type) && !compatible(left.type, right.type)) {\n refuse(expr.site, `cannot compare nominal ${left.type.kind} with ${right.type.kind}; use a principal value only with viewer`);\n }\n if ([\"<\", \"<=\", \">\", \">=\"].includes(expr.op) && (isNullableValue(left.type) || isNullableValue(right.type))) {\n const leftText = optionalComparisonOperand(expr.left, left.type);\n const rightText = optionalComparisonOperand(expr.right, right.type);\n typeError(\n expr.site,\n `ordered comparison ${expr.op} requires present operands`,\n `${leftText} ${expr.op} ${rightText}`,\n );\n }\n return { code: `(${left.code} ${operator} ${right.code})`, type: boolType() };\n }\n refuseFractionalInt(expr, left.type, right.type);\n const branded = brandedType(left.type) ?? brandedType(right.type);\n // @ref LLP 1004#money-and-decimal-worked-out-2026-09-03 \u2014 branded loss of scale is explicit Euclidean divmod, never host-number rounding.\n if (branded && (expr.op === \"/\" || expr.op === \"%\")) {\n const member = expr.op === \"/\" ? \"quotient\" : \"remainder\";\n typeError(expr.site, `${brandedName(branded)} does not admit ${expr.op}`, `use divmod(${simpleExpr(expr.left)}, ${simpleExpr(expr.right)}).${member}`);\n }\n if (branded && (expr.op === \"+\" || expr.op === \"-\")) {\n const other = branded === left.type ? right : left;\n const otherExpr = branded === left.type ? expr.right : expr.left;\n if (!brandedType(other.type) && !numericLiteral(otherExpr)) {\n typeError(expr.site, `${expr.op} requires matching ${brandedName(branded)} values`, `use two matching ${brandedName(branded)} values`);\n }\n return { code: `(${left.code} ${expr.op} ${right.code})`, type: branded };\n }\n if (branded && expr.op === \"*\") {\n const leftBrand = brandedType(left.type);\n const rightBrand = brandedType(right.type);\n if (leftBrand && rightBrand) {\n if (leftBrand.kind === \"money\" && rightBrand.kind === \"money\") {\n typeError(\n expr.site,\n \"money multiplied by money has no currency-squared value in Quarry\",\n \"multiply the money value by a decimal rate or an int\",\n );\n }\n const dropped = leftBrand.kind === \"money\" ? rightBrand\n : rightBrand.kind === \"money\" ? leftBrand\n : rightBrand;\n const result = leftBrand.kind === \"money\" ? leftBrand\n : rightBrand.kind === \"money\" ? rightBrand\n : leftBrand;\n const divisor = 10 ** dropped.scale;\n return { code: `divmod((${left.code} * ${right.code}), ${divisor}).quotient`, type: result };\n }\n const other = branded === left.type ? right : left;\n const otherExpr = branded === left.type ? expr.right : expr.left;\n if (!brandedType(other.type) && (other.type.kind !== \"int\" || fractionalNumericLiteral(otherExpr))) {\n typeError(\n expr.site,\n `${brandedName(branded)} multiplication requires an int operand or a decimal-typed rate; a bare fractional literal has no scale`,\n \"use an int operand or declare the rate as a decimal S argument or column\",\n );\n }\n return { code: `(${left.code} * ${right.code})`, type: branded };\n }\n return { code: `(${left.code} ${expr.op} ${right.code})`, type: left.type };\n}\n\nfunction emitMember(expr: Extract<Expr, { kind: \"member\" }>, env: Environment, writer: Writer): Emitted {\n const directBinding = expr.base.kind === \"name\" ? env.bindings.get(expr.base.name) : undefined;\n let base = emitExpr(expr.base, env, writer);\n if (isRef(base.type)) {\n const refType = base.type;\n if (!refType.table) refuse(expr.site, `cannot auto-dereference ${expr.name} because the reference target is not known; use a typed table ref`);\n const local = temporary(\"deref\", expr.site);\n if (refType.optional) {\n const key = temporary(\"derefKey\", expr.site);\n writer.statement(`const ${key} = ${base.code} ?? null;`, expr.site);\n writer.statement(`let ${local}: any = null;`, expr.site);\n writer.raw(`if (${key} !== null) {`);\n writer.nested(() => writer.statement(`${local} = db.get(${refType.table}, ${key});`, expr.site));\n writer.statement(\"}\", expr.site);\n } else {\n writer.statement(`const ${local} = db.get(${refType.table}, ${base.code});`, expr.site);\n }\n base = { code: local, type: { kind: \"row\", table: refType.table, nullable: true } };\n }\n if (base.type.kind === \"image\" || base.type.kind === \"video\") {\n // @ref LLP 1006#3-authoring-surface \u2014 assets are closed records, so admission facts use ordinary field selection.\n const fields = base.type.kind === \"image\"\n ? [\"id\", \"width\", \"height\"]\n : [\"id\", \"width\", \"height\", \"duration\"];\n if (!fields.includes(expr.name)) {\n typeError(\n expr.site,\n `${base.type.kind} asset has no field ${expr.name}; available fields are ${fields.join(\", \")}`,\n `${simpleExpr(expr.base)}.${base.type.kind === \"video\" ? \"duration\" : \"width\"}`,\n );\n }\n const field: ScalarType = expr.name === \"id\"\n ? { kind: \"id\", optional: base.type.optional }\n : { kind: \"int\", optional: base.type.optional };\n return { code: `${base.code}${base.type.optional ? \"?.\" : \".\"}${expr.name}`, type: field };\n }\n if (base.type.kind === \"row\") {\n const info = env.catalog.get(base.type.table);\n const column = expr.name === \"id\"\n ? { kind: \"ref\", table: base.type.table, optional: false } satisfies ScalarType\n : info?.columns.get(expr.name);\n if (!column) refuse(expr.site, `table ${base.type.table} has no column ${expr.name}`);\n const narrowed = directBinding?.narrowedFields?.has(expr.name) ?? false;\n return {\n code: `${base.code}${base.type.nullable ? \"?.\" : \".\"}${expr.name}`,\n type: { ...column, optional: narrowed ? false : column.optional || base.type.nullable },\n };\n }\n if (base.type.kind === \"object\") {\n const field = base.type.fields.get(expr.name);\n if (!field) refuse(expr.site, `shaped object has no field ${expr.name}`);\n return {\n code: `${base.code}${base.type.nullable ? \"?.\" : \".\"}${expr.name}`,\n type: base.type.nullable ? nullableValue(field) : field,\n };\n }\n if (base.type.kind === \"json\") return { code: `(${base.code} as any)?.${expr.name}`, type: { kind: \"unknown\" } };\n if (base.type.kind === \"unknown\") return { code: `${base.code}?.${expr.name}`, type: { kind: \"unknown\" } };\n refuse(expr.site, `cannot select .${expr.name} from ${base.type.kind}`);\n}\n\nfunction emitCall(expr: Extract<Expr, { kind: \"call\" }>, env: Environment, writer: Writer): Emitted {\n if (expr.name === \"sorted\") {\n refuse(expr.site, \"sorted(a, b) must be consumed by a two-name binding: (lo, hi) = sorted(a, b)\");\n }\n const target = expr.name === \"tokens\" ? \"mentionTokens\" : expr.name;\n if (![\"tokens\", \"range\", \"min\", \"max\", \"count\", \"divmod\", \"share\"].includes(expr.name)) {\n unsupported(expr.site, `user function or recursion (${expr.name})`, \"use a Quarry builtin or inline one bounded expression\");\n }\n const args = expr.args.map((arg) => emitExpr(arg, env, writer));\n // @ref LLP 1004#money-and-decimal-worked-out-2026-09-03 \u2014 Quarry exposes only the engine's exact split primitives and preserves nominal result types.\n if (expr.name === \"divmod\") {\n if (args.length !== 2) typeError(expr.site, `divmod(a, b) requires exactly 2 arguments; received ${args.length}`, \"use divmod(amount, integerDivisor)\");\n const numerator = args[0]!;\n const divisor = args[1]!;\n if (!numericAmountType(numerator.type)) {\n typeError(expr.args[0]!.site, `divmod's first argument must be int, decimal, or money; received ${valueTypeName(numerator.type)}`, \"use an int, decimal, or money numerator\");\n }\n if (divisor.type.kind !== \"int\" || fractionalNumericLiteral(expr.args[1]!)) {\n typeError(expr.args[1]!.site, \"divmod's divisor must be an int\", \"use an integer expression or integer literal as the divisor\");\n }\n const resultType = numerator.type as ScalarType;\n return {\n code: `divmod(${numerator.code}, ${divisor.code})`,\n type: { kind: \"object\", fields: new Map([[\"quotient\", resultType], [\"remainder\", resultType]]), nullable: false },\n };\n }\n if (expr.name === \"share\") {\n if (args.length !== 3) typeError(expr.site, `share(amount, recipients, recipient) requires exactly 3 arguments; received ${args.length}`, \"use share(amount, recipients, recipient)\");\n const amount = args[0]!;\n const recipients = args[1]!;\n const recipient = args[2]!;\n if (!numericAmountType(amount.type)) {\n typeError(expr.args[0]!.site, `share's amount must be int, decimal, or money; received ${valueTypeName(amount.type)}`, \"use an int, decimal, or money amount\");\n }\n const item = boundedItemType(recipients.type);\n if (!item) {\n typeError(expr.args[1]!.site, `share recipients must be a bounded list or page; received ${valueTypeName(recipients.type)}`, \"use a bounded [T] <=N argument or bounded page-derived list\");\n }\n if (!sameRecipientType(item, recipient.type)) {\n typeError(\n expr.args[2]!.site,\n `share recipient type ${valueTypeName(recipient.type)} does not match recipient-list item type ${valueTypeName(item)}`,\n \"use a recipient with the same nominal type as the recipients list items\",\n );\n }\n return { code: `deterministicShare(${amount.code}, ${recipients.code}, ${recipient.code})`, type: amount.type as ScalarType };\n }\n if (expr.name === \"count\") {\n if (args.length !== 1 || ![\"list\", \"page\", \"sequence\"].includes(args[0]!.type.kind)) refuse(expr.site, \"count(x) requires one bounded list or page\");\n return { code: `${args[0]!.code}.length`, type: { kind: \"int\", optional: false } };\n }\n if (expr.name === \"tokens\") return { code: `${target}(${args.map((arg) => arg.code).join(\", \")})`, type: { kind: \"list\", item: { kind: \"text\", max: 4096, optional: false }, max: 64, optional: false } };\n if (expr.name === \"range\") {\n if (args.length !== 2) refuse(expr.site, \"range(a, b) requires two arguments\");\n for (const argument of expr.args) {\n if (fractionalNumericLiteral(argument)) {\n typeError(argument.site, \"int positions take integer literals\", `replace ${literalExpressionText(argument)} with an integer literal`);\n }\n }\n const start = literalNumber(expr.args[0]);\n const end = literalNumber(expr.args[1]);\n const max = start === undefined || end === undefined ? 1000 : Math.max(0, end - start);\n return { code: `range(${args.map((arg) => arg.code).join(\", \")})`, type: { kind: \"list\", item: { kind: \"int\", optional: false }, max, optional: false } };\n }\n if (expr.name === \"min\" || expr.name === \"max\") {\n const branded = args.map((arg) => brandedType(arg.type)).find((type) => type !== undefined);\n if (branded) {\n args.forEach((arg, index) => {\n if (!brandedType(arg.type) && !numericLiteral(expr.args[index]!)) {\n typeError(expr.args[index]!.site, `${expr.name} requires matching ${brandedName(branded)} values`, `use matching ${brandedName(branded)} values`);\n }\n });\n return { code: `${target}(${args.map((arg) => arg.code).join(\", \")})`, type: branded };\n }\n const fractional = expr.args.find(fractionalNumericLiteral);\n if (fractional && args.some((arg) => arg.type.kind === \"int\")) {\n typeError(fractional.site, \"int positions take integer literals\", `replace ${literalExpressionText(fractional)} with an integer literal`);\n }\n }\n return { code: `${target}(${args.map((arg) => arg.code).join(\", \")})`, type: args[0]?.type ?? { kind: \"int\", optional: false } };\n}\n\nfunction emitRead(expr: Extract<Expr, { kind: \"read\" }>, env: Environment, writer: Writer, exists = false): Emitted {\n if (!env.catalog.has(expr.table)) refuse(expr.site, `unknown table ${expr.table}`);\n const mode = expr.range ? \"range\" : exists ? \"exists\" : \"point\";\n const index = selectIndex(env.catalog, expr.table, expr.keys, mode, expr.index, (value) => inferExpr(value, env), expr.site);\n const keys = expr.keys.map((key) => keyBinding(emitExpr(key.value, env, writer)));\n const target = index.name === \"byId\" ? expr.table : `${expr.table}.${index.name}`;\n if (expr.range) {\n const remainingColumns = index.columns.slice(expr.keys.length);\n if (expr.range.cursor && remainingColumns.length === 0) {\n const { cursor: _cursor, cursorKind: _cursorKind, ...range } = expr.range;\n typeError(\n expr.range.cursor.site,\n `scan ${expr.table}.${index.name} prefix names every index column, so a cursor has no position to compare; remove after or shorten the prefix`,\n quarryExpression({ ...expr, range }),\n );\n }\n if (expr.range.cursor && index.columns.at(-1) !== \"id\" && !index.unique) {\n const columns = [...index.columns.filter((column) => column !== \"id\"), \"id\"];\n typeError(\n index.site,\n `cursor at ${formatSite(expr.range.cursor.site)} uses \\`${expr.table}.${index.name}\\`, which is not a total order (it neither ends in id nor is unique)`,\n `by ${index.name}: ${columns.join(\", \")}`,\n );\n }\n const cursor = expr.range.cursor && emitExpr(expr.range.cursor, env, writer);\n if (cursor && cursor.type.kind !== \"cursor\") {\n typeError(\n expr.range.cursor!.site,\n `after expects a cursor value, got ${valueTypeName(cursor.type)}`,\n \"declare c: cursor ? and pass after c\",\n );\n }\n const options = [`order: ${JSON.stringify(expr.range.order)}`, `take: ${expr.range.take}`];\n if (cursor) options.push(`after: ${cursor.code}`, \"opaqueCursor: true\");\n if (expr.range.mergeSite) options.push(`mergeSite: ${JSON.stringify(expr.range.mergeSite)}`);\n const scan = `db.scan(${target}, [${keys.map((key) => key.code).join(\", \")}], { ${options.join(\", \")} })`;\n return { code: scan, type: { kind: \"page\", table: expr.table } };\n }\n const key = index.name === \"byId\" && keys.length === 1 ? keys[0]!.code : `[${keys.map((item) => item.code).join(\", \")}]`;\n return exists\n ? { code: `db.exists(${target}, ${key})`, type: boolType() }\n : { code: `db.get(${target}, ${key})`, type: { kind: \"row\", table: expr.table, nullable: true } };\n}\n\nfunction emitMerge(expr: MergeExpr, env: Environment, writer: Writer): Emitted {\n const info = env.catalog.get(expr.table);\n if (!info) refuse(expr.site, `unknown table ${expr.table}`);\n const index = info.indexes.find((candidate) => candidate.name === expr.index);\n if (!index) refuse(expr.site, `table ${expr.table} has no index ${expr.index}`);\n if (index.columns.at(-1) !== \"id\") {\n const columns = [...index.columns.filter((column) => column !== \"id\"), \"id\"];\n typeError(\n index.site,\n `pageable merge ${expr.table}.${index.name} must end in intrinsic id`,\n `by ${index.name}: ${columns.join(\", \")}`,\n );\n }\n const cursor = expr.cursor && emitExpr(expr.cursor, env, writer);\n if (cursor && cursor.type.kind !== \"cursor\") {\n typeError(expr.cursor!.site, `merge after expects a cursor value, got ${valueTypeName(cursor.type)}`, \"declare c: cursor ? and pass after c\");\n }\n const widths = new Set(expr.lanes.map((lane) => lane.prefix.length));\n if (widths.size !== 1) {\n const lane = expr.lanes.find((candidate) => candidate.prefix.length !== expr.lanes[0]!.prefix.length) ?? expr.lanes[0]!;\n typeError(lane.site, \"merge lanes must have equal-width index prefixes\", `use ${expr.lanes[0]!.prefix.length} prefix key(s) in this lane`);\n }\n const width = expr.lanes[0]!.prefix.length;\n if (width >= index.columns.length) {\n typeError(expr.lanes[0]!.site, `merge lane prefixes must leave at least one ${expr.table}.${index.name} suffix column`, \"drop the last prefix key from every lane\");\n }\n const seen = new Map<string, number>();\n expr.lanes.forEach((lane, offset) => {\n const key = lane.prefix.map(quarryExpression).join(\"\\u0000\");\n if (seen.has(key)) typeError(lane.site, \"merge lanes have structurally identical prefixes\", \"drop this duplicate lane\");\n seen.set(key, offset);\n const nested = env.clone();\n if (lane.loop) nested.bindings.set(lane.loop.name, { code: lane.loop.name, type: { kind: \"row\", table: lane.loop.domain.table, nullable: false } });\n lane.prefix.forEach((value, position) => {\n const actual = inferExpr(value, nested);\n const column = index.columns[position]!;\n const expected = column === \"id\"\n ? { kind: \"ref\", table: expr.table, optional: false } satisfies ScalarType\n : info.columns.get(column);\n if (actual && expected && !compatible(actual, expected)) {\n typeError(lane.site, `merge lane key ${position + 1} is ${valueTypeName(actual)}; ${expr.table}.${index.name}.${column} is ${valueTypeName(expected)}`, `use a ${valueTypeName(expected)} expression in this lane position`);\n }\n });\n selectIndex(\n env.catalog,\n expr.table,\n lane.prefix.map((value) => ({ value, site: value.site })),\n \"range\",\n expr.index,\n (value) => inferExpr(value, nested),\n lane.site,\n );\n });\n const mergeSite = `${expr.site.file}:${expr.site.line}:${expr.site.col}`;\n const union = temporary(\"mergeUnion\", expr.site);\n writer.statement(`const ${union}: Array<(typeof ${expr.table})[\"__row\"]> = [];`, expr.site);\n for (const lane of expr.lanes) {\n const emitLane = (nested: Environment): void => {\n const scan = emitRead({\n kind: \"read\",\n table: expr.table,\n keys: lane.prefix.map((value) => ({ value, site: value.site })),\n index: expr.index,\n range: {\n order: expr.order,\n take: expr.take,\n cursor: expr.cursor,\n cursorKind: expr.cursorKind,\n mergeSite,\n site: lane.site,\n },\n site: lane.site,\n }, nested, writer);\n const row = temporary(\"mergeRow\", lane.site);\n writer.raw(`for (const ${row} of ${scan.code}) {`, lane.site);\n writer.nested(() => writer.statement(`${union}.push(${row});`, lane.site));\n writer.statement(\"}\", lane.site);\n };\n if (!lane.loop) {\n emitLane(env);\n continue;\n }\n const domain = emitRead(lane.loop.domain, env, writer);\n writer.raw(`for (const ${lane.loop.name} of ${domain.code}) {`, lane.site);\n writer.nested(() => {\n const nested = env.clone();\n nested.bindings.set(lane.loop!.name, { code: lane.loop!.name, type: { kind: \"row\", table: lane.loop!.domain.table, nullable: false } });\n emitLane(nested);\n });\n writer.statement(\"}\", lane.site);\n }\n const suffix = index.columns.slice(width);\n return {\n code: `mergeByIndex(${union}, ${JSON.stringify(suffix)}, ${JSON.stringify(expr.order)}, ${expr.take}, ${JSON.stringify(mergeSite)}, ${JSON.stringify(expr.table)})`,\n type: { kind: \"page\", table: expr.table },\n };\n}\n\nfunction emitShape(expr: Extract<Expr, { kind: \"shape\" }>, env: Environment, writer: Writer): Emitted {\n let base = emitExpr(expr.base, env, writer);\n if (isRef(base.type)) {\n const refType = base.type;\n if (!refType.table) refuse(expr.site, \"shape auto-dereference needs a typed table reference\");\n const deref = temporary(\"shapeRef\", expr.site);\n if (refType.optional) {\n const key = temporary(\"shapeRefKey\", expr.site);\n writer.statement(`const ${key} = ${base.code} ?? null;`, expr.site);\n writer.statement(`let ${deref}: any = null;`, expr.site);\n writer.raw(`if (${key} !== null) {`);\n writer.nested(() => writer.statement(`${deref} = db.get(${refType.table}, ${key});`, expr.site));\n writer.statement(\"}\", expr.site);\n } else {\n writer.statement(`const ${deref} = db.get(${refType.table}, ${base.code});`, expr.site);\n }\n base = { code: deref, type: { kind: \"row\", table: refType.table, nullable: true } };\n }\n if (base.type.kind === \"page\") return emitPageShape(base, expr.fields, expr.site, env, writer, base.type.table);\n if (base.type.kind === \"sequence\" && base.type.item.kind === \"row\") {\n return emitPageShape(base, expr.fields, expr.site, env, writer, base.type.item.table);\n }\n if (base.type.kind !== \"row\") refuse(expr.site, \"shapes may focus only a row, reference, or page\");\n const rowType = base.type;\n const focalName = temporary(\"row\", expr.site);\n writer.statement(`const ${focalName} = ${base.code};`, expr.site);\n const result = temporary(\"shape\", expr.site);\n let resultType: ObjectType = { kind: \"object\", fields: new Map(), nullable: false };\n if (rowType.nullable) {\n writer.statement(`let ${result}: any = null;`, expr.site);\n writer.raw(`if (${focalName} !== null) {`);\n writer.nested(() => {\n const [shapeCode, shapeType] = shapeObject(expr.fields, { code: focalName, type: { ...rowType, nullable: false } }, env, writer);\n resultType = shapeType;\n writer.statement(`${result} = ${shapeCode};`, expr.site);\n });\n writer.statement(\"}\", expr.site);\n } else {\n const [shapeCode, shapeType] = shapeObject(expr.fields, { code: focalName, type: rowType }, env, writer);\n resultType = shapeType;\n writer.statement(`const ${result} = ${shapeCode};`, expr.site);\n }\n return { code: result, type: { ...resultType, nullable: rowType.nullable } };\n}\n\nfunction emitPageShape(base: Binding, fields: ShapeField[], site: Site, env: Environment, writer: Writer, table: string): Emitted {\n const page = temporary(\"page\", site);\n const result = temporary(\"rows\", site);\n const row = temporary(\"row\", site);\n let itemType: ObjectType = { kind: \"object\", fields: new Map(), nullable: false };\n writer.statement(`const ${page} = ${base.code};`, site);\n writer.statement(`const ${result}: any[] = [];`, site);\n writer.raw(`for (const ${row} of ${page}) {`);\n writer.nested(() => {\n const [shapeCode, shapeType] = shapeObject(fields, { code: row, type: { kind: \"row\", table, nullable: false } }, env, writer);\n itemType = shapeType;\n writer.statement(`${result}.push(${shapeCode});`, site);\n });\n writer.statement(\"}\", site);\n return { code: result, type: { kind: \"sequence\", item: itemType, max: 1000 } };\n}\n\nfunction shapeObject(fields: ShapeField[], focal: Binding, env: Environment, writer: Writer): [string, ObjectType] {\n const prior = env.focal;\n env.focal = focal;\n try {\n const properties: string[] = [];\n const types = new Map<string, ValueType>();\n for (const field of fields) {\n if (field.kind === \"spread\") {\n properties.push(`...${focal.code}`);\n if (focal.type.kind !== \"row\") refuse(field.site, \"shape spread requires a row\");\n types.set(\"id\", { kind: \"ref\", table: focal.type.table, optional: false });\n for (const [name, type] of env.catalog.get(focal.type.table)?.columns ?? []) types.set(name, type);\n } else if (field.kind === \"bare\") {\n const value = emitMember({ kind: \"member\", base: { kind: \"focal\", site: field.site }, name: field.name, site: field.site }, env, writer);\n properties.push(`${property(field.name)}: ${value.code}`);\n types.set(field.name, value.type);\n } else if (field.kind === \"namedSpread\") {\n refuse(field.site, `shape ${field.name} was not expanded`);\n } else {\n const value = emitExpr(field.value, env, writer);\n properties.push(`${property(field.name)}: ${value.code}`);\n types.set(field.name, value.type);\n }\n }\n return [`{ ${properties.join(\", \")} }`, { kind: \"object\", fields: types, nullable: false }];\n } finally {\n env.focal = prior;\n }\n}\n\nfunction emitWrite(expr: Extract<Expr, { kind: \"write\" }>, env: Environment, writer: Writer): Emitted {\n const info = env.catalog.get(expr.table);\n if (!info) refuse(expr.site, `unknown table ${expr.table}`);\n if (expr.op === \"insert\") {\n const fields = emitFields(expr.fields, env, writer, info.columns);\n if (!expr.fields.some((field) => field.name === \"id\")) fields.unshift(\"id: ctx.newId()\");\n return { code: `db.insert(${expr.table}, { ${fields.join(\", \")} })`, type: { kind: \"row\", table: expr.table, nullable: false } };\n }\n const index = selectIndex(env.catalog, expr.table, expr.keys, \"point\", undefined, (value) => inferExpr(value, env), expr.site);\n validateAddressedKeyFields(expr, index);\n const keys = expr.keys.map((part, offset) => {\n const emitted = keyBinding(emitExpr(part.value, env, writer));\n const local = temporary(`writeKey${offset + 1}`, part.site);\n writer.statement(`const ${local} = ${emitted.code};`, part.value.site);\n return { ...emitted, code: local };\n });\n const addressedFields = new Map(index.columns.map((column, offset) => [column, keys[offset]!.code]));\n if (index.name !== \"byId\" || keys.length !== 1) {\n return emitIndexedWrite(expr, env, writer, info.columns, index, keys);\n }\n const key = keys[0]!;\n if (expr.op === \"delete\") {\n writer.statement(`db.delete(${expr.table}, ${key.code});`, expr.site);\n return { code: \"null\", type: { kind: \"unknown\" }, effectOnly: true };\n }\n const writeFields = expr.op === \"update\"\n ? expr.fields.filter((field) => !addressedFields.has(field.name))\n : expr.fields;\n const usesFocal = writeFields.some((field) => field.value && mentionsFocal(field.value));\n if (!usesFocal && expr.op !== \"upsert\") {\n const fields = emitFields(writeFields, env, writer, info.columns);\n writer.statement(`db.${expr.op}(${expr.table}, ${key.code}, { ${fields.join(\", \")} });`, expr.site);\n return { code: \"null\", type: { kind: \"unknown\" }, effectOnly: true };\n }\n\n const prior = env.focal;\n const rowName = temporary(\"old\", expr.site);\n env.focal = { code: rowName, type: { kind: \"row\", table: expr.table, nullable: expr.op === \"upsert\" } };\n try {\n writer.raw(`db.${expr.op}(${expr.table}, ${key.code}, (${rowName}) => {`);\n writer.nested(() => {\n const fields = emitEvaluatedFields(\n writeFields,\n env,\n writer,\n info.columns,\n expr.op === \"upsert\" ? addressedFields : undefined,\n );\n if (expr.op === \"upsert\" && !expr.fields.some((field) => field.name === \"id\")) fields.unshift(`id: ${key.code}`);\n writer.statement(`return { ${fields.join(\", \")} };`, expr.site);\n });\n writer.statement(\"});\", expr.site);\n } finally {\n env.focal = prior;\n }\n return { code: \"null\", type: { kind: \"unknown\" }, effectOnly: true };\n}\n\n// @ref LLP 1001#1-store-storers \u2014 the engine's write address remains the\n// intrinsic scalar row id; Quarry resolves an alternate unique key before it\n// emits the base-table write rather than pretending the IR has composite ids.\nfunction emitIndexedWrite(\n expr: Extract<Expr, { kind: \"write\" }>,\n env: Environment,\n writer: Writer,\n columns: Map<string, ScalarType>,\n index: IndexDecl,\n keys: Emitted[],\n): Emitted {\n const row = temporary(\"writeRow\", expr.site);\n writer.statement(`const ${row} = db.get(${expr.table}.${index.name}, [${keys.map((key) => key.code).join(\", \")}]);`, expr.site);\n const addressedFields = new Map(index.columns.map((column, offset) => [column, keys[offset]!.code]));\n\n if (expr.op === \"delete\") {\n writer.statement(`db.require(${row} !== null, \"NOT_FOUND\");`, expr.site);\n writer.statement(`db.delete(${expr.table}, ${row}!.id);`, expr.site);\n return { code: \"null\", type: { kind: \"unknown\" }, effectOnly: true };\n }\n\n if (expr.op === \"update\") {\n writer.statement(`db.require(${row} !== null, \"NOT_FOUND\");`, expr.site);\n const prior = env.focal;\n env.focal = { code: `${row}!`, type: { kind: \"row\", table: expr.table, nullable: false } };\n try {\n const patch = expr.fields.filter((field) => !addressedFields.has(field.name));\n const fields = patch.some((field) => field.value && mentionsFocal(field.value))\n ? emitEvaluatedFields(patch, env, writer, columns)\n : emitFields(patch, env, writer, columns);\n writer.statement(`db.update(${expr.table}, ${row}!.id, { ${fields.join(\", \")} });`, expr.site);\n } finally {\n env.focal = prior;\n }\n return { code: \"null\", type: { kind: \"unknown\" }, effectOnly: true };\n }\n\n const prior = env.focal;\n env.focal = { code: row, type: { kind: \"row\", table: expr.table, nullable: true } };\n try {\n // @ref LLP 1011#b3-one-missing-row-rule-no-id-in-an-upsert-row \u2014 alternate\n // upsert preserves a present identity and mints only on its absent branch.\n const sourceFields = expr.fields;\n const key = temporary(\"upsertKey\", expr.site);\n const fields = emitEvaluatedFieldEntries(sourceFields, env, writer, columns, addressedFields);\n const authoredNames = new Set(sourceFields.map((field) => field.name));\n const injected = index.columns.flatMap((column, offset) =>\n authoredNames.has(column) ? [] : [{ name: column, value: keys[offset]!.code }]);\n fields.unshift(...injected);\n const addressedId = fields.find((field) => field.name === \"id\");\n writer.statement(`const ${key} = ${addressedId ? addressedId.value : `${row}?.id ?? ctx.newId()`};`, expr.site);\n const rowFields = fields.filter((field) => field.name !== \"id\").map(fieldCode);\n rowFields.unshift(`id: ${key}`);\n writer.statement(`db.upsert(${expr.table}, ${key}, { ${rowFields.join(\", \")} });`, expr.site);\n } finally {\n env.focal = prior;\n }\n return { code: \"null\", type: { kind: \"unknown\" }, effectOnly: true };\n}\n\nfunction emitFields(\n fields: ObjectField[],\n env: Environment,\n writer: Writer,\n columns: Map<string, ScalarType>,\n): string[] {\n return fields.map((field) => {\n const value = emitExpr(field.value ?? { kind: \"name\", name: field.name, site: field.site }, env, writer);\n const expected = field.name === \"id\" ? { kind: \"id\", optional: false } satisfies ScalarType : columns.get(field.name);\n validateFieldType(field, value.type, expected, env);\n const code = expected && (expected.kind === \"ref\" || expected.kind === \"id\") ? keyBinding(value).code : value.code;\n return `${property(field.name)}: ${code}`;\n });\n}\n\ntype EvaluatedField = { name: string; value: string };\n\nfunction emitEvaluatedFields(\n fields: ObjectField[],\n env: Environment,\n writer: Writer,\n columns: Map<string, ScalarType>,\n replacements: Map<string, string> = new Map(),\n): string[] {\n return emitEvaluatedFieldEntries(fields, env, writer, columns, replacements).map(fieldCode);\n}\n\nfunction emitEvaluatedFieldEntries(\n fields: ObjectField[],\n env: Environment,\n writer: Writer,\n columns: Map<string, ScalarType>,\n replacements: Map<string, string> = new Map(),\n): EvaluatedField[] {\n return fields.map((field) => {\n const replacement = replacements.get(field.name);\n if (replacement) return { name: field.name, value: replacement };\n const value = emitExpr(field.value ?? { kind: \"name\", name: field.name, site: field.site }, env, writer);\n const expected = field.name === \"id\" ? { kind: \"id\", optional: false } satisfies ScalarType : columns.get(field.name);\n validateFieldType(field, value.type, expected, env);\n const code = expected && (expected.kind === \"ref\" || expected.kind === \"id\") ? keyBinding(value).code : value.code;\n const local = temporary(\"patch\", field.site);\n writer.statement(`const ${local} = ${code};`, field.site);\n return { name: field.name, value: local };\n });\n}\n\nfunction fieldCode(field: EvaluatedField): string { return `${property(field.name)}: ${field.value}`; }\n\nfunction validateAddressedKeyFields(expr: Extract<Expr, { kind: \"write\" }>, index: IndexDecl): void {\n if (expr.op === \"delete\") return;\n const authoredId = expr.op === \"update\" || expr.op === \"upsert\"\n ? expr.fields.find((field) => field.name === \"id\")\n : undefined;\n if (authoredId) {\n typeError(\n authoredId.site,\n expr.op === \"upsert\"\n ? \"upsert rows may not name id; identity comes from the addressed row or is minted on insert\"\n : \"update patches may not name id; row identity is immutable\",\n quarryWriteWithoutField(expr, authoredId),\n );\n }\n for (const [offset, column] of index.columns.entries()) {\n const field = expr.fields.find((candidate) => candidate.name === column);\n if (!field) continue;\n const value = field.value ?? { kind: \"name\", name: field.name, site: field.site } satisfies Expr;\n if (quarryExpression(value) === quarryExpression(expr.keys[offset]!.value)) continue;\n typeError(\n field.site,\n `${expr.op} may not reassign addressed key column ${column}; the ${index.name} address is authoritative`,\n quarryWriteWithoutField(expr, field),\n );\n }\n}\n\nfunction quarryWriteWithoutField(expr: Extract<Expr, { kind: \"write\" }>, removed: ObjectField): string {\n const key = expr.op === \"insert\" ? \"\" : `[${expr.keys.map(quarryKeyPart).join(\", \")}]`;\n const fields = expr.op === \"delete\" ? \"\" : ` { ${expr.fields.filter((field) => field !== removed).map(quarryObjectField).join(\", \")} }`;\n return `${expr.op} ${expr.table}${key}${fields}`;\n}\n\nfunction quarryKeyPart(part: KeyPart): string {\n return `${part.column ? `${part.column} = ` : \"\"}${quarryExpression(part.value)}`;\n}\n\nfunction quarryObjectField(field: ObjectField): string {\n return field.value ? `${field.name}: ${quarryExpression(field.value)}` : field.name;\n}\n\nexport function quarryExpression(expr: Expr): string {\n if (expr.kind === \"name\") return expr.name;\n if (expr.kind === \"focal\") return \".\";\n if (expr.kind === \"literal\") return JSON.stringify(expr.value);\n if (expr.kind === \"array\") return `[${expr.items.map(quarryExpression).join(\", \")}]`;\n if (expr.kind === \"object\") return `{ ${expr.fields.map(quarryObjectField).join(\", \")} }`;\n if (expr.kind === \"unary\") return `${expr.op} (${quarryExpression(expr.value)})`;\n if (expr.kind === \"binary\") return `(${quarryExpression(expr.left)} ${expr.op} ${quarryExpression(expr.right)})`;\n if (expr.kind === \"member\") {\n return expr.base.kind === \"focal\"\n ? `.${expr.name}`\n : `(${quarryExpression(expr.base)}).${expr.name}`;\n }\n if (expr.kind === \"call\") return `${expr.name}(${expr.args.map(quarryExpression).join(\", \")})`;\n if (expr.kind === \"read\") {\n let rendered = `${expr.table}[${expr.keys.map(quarryKeyPart).join(\", \")}]`;\n if (expr.range?.cursor) rendered += ` ${expr.range.cursorKind ?? \"after\"} ${quarryExpression(expr.range.cursor)}`;\n if (expr.range) rendered += ` ${expr.range.order === \"asc\" ? \"first\" : \"last\"} ${expr.range.take}`;\n if (expr.index) rendered += ` by ${expr.index}`;\n if (expr.range?.where) rendered += ` where ${quarryExpression(expr.range.where.predicate)}`;\n return rendered;\n }\n if (expr.kind === \"merge\") {\n const cursor = expr.cursor ? ` ${expr.cursorKind ?? \"after\"} ${quarryExpression(expr.cursor)}` : \"\";\n const lanes = expr.lanes.map((lane) => ` [${lane.prefix.map(quarryExpression).join(\", \")}]${lane.loop ? ` for ${lane.loop.name} in ${quarryExpression(lane.loop.domain)}` : \"\"}`).join(\"\\n\");\n return `merge ${expr.table}${cursor} ${expr.order === \"asc\" ? \"first\" : \"last\"} ${expr.take} by ${expr.index}:\\n${lanes}`;\n }\n if (expr.kind === \"exists\" || expr.kind === \"created\") return `${expr.kind} ${quarryExpression(expr.read)}`;\n if (expr.kind === \"aggregate\") return `#${expr.table}[${expr.keys.map(quarryKeyPart).join(\", \")}]`;\n if (expr.kind === \"assert\") return `(${quarryExpression(expr.value)})! else ${expr.code}`;\n if (expr.kind === \"shapeUse\") return `(${quarryExpression(expr.base)}) ${expr.name}`;\n if (expr.kind === \"shape\") {\n if (expr.authoredName) return `(${quarryExpression(expr.base)}) ${expr.authoredName}`;\n const fields = (expr.authoredFields ?? expr.fields).map((field) => field.kind === \"spread\"\n ? \"*\"\n : field.kind === \"namedSpread\" ? `...${field.name}`\n : field.kind === \"bare\" ? field.name : `${field.name}: ${quarryExpression(field.value)}`);\n return `(${quarryExpression(expr.base)}) { ${fields.join(\", \")} }`;\n }\n if (expr.kind === \"walk\") return `walk ${expr.table}[${quarryExpression(expr.seed)}] up .${expr.column} depth ${expr.depth}`;\n return quarryWriteWithoutField(expr, { name: \"\", site: expr.site });\n}\n\nexport function quarryShapeDeclaration(shape: ShapeDecl): string {\n return `shape ${shape.name} = { ${shape.fields.map((field) => field.kind === \"spread\"\n ? \"*\"\n : field.kind === \"namedSpread\" ? `...${field.name}`\n : field.kind === \"bare\" ? field.name : `${field.name}: ${quarryExpression(field.value)}`).join(\", \")} }`;\n}\n\nfunction validateFieldType(\n field: ObjectField,\n actual: ValueType,\n expected: ScalarType | undefined,\n env: Environment,\n): void {\n const expression = field.value ?? { kind: \"name\", name: field.name, site: field.site } satisfies Expr;\n if (expected?.optional && expression.kind === \"literal\" && expression.value === null) return;\n if (expected?.kind === \"int\" && fractionalNumericLiteral(expression)) {\n typeError(field.site, \"int positions take integer literals\", `replace ${literalExpressionText(expression)} with an integer literal`);\n }\n if (expected?.kind === \"decimal\" || expected?.kind === \"money\") {\n if (numericLiteral(expression)) return;\n if (actual.kind === \"decimal\" || actual.kind === \"money\") return;\n typeError(field.site, `${field.name} is ${brandedName(expected)}; ${valueTypeName(actual)} is nominally different`, `use a ${brandedName(expected)} value`);\n }\n if ((actual.kind === \"decimal\" || actual.kind === \"money\") && expected) {\n typeError(field.site, `${field.name} is ${expected.kind}; ${brandedName(actual)} is nominally different`, `use a ${expected.kind} value`);\n }\n if (expected?.kind === \"principal\" && actual.kind !== \"principal\") {\n refuse(field.site, `${field.name} is principal; ${actual.kind} is nominally different (a ref/id is not a principal)`);\n }\n if ((expected?.kind === \"ref\" || expected?.kind === \"id\") && actual.kind === \"principal\") {\n refuse(field.site, `${field.name} is ${expected.kind}; principal is nominally different`);\n }\n const expectedAsset = nestedAssetShape(expected);\n const actualAsset = nestedAssetShape(actual);\n const acceptsAsset = expectedAsset\n ? assetExpressionAcceptsExpected(expression, actual, expected!, env)\n : !actualAsset;\n if ((expectedAsset || actualAsset) && !acceptsAsset) {\n const wrapperMismatch = expectedAsset && actualAsset && expectedAsset.kind === actualAsset.kind;\n const wanted = expectedAsset\n ? wrapperMismatch ? assetShapeName(expectedAsset) : `${expectedAsset.kind} asset`\n : \"non-asset\";\n const received = actualAsset\n ? wrapperMismatch ? assetShapeName(actualAsset) : `${actualAsset.kind} asset`\n : valueTypeName(actual);\n typeError(field.site, `${field.name} requires ${wanted} values at every nested asset position; received ${received}`, `use a ${wanted} value for ${field.name}`);\n }\n}\n\nfunction assetExpressionAcceptsExpected(\n expression: Expr,\n actual: ValueType,\n expected: ScalarType,\n env: Environment,\n): boolean {\n if (expected.kind === \"list\" && expression.kind === \"array\") {\n const inferredItem = actual.kind === \"list\" || actual.kind === \"sequence\"\n ? actual.item\n : { kind: \"unknown\" } satisfies ValueType;\n return expression.items.every((item) => assetExpressionAcceptsExpected(\n item,\n inferExpr(item, env) ?? inferredItem,\n expected.item,\n env,\n ));\n }\n return assetShapeAccepts(nestedAssetShape(expected), nestedAssetShape(actual));\n}\n\n// @ref LLP 1006#3-authoring-surface \u2014 list/optional wrappers do not erase the\n// nominal image/video kind of the closed record stored beneath them.\ntype AssetShape = {\n kind: \"image\" | \"video\";\n wrappers: Array<{ optional: boolean }>;\n leafOptional: boolean;\n};\n\nfunction nestedAssetShape(type: ValueType | undefined): AssetShape | undefined {\n if (!type) return undefined;\n if (type.kind === \"image\" || type.kind === \"video\") {\n return { kind: type.kind, wrappers: [], leafOptional: type.optional };\n }\n if (type.kind === \"list\" || type.kind === \"sequence\") {\n const nested = nestedAssetShape(type.item);\n if (nested) {\n return {\n ...nested,\n wrappers: [{ optional: type.kind === \"list\" && type.optional }, ...nested.wrappers],\n };\n }\n }\n return undefined;\n}\n\nfunction assetShapeAccepts(expected: AssetShape | undefined, actual: AssetShape | undefined): boolean {\n if (!expected || !actual || expected.kind !== actual.kind || expected.wrappers.length !== actual.wrappers.length) return false;\n if (actual.leafOptional && !expected.leafOptional) return false;\n return actual.wrappers.every((wrapper, index) => !wrapper.optional || expected.wrappers[index]!.optional);\n}\n\nfunction assetShapeName(shape: AssetShape): string {\n let name = `${shape.kind} asset${shape.leafOptional ? \" or null\" : \"\"}`;\n for (const wrapper of [...shape.wrappers].reverse()) name = `[${name}]${wrapper.optional ? \" or null\" : \"\"}`;\n return name;\n}\n\nfunction inferExpr(expr: Expr, env: Environment): ScalarType | undefined {\n if (expr.kind === \"name\") {\n const binding = env.bindings.get(expr.name)?.type;\n if (binding && isScalar(binding)) return binding;\n if (binding?.kind === \"row\") return { kind: \"ref\", table: binding.table, optional: binding.nullable };\n if (expr.name === \"viewer\") return { kind: \"principal\", optional: false };\n if (expr.name === \"new\") return { kind: \"id\", optional: false };\n if (expr.name === \"now\" || expr.name === \"commit\") return { kind: \"time\", optional: false };\n }\n if (expr.kind === \"focal\" && env.focal?.type.kind === \"row\") return { kind: \"ref\", table: env.focal.type.table, optional: env.focal.type.nullable };\n if (expr.kind === \"literal\") {\n const type = literalType(expr);\n return isScalar(type) ? type : undefined;\n }\n if (expr.kind === \"member\") {\n const base = inferExpr(expr.base, env);\n if (base?.kind === \"ref\" && base.table) {\n if (expr.name === \"id\") return { kind: \"ref\", table: base.table, optional: base.optional };\n return env.catalog.get(base.table)?.columns.get(expr.name);\n }\n }\n return undefined;\n}\n\nfunction literalType(expr: Extract<Expr, { kind: \"literal\" }>): ScalarType | NumericLiteralType {\n if (typeof expr.value === \"string\") return { kind: \"text\", max: Math.max(1, expr.value.length), optional: false };\n if (typeof expr.value === \"number\") {\n const digits = fractionalDigits(expr.numericText);\n return digits === 0 ? { kind: \"int\", optional: false } : { kind: \"numeric-literal\", fractionalDigits: digits };\n }\n if (typeof expr.value === \"boolean\") return { kind: \"bool\", optional: false };\n return { kind: \"text\", max: 1, optional: true };\n}\n\nfunction scalarOrUnknown(type: ValueType): ScalarType {\n return isScalar(type) ? type : { kind: \"text\", max: 1, optional: true };\n}\n\nfunction isScalar(type: ValueType): type is ScalarType {\n return [\"cursor\", \"text\", \"id\", \"principal\", \"int\", \"decimal\", \"money\", \"time\", \"bool\", \"json\", \"bytes\", \"image\", \"video\", \"enum\", \"ref\", \"list\"].includes(type.kind);\n}\n\nfunction isRef(type: ValueType): type is Extract<ScalarType, { kind: \"ref\" }> { return type.kind === \"ref\"; }\nfunction nonNullable(type: ValueType): ValueType {\n if (type.kind === \"row\") return { ...type, nullable: false };\n if (type.kind === \"object\") return { ...type, nullable: false };\n if (isScalar(type)) return { ...type, optional: false } as ScalarType;\n return type;\n}\nfunction nullableValue(type: ValueType): ValueType {\n if (type.kind === \"row\" || type.kind === \"object\") return { ...type, nullable: true };\n if (isScalar(type)) return { ...type, optional: true } as ScalarType;\n return { kind: \"unknown\" };\n}\nfunction isNullableValue(type: ValueType): boolean {\n if (type.kind === \"row\" || type.kind === \"object\") return type.nullable;\n if (type.kind === \"unknown\") return true;\n return isScalar(type) && type.optional;\n}\nfunction requireBoolean(expr: Expr, type: ValueType, construct: string): void {\n if (type.kind === \"bool\" && !type.optional) return;\n const nullable = (isScalar(type) && type.optional)\n || ((type.kind === \"row\" || type.kind === \"object\") && type.nullable);\n const spelling = expr.kind === \"name\" ? expr.name : expr.kind === \"member\" ? `${simpleExpr(expr.base)}.${expr.name}` : \"x\";\n typeError(\n expr.site,\n `${construct} requires a Boolean operand; got ${type.kind}${nullable ? \"?\" : \"\"}`,\n nullable ? `${spelling} != null` : `compare ${spelling} to a value so ${construct} receives a Boolean`,\n );\n}\nfunction simpleExpr(expr: Expr): string {\n if (expr.kind === \"name\") return expr.name;\n if (expr.kind === \"focal\") return \"\";\n if (expr.kind === \"member\") return `${simpleExpr(expr.base)}.${expr.name}`;\n return \"x\";\n}\nfunction optionalComparisonOperand(expr: Expr, type: ValueType): string {\n const rendered = simpleExpr(expr);\n const value = rendered === \"x\" ? `(${quarryExpression(expr)})` : rendered;\n return isNullableValue(type) ? `${value}!` : value;\n}\nfunction boolType(): ScalarType { return { kind: \"bool\", optional: false }; }\nfunction keyBinding(value: Emitted): Emitted {\n return value.type.kind === \"row\" ? { ...value, code: `${value.code}.id`, type: { kind: \"ref\", table: value.type.table, optional: value.type.nullable } } : value;\n}\nfunction compatible(left: ScalarType, right: ScalarType): boolean {\n if (left.kind === \"principal\" || right.kind === \"principal\") return left.kind === \"principal\" && right.kind === \"principal\";\n if (left.kind === \"ref\" || left.kind === \"id\") return right.kind === \"ref\" || right.kind === \"id\";\n if (right.kind === \"ref\" || right.kind === \"id\") return false;\n if ((left.kind === \"enum\" && right.kind === \"text\") || (left.kind === \"text\" && right.kind === \"enum\")) return true;\n if (left.kind === \"decimal\" || right.kind === \"decimal\") {\n return left.kind === \"decimal\" && right.kind === \"decimal\" && left.scale === right.scale;\n }\n if (left.kind === \"money\" || right.kind === \"money\") {\n return left.kind === \"money\" && right.kind === \"money\"\n && left.currency === right.currency && left.scale === right.scale;\n }\n return left.kind === right.kind;\n}\nfunction brandedType(type: ValueType): Extract<ScalarType, { kind: \"decimal\" | \"money\" }> | undefined {\n return type.kind === \"decimal\" || type.kind === \"money\" ? type : undefined;\n}\nfunction brandedName(type: Extract<ScalarType, { kind: \"decimal\" | \"money\" }>): string {\n return type.kind === \"decimal\" ? `decimal ${type.scale}` : `money ${type.currency} ${type.scale}`;\n}\nfunction numericAmountType(type: ValueType): type is Extract<ScalarType, { kind: \"int\" | \"decimal\" | \"money\" }> {\n return (type.kind === \"int\" || type.kind === \"decimal\" || type.kind === \"money\") && !type.optional;\n}\nfunction boundedItemType(type: ValueType): ValueType | undefined {\n if (type.kind === \"list\" || type.kind === \"sequence\") return type.item;\n if (type.kind === \"page\") return { kind: \"row\", table: type.table, nullable: false };\n return undefined;\n}\nfunction sameRecipientType(left: ValueType, right: ValueType): boolean {\n if (left.kind === \"row\" || right.kind === \"row\") {\n return left.kind === \"row\" && right.kind === \"row\" && left.table === right.table && !left.nullable && !right.nullable;\n }\n if (!isScalar(left) || !isScalar(right) || left.optional || right.optional) return false;\n if (left.kind !== right.kind) return false;\n if (left.kind === \"ref\" && right.kind === \"ref\") return left.table === right.table;\n if (left.kind === \"decimal\" && right.kind === \"decimal\") return left.scale === right.scale;\n if (left.kind === \"money\" && right.kind === \"money\") return left.currency === right.currency && left.scale === right.scale;\n return true;\n}\nfunction valueTypeName(type: ValueType): string {\n if (type.kind === \"numeric-literal\") return \"decimal literal\";\n if (type.kind === \"ref\") return `ref ${type.table}`;\n if (type.kind === \"row\") return `row ${type.table}`;\n return type.kind;\n}\nfunction numericLiteral(expr: Expr): boolean {\n return expr.kind === \"literal\" && typeof expr.value === \"number\"\n || expr.kind === \"unary\" && expr.op === \"-\" && numericLiteral(expr.value);\n}\nfunction fractionalNumericLiteral(expr: Expr): boolean {\n if (expr.kind === \"unary\" && expr.op === \"-\") return fractionalNumericLiteral(expr.value);\n return expr.kind === \"literal\" && typeof expr.value === \"number\" && fractionalDigits(expr.numericText) > 0;\n}\nfunction fractionalDigits(text: string | undefined): number {\n const dot = text?.indexOf(\".\") ?? -1;\n return dot < 0 ? 0 : text!.length - dot - 1;\n}\nfunction literalCode(expr: Extract<Expr, { kind: \"literal\" }>): string {\n return typeof expr.value === \"number\" ? expr.numericText ?? JSON.stringify(expr.value) : JSON.stringify(expr.value);\n}\nfunction literalExpressionText(expr: Expr): string {\n if (expr.kind === \"unary\" && expr.op === \"-\") return `-${literalExpressionText(expr.value)}`;\n return expr.kind === \"literal\" && typeof expr.value === \"number\" ? expr.numericText ?? String(expr.value) : \"the literal\";\n}\nfunction refuseFractionalInt(expr: Extract<Expr, { kind: \"binary\" }>, left: ValueType, right: ValueType): void {\n const fractional = left.kind === \"int\" && fractionalNumericLiteral(expr.right)\n ? expr.right\n : right.kind === \"int\" && fractionalNumericLiteral(expr.left) ? expr.left : undefined;\n if (fractional) {\n typeError(fractional.site, \"int positions take integer literals\", `replace ${literalExpressionText(fractional)} with an integer literal`);\n }\n}\nfunction literalNumber(expr: Expr | undefined): number | undefined { return expr?.kind === \"literal\" && typeof expr.value === \"number\" ? expr.value : undefined; }\nfunction property(value: string): string { return /^[A-Za-z_$][\\w$]*$/.test(value) ? value : JSON.stringify(value); }\nfunction title(value: string): string { return value.length === 0 ? value : value[0]!.toUpperCase() + value.slice(1); }\nfunction temporary(kind: string, site: Site): string { return `__q_${kind}_${site.line}_${site.col}`; }\nfunction formatSite(site: Site): string { return `${site.file}:${site.line}:${site.col}`; }\n\nfunction mentionsFocal(expr: Expr): boolean {\n if (expr.kind === \"focal\") return true;\n if (expr.kind === \"member\") return mentionsFocal(expr.base);\n if (expr.kind === \"binary\") return mentionsFocal(expr.left) || mentionsFocal(expr.right);\n if (expr.kind === \"unary\" || expr.kind === \"assert\") return mentionsFocal(expr.value);\n if (expr.kind === \"call\") return expr.args.some(mentionsFocal);\n if (expr.kind === \"array\") return expr.items.some(mentionsFocal);\n if (expr.kind === \"read\") {\n return expr.keys.some((key) => mentionsFocal(key.value))\n || (expr.range?.cursor !== undefined && mentionsFocal(expr.range.cursor));\n }\n if (expr.kind === \"merge\") return expr.lanes.some((lane) => lane.prefix.some(mentionsFocal));\n if (expr.kind === \"exists\" || expr.kind === \"created\") return mentionsFocal(expr.read);\n if (expr.kind === \"aggregate\") return expr.keys.some((key) => mentionsFocal(key.value));\n if (expr.kind === \"shapeUse\") return mentionsFocal(expr.base);\n if (expr.kind === \"shape\") return mentionsFocal(expr.base) || expr.fields.some((field) => field.kind === \"field\" && mentionsFocal(field.value));\n if (expr.kind === \"walk\") return mentionsFocal(expr.seed);\n if (expr.kind === \"object\") return expr.fields.some((field) => field.value !== undefined && mentionsFocal(field.value));\n if (expr.kind === \"write\") {\n return expr.keys.some((key) => mentionsFocal(key.value))\n || expr.fields.some((field) => field.value !== undefined && mentionsFocal(field.value));\n }\n return false;\n}\n", "import type {\n ArgDecl,\n ChannelDecl,\n ColumnDecl,\n Document,\n Expr,\n IndexDecl,\n KeyPart,\n MaintainDecl,\n MergeExpr,\n MergeLane,\n ObjectField,\n ProgramDecl,\n RuleDecl,\n ScalarType,\n ShapeDecl,\n ShapeField,\n Site,\n Stmt,\n TableDecl,\n} from \"./ast\";\nimport type { QuarryDiagnostic } from \"./ast\";\nimport { QuarryError, refuse, retention, syntax, unsupported } from \"./diagnostics\";\nimport { lex, type Token, type TokenKind } from \"./lexer\";\nimport { quarryExpression } from \"./program\";\n\nconst RESERVED_BINDINGS = new Set([\n \"arguments\", \"await\", \"break\", \"case\", \"catch\", \"class\", \"const\", \"continue\", \"debugger\", \"default\", \"delete\", \"do\",\n \"else\", \"enum\", \"eval\", \"export\", \"extends\", \"false\", \"finally\", \"for\", \"function\", \"if\", \"implements\", \"import\",\n \"in\", \"insert\", \"instanceof\", \"interface\", \"let\", \"merge\", \"new\", \"null\", \"package\", \"private\", \"protected\", \"public\", \"retain\", \"return\", \"static\",\n \"shape\", \"fn\", \"cursor\", \"super\", \"switch\", \"this\", \"throw\", \"true\", \"try\", \"typeof\", \"update\", \"upsert\", \"var\", \"void\", \"while\", \"with\", \"yield\",\n]);\nconst PRECEDENCE = new Map<string, number>([\n [\"??\", 1], [\"or\", 2], [\"and\", 3],\n [\"=\", 4], [\"!=\", 4], [\"<\", 4], [\"<=\", 4], [\">\", 4], [\">=\", 4],\n [\"+\", 5], [\"-\", 5], [\"*\", 6], [\"/\", 6], [\"%\", 6],\n]);\n\nexport function parseDocument(file: string, source: string): { document: Document; diagnostics: QuarryDiagnostic[] } {\n const lexical = lex(file, source);\n const parser = new Parser(lexical.tokens, file, lexical.diagnostics);\n return { document: parser.document(), diagnostics: parser.diagnostics };\n}\n\nclass Parser {\n private position = 0;\n private readonly tables: TableDecl[] = [];\n private readonly maintains: MaintainDecl[] = [];\n private readonly channels: ChannelDecl[] = [];\n private readonly effects: Array<{ name: string; module: string; site: Site }> = [];\n private readonly shapes: ShapeDecl[] = [];\n private readonly programs: ProgramDecl[] = [];\n private identity: Document[\"identity\"];\n\n constructor(private readonly tokens: Token[], private readonly file: string, readonly diagnostics: QuarryDiagnostic[]) {}\n\n document(): Document {\n while (!this.atKind(\"eof\")) {\n this.skipNewlines();\n if (this.atKind(\"eof\")) break;\n try {\n const token = this.peek();\n if (this.at(\"use\")) this.parseUse();\n else if (this.at(\"table\")) this.tables.push(this.parseTable());\n else if (this.at(\"maintain\")) this.maintains.push(this.parseMaintain());\n else if (this.at(\"channel\")) this.channels.push(this.parseChannel());\n else if (this.at(\"query\") || this.at(\"mutation\")) this.programs.push(this.parseProgram());\n else if (this.at(\"effect\")) this.effects.push(this.parseEffect());\n else if (this.at(\"shape\")) this.shapes.push(this.parseShapeDeclaration());\n else if (this.at(\"fn\") || this.at(\"cursor\")) unsupported(token, token.value, `${token.value} is reserved for a future Quarry form; rename this declaration`);\n else if (this.at(\"schedule\")) unsupported(token, \"schedule\", \"perform the bounded work in a named mutation invoked by the caller\");\n else if (this.at(\"index\") || this.at(\"unique\")) syntax(token, \"top-level indexes are invalid; place by/unique inside the table block\", \"move the index line into its table block\");\n else if (this.at(\"device\") || this.at(\"oblivious\")) unsupported(token, token.value, \"pass an explicit bounded argument to the operation\");\n else syntax(token, `unexpected top-level ${JSON.stringify(token.value)}`);\n } catch (error) {\n this.capture(error);\n this.recoverTopLevel();\n }\n }\n return {\n file: this.file,\n identity: this.identity,\n tables: this.tables,\n maintains: this.maintains,\n channels: this.channels,\n effects: this.effects,\n shapes: this.shapes,\n programs: this.programs,\n };\n }\n\n private parseUse(): void {\n const site = this.take(\"use\");\n const kind = this.word();\n if (kind.value !== \"identity\") unsupported(kind, `use ${kind.value}`, \"use identity password, use identity guests, or use identity\");\n let password = true;\n let guests = true;\n if (this.at(\"password\")) { this.take(\"password\"); guests = false; }\n else if (this.at(\"guests\")) { this.take(\"guests\"); password = false; }\n this.identity = { password, guests };\n this.endLine(site);\n }\n\n private parseTable(): TableDecl {\n const site = this.take(\"table\");\n const name = this.generatedBinding(\"table\");\n this.take(\":\");\n this.newline();\n this.takeKind(\"indent\");\n const columns: ColumnDecl[] = [];\n const indexes: IndexDecl[] = [];\n const rules: RuleDecl[] = [];\n const immutable: Array<{ columns: string[]; site: Site }> = [];\n const finalExists: TableDecl[\"finalExists\"] = [];\n let retain: TableDecl[\"retain\"];\n let publicDecl: TableDecl[\"public\"];\n while (!this.atKind(\"dedent\") && !this.atKind(\"eof\")) {\n this.skipNewlines();\n if (this.atKind(\"dedent\")) break;\n try {\n if (this.at(\"public\")) {\n const publicSite = this.take(\"public\");\n const reason = this.atKind(\"string\") ? this.takeKind(\"string\").value : `${name} is public in Quarry`;\n publicDecl = { reason, site: publicSite };\n this.newline();\n } else if (this.at(\"by\")) indexes.push(this.parseIndex(false));\n else if (this.at(\"unique\")) indexes.push(this.parseIndex(true));\n else if (this.at(\"immutable\")) immutable.push(this.parseImmutable());\n else if (this.at(\"retain\")) {\n if (retain) retention(this.peek(), `table ${name} has more than one retain line`);\n retain = this.parseRetention();\n }\n else if (this.at(\"after\")) finalExists.push(this.parseFinalExists());\n else if ([\"read\", \"insert\", \"update\", \"delete\"].includes(this.peek().value)) rules.push(this.parseRule());\n else columns.push(this.parseColumn());\n } catch (error) {\n this.capture(error);\n this.recoverLine();\n }\n }\n this.takeKind(\"dedent\");\n return { name, columns, indexes, rules, immutable, finalExists, ...(retain ? { retain } : {}), ...(publicDecl ? { public: publicDecl } : {}), site };\n }\n\n private parseRetention(): NonNullable<TableDecl[\"retain\"]> {\n const site = this.take(\"retain\");\n if (!this.atKind(\"word\")) retention(site, \"retain requires a policy word\");\n const policy = this.word();\n if (policy.value !== \"until-revoked\" && policy.value !== \"delivered-history\") {\n retention(site, `unknown retention policy ${policy.value}`);\n }\n if (!this.atKind(\"newline\")) retention(site, \"retain accepts exactly one policy word\");\n this.newline();\n return { policy: policy.value, site };\n }\n\n private parseImmutable(): { columns: string[]; site: Site } {\n const site = this.take(\"immutable\");\n const columns = [this.word().value];\n while (this.maybe(\",\")) columns.push(this.word().value);\n this.newline();\n return { columns, site };\n }\n\n private parseFinalExists(): TableDecl[\"finalExists\"][number] {\n const site = this.take(\"after\");\n this.take(\"insert\");\n const value = this.parseFocalRuleValue(\"after insert\", site);\n if (value.kind !== \"exists\") syntax(value.site, \"after insert requires exactly one exists predicate\");\n this.newline();\n return { value, site };\n }\n\n private parseColumn(): ColumnDecl {\n const name = this.word();\n this.take(\":\");\n const type = this.parseType();\n if (type.kind === \"cursor\") syntax(name, \"cursor is an operation argument type, not a table column\", \"use c: cursor ? on a query\");\n this.newline();\n return { name: name.value, type, site: name };\n }\n\n private parseIndex(unique: boolean): IndexDecl {\n const site = this.take(unique ? \"unique\" : \"by\");\n let explicit: string | undefined;\n if (this.atKind(\"word\") && this.peek(1).value === \":\") {\n explicit = this.word().value;\n this.take(\":\");\n }\n const columns = [this.word().value];\n while (this.maybe(\",\")) columns.push(this.word().value);\n this.newline();\n const inferred = `by${columns.map(title).join(\"\")}`;\n return { name: explicit ?? inferred, columns, unique, site };\n }\n\n private parseMaintain(): MaintainDecl {\n const site = this.take(\"maintain\");\n const name = this.word().value;\n this.take(\"=\");\n const aggregateToken = this.word();\n if (aggregateToken.value !== \"count\" && aggregateToken.value !== \"sum\") {\n unsupported(aggregateToken, `maintain ${aggregateToken.value}`, \"use maintain name = count table by columns or maintain name = sum table of intColumn by columns\");\n }\n const source = this.word().value;\n let column: string | undefined;\n if (aggregateToken.value === \"sum\") {\n this.take(\"of\");\n column = this.word().value;\n }\n this.take(\"by\");\n const by = [this.word().value];\n while (this.maybe(\",\")) by.push(this.word().value);\n this.take(\":\");\n this.newline();\n this.takeKind(\"indent\");\n let read: RuleDecl | undefined;\n let readable: RuleDecl | undefined;\n while (!this.atKind(\"dedent\") && !this.atKind(\"eof\")) {\n this.skipNewlines();\n if (this.atKind(\"dedent\")) break;\n try {\n const effect = this.word();\n if (effect.value !== \"read\" && effect.value !== \"readable\") syntax(effect, `unknown maintain property ${effect.value}`);\n const value = this.parseFocalRuleValue(effect.value, effect);\n this.newline();\n const declaration: RuleDecl = { effect: \"read\", bindings: [], value, site: effect };\n if (effect.value === \"read\") read = declaration;\n else readable = declaration;\n } catch (error) {\n this.capture(error);\n this.recoverLine();\n }\n }\n this.takeKind(\"dedent\");\n if (!read) syntax(site, `maintain ${name} requires read <- rule`);\n return { name, aggregate: aggregateToken.value as \"count\" | \"sum\", source, ...(column ? { column } : {}), by, read, ...(readable ? { readable } : {}), site };\n }\n\n private parseEffect(): { name: string; module: string; site: Site } {\n const site = this.take(\"effect\");\n const name = this.generatedBinding(\"effect\");\n this.take(\"from\");\n const module = this.word().value;\n this.newline();\n return { name, module, site };\n }\n\n private parseRule(): RuleDecl {\n const effectToken = this.word();\n const effect = effectToken.value as RuleDecl[\"effect\"];\n let bindings: string[] = [];\n let value: Expr;\n if (this.at(\"(\")) {\n this.take(\"(\");\n bindings = [this.generatedBinding(\"rule\")];\n while (this.maybe(\",\")) bindings.push(this.generatedBinding(\"rule\"));\n this.take(\")\");\n if (effect !== \"update\" || bindings.length !== 2) {\n syntax(effectToken, `${effect} rules use <- for one row; only update (old, next) has named bindings`, `rewrite the ${effect} rule with <- and direct .field terms`);\n }\n this.take(\"<-\");\n value = this.expression(0, new Set([\"<newline>\"]));\n } else {\n value = this.parseFocalRuleValue(effect, effectToken);\n }\n this.newline();\n return { effect, bindings, value, site: effectToken };\n }\n\n private parseFocalRuleValue(label: string, site: Site): Expr {\n if (this.maybe(\"<-\")) return this.expression(0, new Set([\"<newline>\"]));\n const binding = this.word().value;\n this.take(\"<-\");\n const value = this.expression(0, new Set([\"<newline>\"]));\n syntax(\n site,\n `${label} rules use the focal row . and do not take a named single-row binding`,\n `${label} <- ${quarryExpression(focalizeRuleBinding(value, binding))}`,\n );\n }\n\n private parseChannel(): ChannelDecl {\n const site = this.take(\"channel\");\n const name = this.generatedBinding(\"channel\");\n const args = this.parseArgs();\n this.take(\":\");\n this.newline();\n this.takeKind(\"indent\");\n let publish: Expr | undefined;\n let subscribe: Expr | undefined;\n let ttlSeconds: number | undefined;\n while (!this.atKind(\"dedent\") && !this.atKind(\"eof\")) {\n this.skipNewlines();\n if (this.atKind(\"dedent\")) break;\n try {\n const key = this.word();\n if (key.value === \"publish\" || key.value === \"subscribe\") {\n this.take(\"<-\");\n const value = this.expression(0, new Set([\"<newline>\"]));\n if (key.value === \"publish\") publish = value;\n else subscribe = value;\n } else if (key.value === \"ttl\") {\n const amount = this.number();\n if (this.at(\"s\")) this.take(\"s\");\n ttlSeconds = amount;\n } else {\n syntax(key, `unknown channel property ${key.value}`);\n }\n this.newline();\n } catch (error) {\n this.capture(error);\n this.recoverLine();\n }\n }\n this.takeKind(\"dedent\");\n if (!publish) syntax(site, `channel ${name} requires publish <- ...`);\n if (!subscribe) syntax(site, `channel ${name} requires subscribe <- ...`);\n if (ttlSeconds === undefined) syntax(site, `channel ${name} requires ttl Ns`);\n return { name, args, publish, subscribe, ttlSeconds, site };\n }\n\n private parseProgram(): ProgramDecl {\n const kindToken = this.word();\n const kind = kindToken.value as ProgramDecl[\"kind\"];\n const name = this.generatedBinding(\"operation\");\n const args = this.parseArgs();\n if (this.at(\"->\")) unsupported(this.peek(), \"result annotations\", \"results are inferred; remove the annotation\");\n this.take(\":\");\n this.newline();\n const body = this.parseBlock();\n if (body.length === 0) syntax(kindToken, `${kind} ${name} has an empty body`);\n return { kind, name, args, body, site: kindToken };\n }\n\n private parseShapeDeclaration(): ShapeDecl {\n const site = this.take(\"shape\");\n const name = this.generatedBinding(\"shape\");\n this.take(\"=\");\n this.take(\"{\");\n const fields = this.parseShapeFields();\n this.take(\"}\");\n this.newline();\n return { name, fields, site };\n }\n\n private generatedBinding(kind: \"table\" | \"channel\" | \"effect\" | \"operation\" | \"merge lane\" | \"shape\" | \"argument\" | \"local\" | \"loop\" | \"match\" | \"rule\"): string {\n const token = this.word();\n if (RESERVED_BINDINGS.has(token.value)) {\n refuse(\n token,\n `${kind} name ${token.value} is reserved and cannot become a generated TypeScript binding`,\n `rename the ${kind} ${token.value} to an identifier that is not reserved by JavaScript`,\n );\n }\n return token.value;\n }\n\n private parseArgs(): ArgDecl[] {\n this.take(\"(\");\n const args: ArgDecl[] = [];\n while (!this.at(\")\")) {\n const name = this.peek();\n const binding = this.generatedBinding(\"argument\");\n this.take(\":\");\n args.push({ name: binding, type: this.parseType(), site: name });\n if (!this.maybe(\",\")) break;\n }\n this.take(\")\");\n return args;\n }\n\n private parseType(): ScalarType {\n const site = this.peek();\n let type: ScalarType;\n if (this.maybe(\"[\")) {\n const item = this.parseType();\n this.take(\"]\");\n this.take(\"<=\");\n type = { kind: \"list\", item, max: this.number(), optional: false };\n } else {\n const name = this.word();\n if (name.value === \"text\") {\n let min: number | undefined;\n let max: number;\n if (this.maybe(\"<=\")) max = this.number();\n else {\n min = this.number();\n this.take(\".\");\n this.take(\".\");\n max = this.number();\n }\n let format: \"handle\" | \"url\" | undefined;\n if (this.maybe(\"format\")) {\n const value = this.word();\n if (value.value !== \"handle\" && value.value !== \"url\") syntax(value, `unknown text format ${value.value}`);\n format = value.value;\n }\n type = { kind: \"text\", ...(min === undefined ? {} : { min }), max, ...(format ? { format } : {}), optional: false };\n } else if (name.value === \"decimal\") {\n type = { kind: \"decimal\", scale: this.scale(\"decimal 12\"), optional: false };\n } else if (name.value === \"money\") {\n const currency = this.word();\n if (!/^[A-Z]{3}$/.test(currency.value)) {\n syntax(currency, \"money currency must be exactly three uppercase letters\", \"use money USD or money USD 2\");\n }\n const explicitScale = this.atKind(\"number\");\n type = {\n kind: \"money\",\n currency: currency.value,\n scale: explicitScale ? this.scale(`money ${currency.value} 12`) : 2,\n ...(explicitScale ? { explicitScale: true } : {}),\n optional: false,\n };\n } else if ([\"json\", \"bytes\", \"image\", \"video\"].includes(name.value)) {\n this.take(\"<=\");\n type = { kind: name.value as \"json\" | \"bytes\" | \"image\" | \"video\", max: this.number(), optional: false };\n } else if ([\"cursor\", \"id\", \"principal\", \"int\", \"time\", \"bool\"].includes(name.value)) {\n type = { kind: name.value as \"cursor\" | \"id\" | \"principal\" | \"int\" | \"time\" | \"bool\", optional: false };\n } else if (name.value === \"enum\") {\n this.take(\"(\");\n const variants: string[] = [];\n while (!this.at(\")\")) {\n variants.push(this.takeKind(\"string\").value);\n if (!this.maybe(\",\")) break;\n }\n this.take(\")\");\n type = { kind: \"enum\", variants, optional: false };\n } else {\n type = { kind: \"ref\", table: name.value, optional: false };\n }\n }\n if (this.maybe(\"?\")) type = { ...type, optional: true };\n if (type.kind === \"list\" && type.item.optional) syntax(site, \"list element types cannot be optional\");\n return type;\n }\n\n private parseBlock(): Stmt[] {\n this.takeKind(\"indent\");\n const body: Stmt[] = [];\n while (!this.atKind(\"dedent\") && !this.atKind(\"eof\")) {\n this.skipNewlines();\n if (this.atKind(\"dedent\")) break;\n try {\n body.push(this.parseStatement());\n } catch (error) {\n this.capture(error);\n this.recoverStatement();\n }\n }\n this.takeKind(\"dedent\");\n return body;\n }\n\n private parseStatement(): Stmt {\n if (this.at(\"while\")) unsupported(this.peek(), \"while\", \"use a bounded for domain or walk\");\n if (this.at(\"if\")) return this.parseIf();\n if (this.at(\"for\")) return this.parseFor();\n if (this.at(\"match\")) return this.parseMatch();\n if (this.at(\"require\")) return this.parseRequire();\n if (this.at(\"return\")) {\n const site = this.take(\"return\");\n const value = this.expression(0, new Set([\"<newline>\"]));\n if (value.kind !== \"merge\") this.newline();\n return { kind: \"return\", value, site };\n }\n if (this.at(\"emit\")) {\n const site = this.take(\"emit\");\n const effect = this.word().value;\n const payload = this.expression(0, new Set([\"<newline>\"]));\n this.newline();\n return { kind: \"emit\", effect, payload, site };\n }\n if (this.at(\"device\") || this.at(\"oblivious\")) unsupported(this.peek(), this.peek().value, \"pass an explicit bounded argument to the operation\");\n\n if (this.atKind(\"word\") && this.peek(1).value === \"=\") {\n const name = this.peek();\n const binding = this.generatedBinding(\"local\");\n this.take(\"=\");\n const value = this.expression(0, new Set([\"<newline>\"]));\n if (value.kind !== \"merge\") this.newline();\n return { kind: \"bind\", names: [binding], value, site: name };\n }\n if (this.at(\"(\") && this.tupleBindingAhead()) {\n const site = this.take(\"(\");\n const names = [this.generatedBinding(\"local\")];\n while (this.maybe(\",\")) names.push(this.generatedBinding(\"local\"));\n this.take(\")\");\n this.take(\"=\");\n const value = this.expression(0, new Set([\"<newline>\"]));\n this.newline();\n return { kind: \"bind\", names, value, site };\n }\n const value = this.expression(0, new Set([\"<newline>\"]));\n if (value.kind !== \"merge\") this.newline();\n return { kind: \"expr\", value, site: value.site };\n }\n\n private parseIf(): Stmt {\n const site = this.take(\"if\");\n const condition = this.expression(0, new Set([\":\"]));\n this.take(\":\");\n this.newline();\n const thenBody = this.parseBlock();\n let elseBody: Stmt[] = [];\n if (this.at(\"else\")) {\n this.take(\"else\");\n this.take(\":\");\n this.newline();\n elseBody = this.parseBlock();\n }\n return { kind: \"if\", condition, thenBody, elseBody, site };\n }\n\n private parseFor(): Stmt {\n const site = this.take(\"for\");\n const name = this.generatedBinding(\"loop\");\n this.take(\"in\");\n const domain = this.expression(0, new Set([\":\"]));\n this.take(\":\");\n this.newline();\n return { kind: \"for\", name, domain, body: this.parseBlock(), site };\n }\n\n private parseRequire(): Stmt {\n const site = this.take(\"require\");\n const condition = this.expression(0, new Set([\"else\"]));\n this.take(\"else\");\n const code = this.word().value;\n this.newline();\n return { kind: \"require\", condition, code, site };\n }\n\n private parseMatch(): Stmt {\n const site = this.take(\"match\");\n const read = this.expression(0, new Set([\":\"]));\n if (read.kind !== \"read\" || read.range) syntax(read.site, \"match requires a point read t[key]\");\n this.take(\":\");\n this.newline();\n this.takeKind(\"indent\");\n this.take(\"some\");\n const someName = this.generatedBinding(\"match\");\n this.take(\":\");\n this.newline();\n const someBody = this.parseBlock();\n this.take(\"none\");\n this.take(\":\");\n this.newline();\n const noneBody = this.parseBlock();\n this.takeKind(\"dedent\");\n return { kind: \"match\", read, someName, someBody, noneBody, site };\n }\n\n private expression(minimum = 0, stops = new Set<string>()): Expr {\n let left = this.prefix(stops);\n for (;;) {\n const token = this.peek();\n if (this.isStop(token, stops)) break;\n const precedence = PRECEDENCE.get(token.value);\n if (precedence === undefined || precedence < minimum) break;\n this.position += 1;\n const right = this.expression(precedence + (token.value === \"??\" ? 0 : 1), stops);\n left = { kind: \"binary\", op: token.value, left, right, site: token };\n }\n return left;\n }\n\n private prefix(stops: Set<string>): Expr {\n const token = this.peek();\n if (token.value === \"not\") {\n this.position += 1;\n return this.postfix({ kind: \"unary\", op: \"not\", value: this.expression(7, stops), site: token }, stops);\n }\n if (token.value === \"-\" && !(this.peek(1).kind === \"word\" && this.peek(2).value === \"[\")) {\n this.position += 1;\n return this.postfix({ kind: \"unary\", op: \"-\", value: this.expression(7, stops), site: token }, stops);\n }\n if (token.value === \"exists\") {\n this.position += 1;\n const value = this.prefix(stops);\n if (value.kind !== \"read\" || value.range) syntax(value.site, \"exists requires an indexed read t[key]\");\n return { kind: \"exists\", read: value, site: token };\n }\n if (token.value === \"created\") {\n this.position += 1;\n const value = this.prefix(stops);\n if (value.kind !== \"read\" || value.range) syntax(value.site, \"created requires an indexed read t[key]\");\n return { kind: \"created\", read: value, site: token };\n }\n if (token.value === \"walk\") return this.parseWalk();\n // @ref LLP 1010#a1-words-for-writes \u2014 the four writes have one word form;\n // sigils are syntax errors rather than a compatibility lane.\n if ([\"insert\", \"update\", \"upsert\", \"delete\"].includes(token.value)) return this.parseWrite();\n if ((token.value === \"+\" && (this.peek(1).kind === \"word\" || this.peek(1).value === \"~\"))\n || token.value === \"~\"\n || (token.value === \"-\" && this.peek(1).kind === \"word\" && this.peek(2).value === \"[\")) {\n syntax(token, \"write sigils are invalid; use insert, update, upsert, or delete\", \"use insert, update, upsert, or delete\");\n }\n if (token.value === \"#\") {\n this.position += 1;\n const table = this.word();\n const read = this.parseRead(table.value, table);\n return { kind: \"aggregate\", table: table.value, keys: read.keys, site: token };\n }\n if (token.value === \"merge\") return this.parseMerge();\n if (token.value === \"device\" || token.value === \"oblivious\") unsupported(token, token.value, \"pass an explicit bounded argument to the operation\");\n\n let value: Expr;\n if (token.kind === \"string\") {\n this.position += 1;\n value = { kind: \"literal\", value: token.value, site: token };\n } else if (token.kind === \"number\") {\n this.position += 1;\n value = { kind: \"literal\", value: Number(token.value), numericText: token.value, site: token };\n } else if (token.value === \"true\" || token.value === \"false\" || token.value === \"null\") {\n this.position += 1;\n value = { kind: \"literal\", value: token.value === \"null\" ? null : token.value === \"true\", site: token };\n } else if (token.value === \".\") {\n this.position += 1;\n value = { kind: \"focal\", site: token };\n if (this.atKind(\"word\")) value = { kind: \"member\", base: value, name: this.word().value, site: token };\n } else if (token.value === \"[\") {\n this.position += 1;\n const items: Expr[] = [];\n while (!this.at(\"]\")) {\n items.push(this.expression(0, new Set([\",\", \"]\"])));\n if (!this.maybe(\",\")) break;\n }\n this.take(\"]\");\n value = { kind: \"array\", items, site: token };\n } else if (token.value === \"{\") {\n value = { kind: \"object\", fields: this.parseObjectFields(), site: token };\n } else if (token.value === \"(\") {\n this.position += 1;\n const first = this.expression(0, new Set([\",\", \")\"]));\n if (this.maybe(\",\")) {\n const items = [first];\n do {\n items.push(this.expression(0, new Set([\",\", \")\"])));\n } while (this.maybe(\",\"));\n value = { kind: \"array\", items, site: token };\n } else {\n value = first;\n }\n this.take(\")\");\n } else if (token.kind === \"word\") {\n this.position += 1;\n value = { kind: \"name\", name: token.value, site: token };\n } else {\n syntax(token, `expected expression, got ${JSON.stringify(token.value)}`);\n }\n return this.postfix(value, stops);\n }\n\n private postfix(initial: Expr, stops: Set<string>): Expr {\n let value = initial;\n for (;;) {\n if (this.at(\".\") && this.peek(1).kind === \"word\") {\n const site = this.take(\".\");\n const name = this.word().value;\n value = { kind: \"member\", base: value, name, site };\n } else if (this.at(\"(\") && value.kind === \"name\") {\n const site = this.take(\"(\");\n const args: Expr[] = [];\n while (!this.at(\")\")) {\n args.push(this.expression(0, new Set([\",\", \")\"])));\n if (!this.maybe(\",\")) break;\n }\n this.take(\")\");\n value = { kind: \"call\", name: value.name, args, site };\n } else if (this.at(\"[\") && value.kind === \"name\") {\n value = this.parseRead(value.name, value.site);\n } else if (value.kind === \"read\" && this.at(\"where\")) {\n const site = this.take(\"where\");\n const predicate = this.expression(0, new Set([\"<newline>\", \"{\", \",\", \"}\"]));\n value = { ...value, range: { ...value.range!, where: { predicate, site } } };\n } else if (value.kind === \"read\" && this.at(\"before\")) {\n unsupported(this.peek(), \"before\", \"use after c; reverse display order in the client when needed\");\n } else if (value.kind === \"read\" && [\"after\", \"first\", \"last\", \"by\"].includes(this.peek().value)) {\n value = this.parseRange(value);\n } else if (this.maybe(\"!\")) {\n const assertion = this.tokens[this.position - 1]!;\n let code = \"NOT_FOUND\";\n if (this.maybe(\"else\")) code = this.word().value;\n value = { kind: \"assert\", value, code, site: assertion };\n } else if (this.at(\"{\")) {\n value = this.parseShape(value);\n } else if (this.atKind(\"word\") && !PRECEDENCE.has(this.peek().value)\n && !stops.has(this.peek().value) && ![\"else\", \"some\", \"none\", \"for\", \"in\"].includes(this.peek().value)) {\n const named = this.word();\n value = { kind: \"shapeUse\", base: value, name: named.value, site: named };\n } else {\n break;\n }\n }\n return value;\n }\n\n private parseRead(table: string, site: Site): Extract<Expr, { kind: \"read\" }> {\n this.take(\"[\");\n const keys: KeyPart[] = [];\n while (!this.at(\"]\")) {\n const keySite = this.peek();\n let column: string | undefined;\n if (this.atKind(\"word\") && this.peek(1).value === \"=\") {\n column = this.word().value;\n this.take(\"=\");\n }\n const value = this.expression(0, new Set([\",\", \"]\"]));\n keys.push({ column, value, site: keySite });\n if (!this.maybe(\",\")) break;\n }\n this.take(\"]\");\n return { kind: \"read\", table, keys, site };\n }\n\n private parseRange(read: Extract<Expr, { kind: \"read\" }>): Extract<Expr, { kind: \"read\" }> {\n // @ref LLP 1010#a7-one-modifier-order \u2014 retain the first value for each\n // modifier while parsing the whole read so a refusal can paste one canonical form.\n let order: \"asc\" | \"desc\" | undefined;\n let take: number | undefined;\n let cursor: Expr | undefined;\n let cursorKind: \"after\" | undefined;\n const site = this.peek();\n let index = read.index;\n let highestRank = -1;\n const seen = new Set<number>();\n let violation: Token | undefined;\n while ([\"after\", \"first\", \"last\", \"by\"].includes(this.peek().value)) {\n const key = this.word();\n const rank = key.value === \"after\" ? 0\n : key.value === \"first\" || key.value === \"last\" ? 1\n : 2;\n if (!violation && (seen.has(rank) || rank < highestRank)) violation = key;\n seen.add(rank);\n highestRank = Math.max(highestRank, rank);\n if (key.value === \"after\") {\n const candidate = this.expression(0, new Set([\"after\", \"first\", \"last\", \"by\", \"where\", \"<newline>\", \":\", \"{\", \",\", \"}\"]));\n if (!cursor) {\n cursorKind = key.value;\n cursor = candidate;\n }\n } else if (key.value === \"first\" || key.value === \"last\") {\n const candidate = this.number();\n if (take === undefined) {\n order = key.value === \"first\" ? \"asc\" : \"desc\";\n take = candidate;\n }\n } else if (key.value === \"by\") {\n const candidate = this.word().value;\n if (!index) index = candidate;\n }\n }\n if (take === undefined && !cursor) {\n const point = { ...read, index };\n if (violation) syntax(violation, \"read modifiers may appear once and only in canonical order\", quarryExpression(point));\n return point;\n }\n if (take === undefined || !order) syntax(site, \"range reads require first N or last N\");\n const range = { ...read, index, range: { order, take, cursor, cursorKind, site } };\n if (violation) syntax(violation, \"read modifiers may appear once and only in canonical order\", quarryExpression(range));\n return range;\n }\n\n private parseMerge(): MergeExpr {\n const site = this.take(\"merge\");\n const table = this.word().value;\n let cursor: Expr | undefined;\n let cursorKind: \"after\" | undefined;\n if (this.at(\"before\")) unsupported(this.peek(), \"before\", \"use after c in the merge header\");\n if (this.at(\"after\")) {\n cursorKind = this.word().value as \"after\";\n cursor = this.expression(0, new Set([\"first\", \"last\", \"by\", \":\"]));\n }\n const bound = this.peek();\n if (!this.at(\"first\") && !this.at(\"last\")) {\n syntax(bound, \"merge modifiers use [after cursor] first|last N by index\", `merge ${table} first 20 by index:`);\n }\n const order = this.word().value === \"first\" ? \"asc\" : \"desc\";\n const take = this.number();\n if (!this.at(\"by\")) {\n const cursorText = cursor ? ` ${cursorKind} ${this.renderExpr(cursor)}` : \"\";\n syntax(this.peek(), \"merge requires by <index> in its header\", `merge ${table}${cursorText} ${order === \"asc\" ? \"first\" : \"last\"} ${take} by index:`);\n }\n this.take(\"by\");\n const index = this.word().value;\n this.take(\":\");\n this.newline();\n if (!this.atKind(\"indent\")) {\n syntax(this.peek(), \"merge requires an indented block with at least one [prefix] lane\", `[viewer]`);\n }\n this.takeKind(\"indent\");\n const lanes: MergeLane[] = [];\n while (!this.atKind(\"dedent\") && !this.atKind(\"eof\")) {\n this.skipNewlines();\n if (this.atKind(\"dedent\")) break;\n const laneSite = this.take(\"[\");\n const prefix: Expr[] = [];\n while (!this.at(\"]\")) {\n prefix.push(this.expression(0, new Set([\",\", \"]\"])));\n if (!this.maybe(\",\")) break;\n }\n this.take(\"]\");\n let loop: MergeLane[\"loop\"];\n if (this.maybe(\"for\")) {\n const name = this.generatedBinding(\"merge lane\");\n this.take(\"in\");\n const domain = this.expression(0, new Set([\"<newline>\"]));\n if (domain.kind !== \"read\" || !domain.range) {\n syntax(domain.site, \"a merge for lane requires a bounded range read\", \"for row in table[prefix] first 50 by index\");\n }\n loop = { name, domain };\n }\n this.newline();\n lanes.push({ prefix, ...(loop ? { loop } : {}), site: laneSite });\n }\n this.takeKind(\"dedent\");\n if (lanes.length === 0) syntax(site, \"merge requires at least one lane\", `[viewer]`);\n return { kind: \"merge\", table, index, order, take, cursor, cursorKind, lanes, site };\n }\n\n private renderExpr(expr: Expr): string {\n return quarryExpression(expr);\n }\n\n private parseShape(base: Expr): Expr {\n const site = this.take(\"{\");\n const fields = this.parseShapeFields();\n this.take(\"}\");\n return { kind: \"shape\", base, fields, site };\n }\n\n private parseShapeFields(): ShapeField[] {\n const fields: ShapeField[] = [];\n while (!this.at(\"}\")) {\n const fieldSite = this.peek();\n if (this.maybe(\"*\")) fields.push({ kind: \"spread\", site: fieldSite });\n else if (this.at(\".\") && this.peek(1).value === \".\" && this.peek(2).value === \".\") {\n this.take(\".\");\n this.take(\".\");\n this.take(\".\");\n fields.push({ kind: \"namedSpread\", name: this.word().value, site: fieldSite });\n }\n else {\n const name = this.word().value;\n if (this.maybe(\":\")) fields.push({ kind: \"field\", name, value: this.expression(0, new Set([\",\", \"}\"])), site: fieldSite });\n else fields.push({ kind: \"bare\", name, site: fieldSite });\n }\n if (!this.maybe(\",\")) break;\n }\n return fields;\n }\n\n private parseWrite(): Expr {\n const opToken = this.word();\n const table = this.word().value;\n const op = opToken.value as \"insert\" | \"update\" | \"upsert\" | \"delete\";\n const keys = op === \"insert\" ? [] : this.parseRead(table, opToken).keys;\n const fields = op === \"delete\" ? [] : this.parseObjectFields();\n return { kind: \"write\", op, table, keys, fields, site: opToken };\n }\n\n private parseObjectFields(): ObjectField[] {\n this.take(\"{\");\n const fields: ObjectField[] = [];\n while (!this.at(\"}\")) {\n const name = this.word();\n fields.push({ name: name.value, value: this.maybe(\":\") ? this.expression(0, new Set([\",\", \"}\"])) : undefined, site: name });\n if (!this.maybe(\",\")) break;\n }\n this.take(\"}\");\n return fields;\n }\n\n private parseWalk(): Expr {\n const site = this.take(\"walk\");\n const table = this.word().value;\n const read = this.parseRead(table, site);\n if (read.keys.length !== 1 || read.keys[0]!.column) syntax(read.site, \"walk seed must be one positional reference t[seed]\");\n this.take(\"up\");\n this.take(\".\");\n const column = this.word().value;\n this.take(\"depth\");\n const depth = this.number();\n return { kind: \"walk\", table, seed: read.keys[0]!.value, column, depth, site };\n }\n\n private tupleBindingAhead(): boolean {\n let cursor = this.position + 1;\n if (this.tokens[cursor]?.kind !== \"word\") return false;\n cursor += 1;\n while (this.tokens[cursor]?.value === \",\") {\n cursor += 1;\n if (this.tokens[cursor]?.kind !== \"word\") return false;\n cursor += 1;\n }\n return this.tokens[cursor]?.value === \")\" && this.tokens[cursor + 1]?.value === \"=\";\n }\n\n private isStop(token: Token, stops: Set<string>): boolean {\n if (token.kind === \"newline\" || token.kind === \"dedent\" || token.kind === \"eof\") return true;\n return stops.has(token.value) || stops.has(`<${token.kind}>`);\n }\n\n private endLine(site: Site): void {\n if (!this.atKind(\"newline\")) syntax(this.peek(), `unexpected token after declaration from line ${site.line}`);\n this.newline();\n }\n\n private newline(): void { this.takeKind(\"newline\"); }\n private skipNewlines(): void { while (this.atKind(\"newline\")) this.position += 1; }\n private number(): number {\n const token = this.takeKind(\"number\");\n if (!/^\\d+$/.test(token.value)) syntax(token, \"this position takes an integer literal\");\n return Number(token.value);\n }\n private scale(rewrite: string): number {\n const token = this.peek();\n const scale = this.number();\n if (scale < 0 || scale > 12) {\n syntax(token, \"decimal and money scales must be integers from 0 through 12\", `use ${rewrite}`);\n }\n return scale;\n }\n private word(): Token { return this.takeKind(\"word\"); }\n private at(value: string): boolean { return this.peek().value === value; }\n private atKind(kind: TokenKind): boolean { return this.peek().kind === kind; }\n private maybe(value: string): boolean {\n if (!this.at(value)) return false;\n this.position += 1;\n return true;\n }\n private take(value: string): Token {\n const token = this.peek();\n if (token.value !== value) syntax(token, `expected ${JSON.stringify(value)}, got ${JSON.stringify(token.value)}`);\n this.position += 1;\n return token;\n }\n private takeKind(kind: TokenKind): Token {\n const token = this.peek();\n if (token.kind !== kind) syntax(token, `expected ${kind}, got ${JSON.stringify(token.value)}`);\n this.position += 1;\n return token;\n }\n private peek(offset = 0): Token { return this.tokens[Math.min(this.position + offset, this.tokens.length - 1)]!; }\n\n private capture(error: unknown): void {\n if (error instanceof QuarryError) this.diagnostics.push(error.diagnostic);\n else throw error;\n }\n\n private recoverLine(): void {\n while (!this.atKind(\"newline\") && !this.atKind(\"dedent\") && !this.atKind(\"eof\")) this.position += 1;\n if (this.atKind(\"newline\")) this.position += 1;\n }\n\n private recoverStatement(): void {\n this.recoverLine();\n }\n\n private recoverTopLevel(): void {\n this.recoverLine();\n let depth = 0;\n const declarations = new Set([\"use\", \"table\", \"maintain\", \"channel\", \"query\", \"mutation\", \"effect\", \"shape\", \"fn\", \"cursor\", \"schedule\", \"index\", \"unique\", \"device\", \"oblivious\"]);\n while (!this.atKind(\"eof\")) {\n if (this.atKind(\"indent\")) { depth += 1; this.position += 1; continue; }\n if (this.atKind(\"dedent\")) { depth = Math.max(0, depth - 1); this.position += 1; continue; }\n if (depth === 0 && this.atKind(\"word\") && declarations.has(this.peek().value)) return;\n this.position += 1;\n }\n }\n}\n\nfunction focalizeRuleBinding(expr: Expr, binding: string): Expr {\n if (expr.kind === \"name\") return expr.name === binding ? { kind: \"focal\", site: expr.site } : expr;\n if (expr.kind === \"unary\") return { ...expr, value: focalizeRuleBinding(expr.value, binding) };\n if (expr.kind === \"binary\") return { ...expr, left: focalizeRuleBinding(expr.left, binding), right: focalizeRuleBinding(expr.right, binding) };\n if (expr.kind === \"member\") return { ...expr, base: focalizeRuleBinding(expr.base, binding) };\n if (expr.kind === \"call\") return { ...expr, args: expr.args.map((item) => focalizeRuleBinding(item, binding)) };\n if (expr.kind === \"array\") return { ...expr, items: expr.items.map((item) => focalizeRuleBinding(item, binding)) };\n if (expr.kind === \"object\") return { ...expr, fields: expr.fields.map((field) => ({ ...field, value: field.value && focalizeRuleBinding(field.value, binding) })) };\n if (expr.kind === \"read\") return {\n ...expr,\n keys: expr.keys.map((part) => ({ ...part, value: focalizeRuleBinding(part.value, binding) })),\n range: expr.range && {\n ...expr.range,\n cursor: expr.range.cursor && focalizeRuleBinding(expr.range.cursor, binding),\n where: expr.range.where && {\n ...expr.range.where,\n predicate: focalizeRuleBinding(expr.range.where.predicate, binding),\n },\n },\n };\n if (expr.kind === \"exists\" || expr.kind === \"created\") return { ...expr, read: focalizeRuleBinding(expr.read, binding) as Extract<Expr, { kind: \"read\" }> };\n if (expr.kind === \"aggregate\") return { ...expr, keys: expr.keys.map((part) => ({ ...part, value: focalizeRuleBinding(part.value, binding) })) };\n if (expr.kind === \"assert\") return { ...expr, value: focalizeRuleBinding(expr.value, binding) };\n if (expr.kind === \"shapeUse\") return { ...expr, base: focalizeRuleBinding(expr.base, binding) };\n if (expr.kind === \"shape\") return {\n ...expr,\n base: focalizeRuleBinding(expr.base, binding),\n fields: expr.fields.map((field) => field.kind === \"field\" ? { ...field, value: focalizeRuleBinding(field.value, binding) } : field),\n };\n if (expr.kind === \"walk\") return { ...expr, seed: focalizeRuleBinding(expr.seed, binding) };\n if (expr.kind === \"write\") return {\n ...expr,\n keys: expr.keys.map((part) => ({ ...part, value: focalizeRuleBinding(part.value, binding) })),\n fields: expr.fields.map((field) => ({ ...field, value: field.value && focalizeRuleBinding(field.value, binding) })),\n };\n return expr;\n}\n\nfunction title(value: string): string {\n return value.length === 0 ? value : value[0]!.toUpperCase() + value.slice(1);\n}\n", "import type { Document, Expr, IndexDecl, QuarryDiagnostic, ScalarType, Stmt, TableCatalog } from \"./ast\";\nimport { quarryExpression } from \"./program\";\n\nconst FALLBACK = \"use an index whose prefix pins the predicate, a table invariant (after insert <- exists ...), or merge for a fan-in feed\";\n\n// @ref LLP 1011#b6-the-refused-where-as-a-two-site-repair \u2014 `where` never\n// reaches lowering; catalog facts turn the narrow equality form into two sited repairs.\nexport function whereRepairDiagnostics(documents: Document[], catalog: TableCatalog): QuarryDiagnostic[] {\n const diagnostics: QuarryDiagnostic[] = [];\n for (const document of documents) {\n for (const program of document.programs) {\n walkStatements(program.body, (expr) => {\n if (expr.kind !== \"read\" || !expr.range?.where) return;\n diagnostics.push(...repair(expr, catalog));\n });\n }\n }\n return diagnostics;\n}\n\nfunction repair(read: Extract<Expr, { kind: \"read\" }>, catalog: TableCatalog): QuarryDiagnostic[] {\n const intent = read.range!.where!;\n if (!read.range?.order || !Number.isInteger(read.range.take)) return [fallback(intent.site)];\n const info = catalog.get(read.table);\n const terms = equalityTerms(intent.predicate);\n const base = info && baseIndex(read, info.indexes);\n if (!info || !terms || !base) return [fallback(intent.site)];\n\n const prefixColumns = base.columns.slice(0, read.keys.length);\n const suffixColumns = base.columns.slice(read.keys.length);\n const predicateColumns: string[] = [];\n const predicateValues: Expr[] = [];\n const seen = new Map<string, string>();\n for (const term of terms) {\n const column = info.columns.get(term.column);\n if (!column || !indexable(column)) return [fallback(intent.site)];\n const rendered = quarryExpression(term.value);\n const prior = seen.get(term.column);\n if (prior !== undefined) {\n if (prior !== rendered) return [fallback(intent.site)];\n continue;\n }\n seen.set(term.column, rendered);\n const prefixOffset = prefixColumns.indexOf(term.column);\n if (prefixOffset >= 0) {\n if (quarryExpression(read.keys[prefixOffset]!.value) !== rendered) return [fallback(intent.site)];\n continue;\n }\n predicateColumns.push(term.column);\n predicateValues.push(term.value);\n }\n const leading = [...prefixColumns, ...predicateColumns];\n const compatible = info.indexes.find((index) => total(index)\n && leading.every((column, offset) => index.columns[offset] === column));\n let selected: IndexDecl;\n let indexLine: string;\n let schemaMessage: string;\n if (compatible) {\n selected = compatible;\n indexLine = renderIndex(compatible);\n schemaMessage = `where repair reuses ${read.table}.${compatible.name} for the read at ${siteText(intent.site)}`;\n } else {\n const predicateSet = new Set(predicateColumns);\n const columns = [...leading, ...suffixColumns.filter((column) => !predicateSet.has(column))];\n const unique = base.unique;\n if (!unique && columns.at(-1) !== \"id\") columns.push(\"id\");\n if (columns.length > 8) return [fallback(intent.site)];\n const name = collisionFreeName(columns, info.indexes);\n selected = { name, columns, unique, site: base.site };\n indexLine = renderIndex(selected);\n schemaMessage = `where needs this index for the read at ${siteText(intent.site)}`;\n }\n\n const repaired: Extract<Expr, { kind: \"read\" }> = {\n ...read,\n keys: [\n ...read.keys,\n ...predicateValues.map((value) => ({ value, site: value.site })),\n ],\n index: selected.name,\n range: { ...read.range!, where: undefined },\n };\n return [\n diagnostic(selected.site, schemaMessage, indexLine),\n diagnostic(intent.site, \"where is refused; use the indexed prefix scan in this rewrite\", quarryExpression(repaired)),\n ];\n}\n\nfunction baseIndex(read: Extract<Expr, { kind: \"read\" }>, indexes: IndexDecl[]): IndexDecl | undefined {\n if (read.index) return indexes.find((index) => index.name === read.index\n && read.keys.every((key, offset) => key.column === undefined || key.column === index.columns[offset]));\n const named = read.keys.some((key) => key.column !== undefined);\n if (named && read.keys.some((key) => key.column === undefined)) return undefined;\n const candidates = indexes.filter((index) => index.name !== \"byId\" && index.columns.length > read.keys.length\n && (!named || read.keys.every((key, offset) => key.column === index.columns[offset])));\n return candidates.length === 1 ? candidates[0] : undefined;\n}\n\nfunction equalityTerms(expr: Expr): Array<{ column: string; value: Expr }> | undefined {\n if (expr.kind === \"binary\" && expr.op === \"and\") {\n const left = equalityTerms(expr.left);\n const right = equalityTerms(expr.right);\n return left && right ? [...left, ...right] : undefined;\n }\n if (expr.kind !== \"binary\" || expr.op !== \"=\" || expr.left.kind !== \"member\" || expr.left.base.kind !== \"focal\") return undefined;\n return [{ column: expr.left.name, value: expr.right }];\n}\n\nfunction indexable(type: ScalarType): boolean {\n const value = type.kind === \"list\" ? type.item : type;\n return type.kind !== \"list\" && value.kind !== \"json\";\n}\n\nfunction total(index: IndexDecl): boolean { return index.unique || index.columns.at(-1) === \"id\"; }\n\nfunction collisionFreeName(columns: string[], indexes: IndexDecl[]): string {\n const stemColumns = columns.at(-1) === \"id\" ? columns.slice(0, -1) : columns;\n const stem = `by${stemColumns.map(title).join(\"\") || \"Repair\"}`;\n const names = new Set(indexes.map((index) => index.name));\n if (!names.has(stem)) return stem;\n let suffix = 2;\n while (names.has(`${stem}${suffix}`)) suffix += 1;\n return `${stem}${suffix}`;\n}\n\nfunction renderIndex(index: IndexDecl): string {\n return `${index.unique ? \"unique\" : \"by\"} ${index.name}: ${index.columns.join(\", \")}`;\n}\n\nfunction diagnostic(site: Expr[\"site\"], message: string, rewrite: string): QuarryDiagnostic {\n return { ...site, code: \"E_QUARRY_UNSUPPORTED\", message, rewrite, guide: \"quarry/refusals\" };\n}\n\nfunction fallback(site: Expr[\"site\"]): QuarryDiagnostic {\n return diagnostic(site, \"where is not part of the Snapback 2 platform\", FALLBACK);\n}\n\nfunction walkStatements(statements: Stmt[], visit: (expr: Expr) => void): void {\n for (const statement of statements) {\n if (statement.kind === \"bind\" || statement.kind === \"expr\" || statement.kind === \"return\") walk(statement.value, visit);\n else if (statement.kind === \"require\") walk(statement.condition, visit);\n else if (statement.kind === \"emit\") walk(statement.payload, visit);\n else if (statement.kind === \"if\") {\n walk(statement.condition, visit);\n walkStatements(statement.thenBody, visit);\n walkStatements(statement.elseBody, visit);\n } else if (statement.kind === \"for\") {\n walk(statement.domain, visit);\n walkStatements(statement.body, visit);\n } else {\n walk(statement.read, visit);\n walkStatements(statement.someBody, visit);\n walkStatements(statement.noneBody, visit);\n }\n }\n}\n\nfunction walk(expr: Expr, visit: (expr: Expr) => void): void {\n visit(expr);\n if (expr.kind === \"unary\" || expr.kind === \"assert\") walk(expr.value, visit);\n else if (expr.kind === \"binary\") { walk(expr.left, visit); walk(expr.right, visit); }\n else if (expr.kind === \"member\" || expr.kind === \"shapeUse\") walk(expr.base, visit);\n else if (expr.kind === \"call\") expr.args.forEach((item) => walk(item, visit));\n else if (expr.kind === \"array\") expr.items.forEach((item) => walk(item, visit));\n else if (expr.kind === \"object\") expr.fields.forEach((field) => field.value && walk(field.value, visit));\n else if (expr.kind === \"read\") {\n expr.keys.forEach((key) => walk(key.value, visit));\n if (expr.range?.cursor) walk(expr.range.cursor, visit);\n } else if (expr.kind === \"merge\") {\n if (expr.cursor) walk(expr.cursor, visit);\n expr.lanes.forEach((lane) => {\n lane.prefix.forEach((value) => walk(value, visit));\n if (lane.loop) walk(lane.loop.domain, visit);\n });\n } else if (expr.kind === \"exists\" || expr.kind === \"created\") walk(expr.read, visit);\n else if (expr.kind === \"aggregate\") expr.keys.forEach((key) => walk(key.value, visit));\n else if (expr.kind === \"shape\") {\n walk(expr.base, visit);\n expr.fields.forEach((field) => field.kind === \"field\" && walk(field.value, visit));\n } else if (expr.kind === \"walk\") walk(expr.seed, visit);\n else if (expr.kind === \"write\") {\n expr.keys.forEach((key) => walk(key.value, visit));\n expr.fields.forEach((field) => field.value && walk(field.value, visit));\n }\n}\n\nfunction title(value: string): string { return value ? value[0]!.toUpperCase() + value.slice(1) : value; }\nfunction siteText(site: Expr[\"site\"]): string { return `${site.file}:${site.line}:${site.col}`; }\n", "import { basename, dirname, isAbsolute, relative, resolve, sep } from \"node:path\";\nimport ts from \"typescript\";\nimport { typeDiagnostic } from \"./diagnostics\";\nimport type { FrontendDiagnostic } from \"./ir\";\nimport { callLeaf } from \"./lower/static\";\nimport { findNarrowestNode, hasExport, unwrapCall } from \"./syntax\";\nimport { typeDiagnosticSite } from \"./type-diagnostic-site\";\n\nexport function createProjectProgram(\n schemaPath: string,\n schemaSource: string,\n moduleSources: ReadonlyArray<readonly [string, string]>,\n libText: string,\n): { program: ts.Program; checker: ts.TypeChecker } {\n const libPath = resolve(dirname(schemaPath), \"__snapback2_lib.d.ts\");\n const files = new Map<string, string>([[schemaPath, schemaSource], [libPath, libText], ...moduleSources]);\n const options: ts.CompilerOptions = {\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n noEmit: true,\n noLib: true,\n strict: true,\n target: ts.ScriptTarget.ES2022,\n types: [],\n };\n const host = ts.createCompilerHost(options, true);\n host.resolveModuleNameLiterals = (literals, containingFile, _redirectedReference, compilerOptions) =>\n literals.map((literal) => {\n const name = literal.text;\n if (name === \"snapback2\" || name.startsWith(\"snapback2/\")) return { resolvedModule: undefined };\n return ts.resolveModuleName(name, containingFile, compilerOptions, host);\n });\n const sourceFile = host.getSourceFile.bind(host);\n const read = host.readFile.bind(host);\n const exists = host.fileExists.bind(host);\n host.fileExists = (name) => files.has(name) || exists(name);\n host.readFile = (name) => files.get(name) ?? read(name);\n host.getSourceFile = (name, languageVersion, onError, shouldCreateNewSourceFile) => {\n const text = files.get(name);\n return text === undefined\n ? sourceFile(name, languageVersion, onError, shouldCreateNewSourceFile)\n : ts.createSourceFile(name, text, languageVersion, true);\n };\n const program = ts.createProgram([...files.keys()], options, host);\n return { program, checker: program.getTypeChecker() };\n}\n\nexport function projectTypeDiagnostics(program: ts.Program, projectRoot: string): FrontendDiagnostic[] {\n const checker = program.getTypeChecker();\n return ts.getPreEmitDiagnostics(program).flatMap((item) => {\n if (!item.file || item.file.fileName.endsWith(\"__snapback2_lib.d.ts\")) return [];\n if (item.file.fileName.includes(`${sep}node_modules${sep}`)) return [];\n if (!resolve(item.file.fileName).startsWith(`${resolve(projectRoot)}${sep}`)) return [];\n if (selfTableReference(item) || exportedStaticTableUsedBeforeAssigned(item, checker)) return [];\n const position = item.start === undefined ? { line: 0, character: 0 } : item.file.getLineAndCharacterOfPosition(item.start);\n const file = relativeSite(projectRoot, item.file.fileName);\n const message = ts.flattenDiagnosticMessageText(item.messageText, \"\\n\");\n const node = item.start === undefined ? item.file : findNarrowestNode(item.file, item.start);\n const siteKind = typeDiagnosticSite(node, file);\n return [typeDiagnostic(\n siteKind.code,\n siteKind.family,\n file,\n position.line + 1,\n position.character + 1,\n message,\n typeDiagnosticRewrite(item.file, node, message),\n siteKind.guide,\n )];\n });\n}\n\nfunction selfTableReference(item: ts.Diagnostic): boolean {\n if (!item.file || item.start === undefined) return false;\n const node = findNarrowestNode(item.file, item.start);\n const declaration = ancestor(node, ts.isVariableDeclaration);\n const call = declaration?.initializer && unwrapCall(declaration.initializer);\n return !!call && callLeaf(call) === \"table\" && ts.isIdentifier(declaration!.name) && node.getText() === declaration!.name.text;\n}\n\nfunction exportedStaticTableUsedBeforeAssigned(item: ts.Diagnostic, checker: ts.TypeChecker): boolean {\n if (item.code !== 2454 || !item.file || item.start === undefined) return false;\n if (basename(item.file.fileName) !== \"schema.ts\" || basename(dirname(item.file.fileName)) !== \"snapback\") return false;\n const node = findNarrowestNode(item.file, item.start);\n if (!ts.isIdentifier(node)) return false;\n const declaration = checker.getSymbolAtLocation(node)?.valueDeclaration;\n if (!declaration || !ts.isVariableDeclaration(declaration) || declaration.getSourceFile() !== item.file) return false;\n const statement = ancestor(declaration, ts.isVariableStatement);\n const call = declaration.initializer && unwrapCall(declaration.initializer);\n return !!statement && hasExport(statement) && !!call && callLeaf(call) === \"table\";\n}\n\nfunction ancestor<T extends ts.Node>(node: ts.Node, guard: (value: ts.Node) => value is T): T | undefined {\n let current: ts.Node | undefined = node;\n while (current) {\n if (guard(current)) return current;\n current = current.parent;\n }\n return undefined;\n}\n\nfunction typeDiagnosticRewrite(sourceFile: ts.SourceFile, node: ts.Node, message: string): string {\n const statement = ancestor(node, ts.isStatement);\n if (statement) return `${statement.getText(sourceFile)}\\n// Fix the TypeScript error above: ${message.split(\"\\n\")[0]}`;\n const position = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n const lineStarts = sourceFile.getLineStarts();\n const start = lineStarts[position.line] ?? 0;\n const next = lineStarts[position.line + 1] ?? sourceFile.text.length;\n return `${sourceFile.text.slice(start, next).trimEnd()}\\n// Fix the TypeScript error above: ${message.split(\"\\n\")[0]}`;\n}\n\nfunction relativeSite(root: string, path: string): string {\n return relative(root, isAbsolute(path) ? path : resolve(path)).split(sep).join(\"/\");\n}\n", "import ts from \"typescript\";\nimport { diagnostic, type DiagnosticModule } from \"./diagnostics\";\nimport { IR_CONTRACT, type FrontendDiagnostic } from \"./ir\";\nimport { booleanValue, stringValue } from \"./lower/static\";\nimport { propertyName, unwrapExpression } from \"./syntax\";\n\nclass AuthoredSeedNumber {\n constructor(readonly text: string) {}\n}\n\nexport function staticSeedJson(node: ts.Expression, constants: Map<string, unknown> = new Map()): unknown | undefined {\n const value = unwrapExpression(node);\n if (value.kind === ts.SyntaxKind.NullKeyword) return null;\n const bool = booleanValue(value);\n if (bool !== undefined) return bool;\n if (ts.isNumericLiteral(value)) return new AuthoredSeedNumber(value.getText());\n if (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(value.operand)) {\n return new AuthoredSeedNumber(`-${value.operand.getText()}`);\n }\n const string = stringValue(value);\n if (string !== undefined) return string;\n if (ts.isIdentifier(value)) return constants.get(value.text);\n if (ts.isArrayLiteralExpression(value)) {\n const output: unknown[] = [];\n for (const item of value.elements) {\n if (ts.isSpreadElement(item)) return undefined;\n const lowered = staticSeedJson(item, constants);\n if (lowered === undefined) return undefined;\n output.push(lowered);\n }\n return output;\n }\n if (ts.isObjectLiteralExpression(value)) {\n const output: Record<string, unknown> = Object.create(null);\n for (const item of value.properties) {\n if (ts.isSpreadAssignment(item)) {\n const spread = staticSeedJson(item.expression, constants);\n if (!spread || typeof spread !== \"object\" || Array.isArray(spread)) return undefined;\n Object.assign(output, spread);\n continue;\n }\n const entry = ts.isPropertyAssignment(item)\n ? { name: propertyName(item.name), value: item.initializer }\n : ts.isShorthandPropertyAssignment(item) ? { name: item.name.text, value: item.name } : undefined;\n if (!entry?.name) return undefined;\n const lowered = staticSeedJson(entry.value, constants);\n if (lowered === undefined) return undefined;\n output[entry.name] = lowered;\n }\n return output;\n }\n return undefined;\n}\n\nexport function moduleSeedJsonConstants(sourceFile: ts.SourceFile): Map<string, unknown> {\n const constants = new Map<string, unknown>();\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const value = staticSeedJson(declaration.initializer, constants);\n if (value !== undefined) constants.set(declaration.name.text, value);\n }\n }\n return constants;\n}\n\nexport function validateSeedRow(\n module: DiagnosticModule,\n node: ts.Node,\n table: string,\n index: number,\n value: unknown,\n columns: Record<string, unknown>,\n diagnostics: FrontendDiagnostic[],\n): void {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n diagnostics.push(diagnostic(module, \"E_SEED_ROW\", node, `seed ${table}[${index}] must be an object with a string id`, module.source));\n return;\n }\n const row = value as Record<string, unknown>;\n if (typeof row.id !== \"string\" || row.id.length === 0) {\n diagnostics.push(diagnostic(module, \"E_SEED_ROW\", node, `seed ${table}[${index}].id must be a non-empty string`, module.source));\n }\n for (const field of Object.keys(row)) {\n if (!Object.hasOwn(columns, field)) {\n diagnostics.push(diagnostic(module, \"E_SEED_VALUE\", node, `seed ${table}[${index}] has unknown column ${field}`, module.source));\n }\n }\n for (const [field, type] of Object.entries(columns)) {\n if (!Object.hasOwn(row, field)) {\n if (!isOptionalColumn(type)) {\n diagnostics.push(diagnostic(module, \"E_SEED_VALUE\", node, `seed ${table}[${index}] is missing required column ${field}`, module.source));\n }\n continue;\n }\n const normalized = normalizeSeedValue(row[field], type, `${table}[${index}].${field}`);\n if (normalized.mismatch) diagnostics.push(diagnostic(module, normalized.mismatch.code, node, normalized.mismatch.message, normalized.mismatch.rewrite ?? module.source));\n else row[field] = normalized.value;\n }\n}\n\ntype SeedMismatch = {\n code: \"E_SEED_VALUE\" | \"E_SCHEMA_ASSET_SEED\";\n message: string;\n rewrite?: string;\n};\n\nfunction seedMismatch(message: string): SeedMismatch {\n return { code: \"E_SEED_VALUE\", message };\n}\n\ntype NormalizedSeed = { value?: unknown; mismatch?: SeedMismatch };\n\nfunction normalizeSeedValue(value: unknown, type: unknown, path: string): NormalizedSeed {\n if (type && typeof type === \"object\" && !Array.isArray(type)) {\n const descriptor = type as Record<string, any>;\n if (descriptor.Decimal || descriptor.Money) return normalizeWholeUnits(value, descriptor, path);\n if (\"Optional\" in descriptor) return value === null ? { value: null } : normalizeSeedValue(value, descriptor.Optional, path);\n if (descriptor.List) {\n if (!Array.isArray(value)) return { mismatch: seedMismatch(`${path} must be a list`) };\n if (value.length > descriptor.List.max) return { mismatch: seedMismatch(`${path} exceeds list max ${descriptor.List.max}`) };\n const items: unknown[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const normalized = normalizeSeedValue(value[index], descriptor.List.of, `${path}[${index}]`);\n if (normalized.mismatch) return normalized;\n items.push(normalized.value);\n }\n return { value: items };\n }\n }\n const plain = plainSeedValue(value);\n const mismatch = seedValueMismatch(plain, type, path);\n return mismatch ? { mismatch } : { value: plain };\n}\n\n// @ref LLP 1011#b5-whole-unit-seeds \u2014 retain the authored character path so\n// scaling never passes through a rounded host number.\nfunction normalizeWholeUnits(value: unknown, descriptor: Record<string, any>, path: string): NormalizedSeed {\n const text = value instanceof AuthoredSeedNumber ? value.text\n : typeof value === \"number\" ? String(value)\n : typeof value === \"string\" ? value : undefined;\n const named = descriptor.Decimal\n ? `Decimal<${descriptor.Decimal.scale}>`\n : `Money<${JSON.stringify(descriptor.Money.currency)}, ${descriptor.Money.scale}>`;\n const scale = Number((descriptor.Decimal ?? descriptor.Money).scale);\n if (text === undefined) return { mismatch: seedMismatch(`${path} must be a JSON number or decimal string in whole units`) };\n if (/[eE]/.test(text)) return { mismatch: seedMismatch(`${path} refuses exponent notation; spell the whole-unit decimal directly`) };\n const match = text.match(/^(-?)(\\d+)(?:\\.(\\d+))?$/);\n if (!match) return { mismatch: seedMismatch(`${path} must be a JSON number or decimal string in whole units`) };\n const fractional = match[3] ?? \"\";\n if (fractional.length > scale) {\n return { mismatch: seedMismatch(`${fractional.length} fractional digits, scale ${scale}; ${named} cannot represent ${text}`) };\n }\n const digits = `${match[2]}${fractional.padEnd(scale, \"0\")}`.replace(/^0+(?=\\d)/, \"\");\n const minor = BigInt(`${match[1]}${digits}`);\n const maximum = 9_007_199_254_740_991n;\n if (minor < -maximum || minor > maximum) {\n return { mismatch: seedMismatch(`${text} at scale ${scale} is outside the safe integer wire range`) };\n }\n return { value: Number(minor) };\n}\n\nfunction plainSeedValue(value: unknown): unknown {\n if (value instanceof AuthoredSeedNumber) return Number(value.text);\n if (Array.isArray(value)) return value.map(plainSeedValue);\n if (value && typeof value === \"object\") {\n const output: Record<string, unknown> = Object.create(null);\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) output[key] = plainSeedValue(item);\n return output;\n }\n return value;\n}\n\nfunction seedValueMismatch(value: unknown, type: unknown, path: string): SeedMismatch | undefined {\n if (type === \"Id\" || type === \"Principal\" || (type && typeof type === \"object\" && \"Ref\" in type)) {\n if (value === IR_CONTRACT.systemPrincipalId) return seedMismatch(`${path} cannot carry the reserved system principal`);\n return typeof value === \"string\" && value.length > 0 ? undefined : seedMismatch(`${path} must be a non-empty string`);\n }\n if (type === \"Int\" || type === \"Time\") {\n return typeof value === \"number\" && Number.isSafeInteger(value) ? undefined : seedMismatch(`${path} must be an integer`);\n }\n if (type === \"Bool\") return typeof value === \"boolean\" ? undefined : seedMismatch(`${path} must be boolean`);\n if (!type || typeof type !== \"object\" || Array.isArray(type)) return seedMismatch(`${path} has an unsupported schema type`);\n const descriptor = type as Record<string, any>;\n if (descriptor.Text) {\n if (typeof value !== \"string\" || [...value].length > descriptor.Text.max) {\n return seedMismatch(`${path} must be text of at most ${descriptor.Text.max} characters`);\n }\n const codePoint = disallowedTextControlCodePoint(value);\n return codePoint === undefined\n ? undefined\n : seedMismatch(`${path} contains disallowed control character U+${codePoint.toString(16).toUpperCase().padStart(4, \"0\")}`);\n }\n if (descriptor.Bytes) {\n const encodedObject = value && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined;\n const encoded = encodedObject?.Bytes;\n return encodedObject && Object.keys(encodedObject).length === 1\n && typeof encoded === \"string\" && /^(?:[0-9a-f]{2})*$/.test(encoded)\n && encoded.length / 2 <= descriptor.Bytes.max\n ? undefined\n : seedMismatch(`${path} must be canonical lowercase base16 of at most ${descriptor.Bytes.max} bytes`);\n }\n if (descriptor.Json) {\n const mismatch = jsonWireMismatch(value, path);\n if (mismatch) return mismatch;\n const bytes = new TextEncoder().encode(JSON.stringify(value)).length;\n return bytes <= descriptor.Json.max_bytes ? undefined : seedMismatch(`${path} JSON exceeds ${descriptor.Json.max_bytes} bytes`);\n }\n if (descriptor.Enum) {\n const variants = descriptor.Enum.variants as unknown[];\n return typeof value === \"string\" && variants.includes(value)\n ? undefined\n : seedMismatch(`${path} must be one of ${variants.map(String).join(\", \")}`);\n }\n if (descriptor.Decimal || descriptor.Money) return seedMismatch(`${path} was not normalized from whole units`);\n if (descriptor.Image || descriptor.Video) {\n const kind = descriptor.Image ? \"image\" : \"video\";\n // @ref LLP 1006#2a-one-asset-one-home-author-ruling-2026-09-01 \u2014 seeds\n // cannot fabricate the engine-owned ledger row required by an asset value.\n return {\n code: \"E_SCHEMA_ASSET_SEED\",\n message: `${path} cannot seed a ${kind} asset because seeds cannot mint ledger rows`,\n rewrite: \"upload through the app; seeds cannot mint ledger rows\",\n };\n }\n if (\"Optional\" in descriptor) {\n return value === null ? undefined : seedValueMismatch(value, descriptor.Optional, path);\n }\n if (descriptor.List) {\n if (!Array.isArray(value)) return seedMismatch(`${path} must be a list`);\n if (value.length > descriptor.List.max) return seedMismatch(`${path} exceeds list max ${descriptor.List.max}`);\n for (let index = 0; index < value.length; index += 1) {\n const mismatch = seedValueMismatch(value[index], descriptor.List.of, `${path}[${index}]`);\n if (mismatch) return mismatch;\n }\n return undefined;\n }\n return seedMismatch(`${path} has an unsupported schema type`);\n}\n\nfunction disallowedTextControlCodePoint(text: string): number | undefined {\n for (const character of text) {\n const codePoint = character.codePointAt(0)!;\n if (codePoint < 0x20 && ![0x09, 0x0a, 0x0d].includes(codePoint)) return codePoint;\n }\n return undefined;\n}\n\nfunction isOptionalColumn(type: unknown): boolean {\n return !!type && typeof type === \"object\" && !Array.isArray(type) && \"Optional\" in type;\n}\n\nfunction jsonWireMismatch(value: unknown, path: string): SeedMismatch | undefined {\n if (typeof value === \"number\") return Number.isSafeInteger(value) ? undefined : seedMismatch(`${path} JSON numbers must be integers`);\n if (Array.isArray(value)) {\n for (let index = 0; index < value.length; index += 1) {\n const mismatch = jsonWireMismatch(value[index], `${path}[${index}]`);\n if (mismatch) return mismatch;\n }\n } else if (value && typeof value === \"object\") {\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n const mismatch = jsonWireMismatch(item, `${path}.${key}`);\n if (mismatch) return mismatch;\n }\n }\n return undefined;\n}\n", "import type { Program } from \"./ir\";\n\nexport function sortSerdeMaps(program: Program): Program {\n return {\n ...program,\n args: Object.fromEntries(Object.entries(program.args).sort(([left], [right]) => left.localeCompare(right))),\n body: sortNestedMaps(program.body) as Program[\"body\"],\n };\n}\n\nfunction sortNestedMaps(value: unknown, mapValue = false): unknown {\n if (Array.isArray(value)) return value.map((item) => sortNestedMaps(item));\n if (!value || typeof value !== \"object\") return value;\n const entries = Object.entries(value as Record<string, unknown>);\n const ordered = mapValue ? entries.sort(([left], [right]) => left.localeCompare(right)) : entries;\n return Object.fromEntries(ordered.map(([key, item]) => [key, sortNestedMaps(item, [\"Object\", \"Row\", \"Map\"].includes(key))]));\n}\n", "import { readFile } from \"node:fs/promises\";\nimport { basename, relative, resolve, sep } from \"node:path\";\nimport ts from \"typescript\";\nimport { expandArgumentObject } from \"./args\";\nimport { diagnostic, typeDiagnostic } from \"./diagnostics\";\nimport type { FrontendDiagnostic } from \"./ir\";\nimport { numberValue, objectOf, property, stringValue } from \"./lower/static\";\nimport { hasExport, snapbackCallName, staticMemberPath, unwrapCall } from \"./syntax\";\n\nexport type LowerProjectOptions = { authoring?: \"quarry\" | \"any\" };\n\nconst authoredDeclarations = new Set([\"query\", \"mutation\", \"table\", \"channel\", \"schema\"]);\n\n// @ref LLP 1007#4b-does-the-typescript-authoring-surface-stay \u2014 product compilation admits Quarry declarations and TypeScript effects only.\nexport async function quarryOnlyDiagnostics(\n projectRoot: string,\n hasTypeScriptSchema: boolean,\n modulePaths: string[],\n): Promise<FrontendDiagnostic[]> {\n const diagnostics: FrontendDiagnostic[] = [];\n if (hasTypeScriptSchema) {\n diagnostics.push(typeDiagnostic(\n \"E_QUARRY_ONLY\",\n \"quarry\",\n \"snapback/schema.ts\",\n 1,\n 1,\n \"backends are authored in Quarry; the schema is snapback/schema.q\",\n \"table items:\\n value: json <=1000\\n public\",\n \"quarry/projects\",\n ));\n }\n for (const path of modulePaths.sort()) {\n const source = await readFile(path, \"utf8\");\n const fileName = relativeSite(projectRoot, path);\n const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.ES2022, true);\n const module = { fileName, sourceFile };\n const locals = new Map<string, { kind: string; call: ts.CallExpression }>();\n for (const statement of sourceFile.statements) {\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const call = unwrapCall(declaration.initializer);\n const kind = call && snapbackCallName(call, sourceFile);\n if (!call || !kind || !authoredDeclarations.has(kind)) continue;\n locals.set(declaration.name.text, { kind, call });\n if (hasExport(statement)) pushAuthored(diagnostics, module, fileName, declaration.name, declaration.name.text, kind, call);\n }\n }\n }\n for (const statement of sourceFile.statements) {\n if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && statement.exportClause\n && ts.isNamedExports(statement.exportClause)) {\n for (const specifier of statement.exportClause.elements) {\n const local = locals.get(specifier.propertyName?.text ?? specifier.name.text);\n if (local) pushAuthored(diagnostics, module, fileName, specifier.name, specifier.name.text, local.kind, local.call);\n }\n } else if (ts.isExportAssignment(statement) && !statement.isExportEquals) {\n const call = unwrapCall(statement.expression);\n const directKind = call && snapbackCallName(call, sourceFile);\n const local = ts.isIdentifier(statement.expression) ? locals.get(statement.expression.text) : undefined;\n const authored = call && directKind && authoredDeclarations.has(directKind)\n ? { kind: directKind, call }\n : local;\n const name = local && ts.isIdentifier(statement.expression) ? statement.expression.text : \"operation\";\n if (authored) pushAuthored(diagnostics, module, fileName, statement, name, authored.kind, authored.call);\n }\n }\n }\n return diagnostics;\n}\n\nfunction pushAuthored(\n diagnostics: FrontendDiagnostic[],\n module: { fileName: string; sourceFile: ts.SourceFile },\n fileName: string,\n site: ts.Node,\n name: string,\n kind: string,\n call: ts.CallExpression,\n): void {\n diagnostics.push(diagnostic(module, \"E_QUARRY_ONLY\", site, authoringMessage(fileName), quarryHeader(kind, name, call)));\n}\n\nfunction authoringMessage(fileName: string): string {\n const stem = basename(fileName, \".ts\");\n return `queries and mutations are authored in Quarry (snapback/${stem}.q); TypeScript modules may export effects only`;\n}\n\nfunction quarryHeader(kind: string, name: string, call: ts.CallExpression): string {\n if (kind === \"query\" || kind === \"mutation\") {\n const args = objectOf(call.arguments[0]);\n const fields = args ? expandArgumentObject(args).entries.map((entry) => `${entry.name}: ${quarryType(entry.value)}`) : [];\n return `${kind} ${name}(${fields.join(\", \")}):`;\n }\n if (kind === \"table\") return `table ${name}:`;\n if (kind === \"channel\") return `channel ${name}():`;\n return \"table items:\\n value: json <=1000\\n public\";\n}\n\nfunction quarryType(node: ts.Expression): string {\n const call = unwrapCall(node);\n if (!call) return \"json <=1000\";\n const kind = snapbackCallName(call) ?? staticMemberPath(call.expression)?.split(\".\").at(-1);\n if (kind === \"optional\" && call.arguments[0]) return `${quarryType(call.arguments[0])} ?`;\n if (kind === \"id\" || kind === \"principal\" || kind === \"int\" || kind === \"time\" || kind === \"bool\") return kind;\n if ([\"text\", \"json\", \"bytes\", \"image\", \"video\"].includes(kind ?? \"\")) {\n return `${kind} <=${numberValue(call.arguments[0]) ?? 1000}`;\n }\n if (kind === \"ref\") return staticMemberPath(call.arguments[0]) ?? \"id\";\n if (kind === \"list\" && call.arguments[0]) {\n const options = objectOf(call.arguments[1]);\n const max = options && numberValue(property(options, \"max\"));\n return `[${quarryType(call.arguments[0])}] <=${max ?? 100}`;\n }\n if (kind === \"enum\") {\n const values = call.arguments[0] && ts.isArrayLiteralExpression(call.arguments[0])\n ? call.arguments[0].elements.map((item) => stringValue(item as ts.Expression)).filter((item): item is string => item !== undefined)\n : [];\n return `enum(${values.map((item) => JSON.stringify(item)).join(\", \")})`;\n }\n return \"json <=1000\";\n}\n\nfunction relativeSite(root: string, path: string): string {\n return relative(root, resolve(path)).split(sep).join(\"/\");\n}\n", "import ts from \"typescript\";\nimport { expandArgumentObject } from \"./args\";\nimport { requiredType, type AuthoredType, type TableInfo } from \"./authored-types\";\nimport type { OperationDecl } from \"./lower/effects\";\nimport {\n callLeaf,\n numberValue,\n objectOf,\n property,\n propertyEntries,\n stringArray,\n stringValue,\n} from \"./lower/static\";\nimport { hasExport, propertyName, staticMemberPath, unwrapCall, unwrapExpression } from \"./syntax\";\n\ntype ApiType = {\n text: string;\n special: boolean;\n fields?: Record<string, ApiType>;\n row?: TableInfo;\n element?: ApiType;\n optional?: boolean;\n groupedInArray?: boolean;\n};\n\ntype ApiTypeBinding =\n | { kind: \"args\" }\n | { kind: \"local\"; row?: TableInfo; elementRow?: TableInfo; type?: ApiType };\n\ntype ApiTypeEnvironment = { bindings: Map<string, ApiTypeBinding> };\n\n// @ref LLP 1002#3-the-compiler-worker-and-the-project-json \u2014 API declarations are inferred build output owned by the compiler pass.\nexport function generateApiDts(\n operations: Map<string, OperationDecl>,\n program: ts.Program,\n checker: ts.TypeChecker,\n tables: Map<string, TableInfo>,\n bindingsByModule: Map<string, Map<string, TableInfo>>,\n): string {\n const grouped = new Map<string, string[]>();\n for (const operation of [...operations.values()].sort((left, right) => left.name.localeCompare(right.name))) {\n const checkedCall = checkedOperationCall(program, operation);\n const args = checkedCall?.arguments[0] && objectOf(checkedCall.arguments[0]);\n const argsText = args ? apiArgsType(args, checker, operation.kind === \"mutation\") : \"{}\";\n const handler = checkedCall?.arguments[1];\n let resultText = \"unknown\";\n if (handler && (ts.isArrowFunction(handler) || ts.isFunctionExpression(handler))) {\n const signature = checker.getSignatureFromDeclaration(handler);\n if (signature) {\n resultText = checker.typeToString(\n checker.getReturnTypeOfSignature(signature),\n handler,\n ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.InTypeAlias,\n ).replaceAll('import(\"snapback2\").', \"\");\n }\n const tables = bindingsByModule.get(operation.moduleName) ?? new Map();\n const authored = apiAuthoredResult(handler, args, tables, checker);\n if (authored?.special) resultText = authored.text;\n }\n const items = grouped.get(operation.moduleName) ?? [];\n items.push(` readonly ${quoteProperty(operation.exportName)}: Op<${argsText}, ${resultText}>;`);\n grouped.set(operation.moduleName, items);\n }\n const rowTypes = [...tables.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .map(apiRowType)\n .join(\"\\n\");\n const channels = apiChannels(program, checker);\n const modulesText = [...grouped].sort(([left], [right]) => left.localeCompare(right))\n .filter(([name]) => name !== \"channels\" || channels.length === 0)\n .map(([name, items]) => ` readonly ${quoteProperty(name)}: {\\n${items.join(\"\\n\")}\\n };`)\n .join(\"\\n\");\n const channelsText = channels.length === 0 ? \"\" : (() => {\n const channelByName = new Map(channels.map((item) => [item.name, item]));\n const channelOperations = [...operations.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .filter((operation) => operation.moduleName === \"channels\");\n const operationItems = (grouped.get(\"channels\") ?? []).map((item, index) => {\n const channel = channelByName.get(channelOperations[index]!.exportName);\n return channel ? item.replace(/;$/, ` & Channel<${channel.args}, unknown>;`) : item;\n });\n const operationNames = new Set(channelOperations.map((operation) => operation.exportName));\n const channelItems = channels\n .filter((item) => !operationNames.has(item.name))\n .map((item) => `${quoteProperty(item.name)}: Channel<${item.args}, unknown>`);\n const catalog = operationItems.length === 0\n ? ` readonly channels: { ${channelItems.join(\"; \")} };`\n : ` readonly channels: {\\n${operationItems.join(\"\\n\")}\\n${channelItems.map((item) => ` readonly ${item};`).join(\"\\n\")}\\n };`;\n const occupiedRoots = new Set([...grouped.keys(), \"channels\", \"op\", \"then\", \"toJSON\"]);\n const aliases = channels\n .filter((item) => !occupiedRoots.has(item.name))\n .map((item) => ` readonly ${quoteProperty(item.name)}: Channel<${item.args}, unknown>;`);\n return [catalog, ...aliases].join(\"\\n\");\n })();\n const members = [modulesText, channelsText].filter(Boolean).join(\"\\n\");\n return `import type { Bytes, Cursor, Decimal, ImageAsset, Json, Money, Page, Principal, VideoAsset } from 'snapback2';\\nimport type { Channel, Op } from 'snapback2/client';\\n\\n${rowTypes}\\n\\ndeclare module 'snapback2/client' {\\n interface Api {\\n${members}\\n }\\n}\\n\\nexport {};\\n`;\n}\n\nfunction apiChannels(program: ts.Program, checker: ts.TypeChecker): Array<{ name: string; args: string }> {\n const schema = program.getSourceFiles().find((item) => /[/\\\\]snapback[/\\\\]schema\\.ts$/.test(item.fileName));\n if (!schema) return [];\n const channels: Array<{ name: string; args: string }> = [];\n for (const statement of schema.statements) {\n if (!ts.isVariableStatement(statement) || !hasExport(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const call = unwrapCall(declaration.initializer);\n if (!call || callLeaf(call) !== \"channel\") continue;\n const config = objectOf(call.arguments[0]);\n const args = config && objectOf(property(config, \"args\"));\n channels.push({ name: declaration.name.text, args: args ? apiArgsType(args, checker, false) : \"{}\" });\n }\n }\n return channels.sort((left, right) => left.name.localeCompare(right.name));\n}\n\nfunction apiRowType(table: TableInfo): string {\n const fields = Object.entries(table.columns ?? {}).map(([name, type]) => {\n const optional = type.kind === \"optional\";\n return ` ${quoteProperty(name)}${optional ? \"?\" : \"\"}: ${apiAuthoredType(optional ? type.of : type)};`;\n });\n if (!fields.some((field) => /^ id[?:]/.test(field))) fields.unshift(\" id: string;\");\n return `type ${apiRowName(table.name)} = {\\n${fields.join(\"\\n\")}\\n};`;\n}\n\nexport function apiRowName(table: string): string {\n const pascal = table.split(/[^A-Za-z0-9]+/).filter(Boolean)\n .map((part) => part[0]!.toUpperCase() + part.slice(1))\n .join(\"\");\n return `${pascal || \"Table\"}Row`;\n}\n\nfunction checkedOperationCall(program: ts.Program, operation: OperationDecl): ts.CallExpression | undefined {\n const file = program.getSourceFiles().find((item) => item.fileName.endsWith(`/snapback/${operation.moduleName}.ts`));\n if (!file) return undefined;\n for (const statement of file.statements) {\n if (!ts.isVariableStatement(statement) || !hasExport(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || declaration.name.text !== operation.exportName || !declaration.initializer) continue;\n return unwrapCall(declaration.initializer);\n }\n }\n return undefined;\n}\n\nfunction apiArgsType(object: ts.ObjectLiteralExpression, checker: ts.TypeChecker, acceptFiles: boolean): string {\n const fields = expandArgumentObject(object).entries.map((entry) => {\n const call = unwrapCall(entry.value);\n const optional = call && callLeaf(call) === \"optional\";\n const type = call ? argumentDescriptorType(call, checker, acceptFiles) : \"unknown\";\n const brand = call && argumentBrand(call);\n const comment = brand ? `/** ${brand} \u2014 minor units */ ` : \"\";\n return `${comment}${quoteProperty(entry.name)}${optional ? \"?\" : \"\"}: ${type}`;\n });\n return fields.length === 0 ? \"{}\" : `{ ${fields.join(\"; \")} }`;\n}\n\n// @ref LLP 1004#money-and-decimal-worked-out-2026-09-03 \u2014 callers write integer minor units while results retain nominal brands.\nfunction argumentDescriptorType(call: ts.CallExpression, checker: ts.TypeChecker, acceptFiles: boolean): string {\n const name = callLeaf(call);\n if ((name === \"decimal\" || name === \"money\")) return \"number\";\n if ((name === \"optional\" || name === \"list\") && call.arguments[0]) {\n const inner = unwrapCall(call.arguments[0]);\n const value = inner ? argumentDescriptorType(inner, checker, acceptFiles) : \"unknown\";\n return name === \"list\" ? `${value.includes(\" | \") ? `(${value})` : value}[]` : `${value} | null`;\n }\n if (acceptFiles && (name === \"image\" || name === \"video\")) {\n // @ref LLP 1006#10-clients \u2014 File substitution is a generated mutation-call convenience; programs and results retain records.\n return `File | ${name === \"image\" ? \"ImageAsset\" : \"VideoAsset\"}`;\n }\n return descriptorType(call, checker);\n}\n\nfunction argumentBrand(call: ts.CallExpression): string | undefined {\n const name = callLeaf(call);\n if (name === \"optional\" && call.arguments[0]) {\n const inner = unwrapCall(call.arguments[0]);\n return inner && argumentBrand(inner);\n }\n if (name === \"decimal\") return `decimal ${numberValue(call.arguments[0]) ?? \"?\"}`;\n if (name === \"money\") {\n return `money ${stringValue(call.arguments[0]) ?? \"?\"} ${numberValue(call.arguments[1]) ?? 2}`;\n }\n return undefined;\n}\n\nfunction descriptorType(call: ts.CallExpression, checker: ts.TypeChecker): string {\n const name = callLeaf(call);\n if (name === \"cursor\") return \"Cursor\";\n if (name === \"principal\") return \"Principal\";\n if (name === \"id\" || name === \"text\" || name === \"ref\") return \"string\";\n if (name === \"bytes\") return \"Bytes\";\n if (name === \"image\") return \"ImageAsset\";\n if (name === \"video\") return \"VideoAsset\";\n if (name === \"int\" || name === \"time\") return \"number\";\n if (name === \"bool\") return \"boolean\";\n if (name === \"enum\") {\n const variants = stringArray(call.arguments[0]);\n return variants?.map((item) => JSON.stringify(item)).join(\" | \") || \"never\";\n }\n if (name === \"decimal\") return `Decimal<${numberValue(call.arguments[0]) ?? \"number\"}>`;\n if (name === \"money\") {\n return `Money<${JSON.stringify(stringValue(call.arguments[0]) ?? \"\")}, ${numberValue(call.arguments[1]) ?? 2}>`;\n }\n if (name === \"optional\" && call.arguments[0]) {\n const inner = unwrapCall(call.arguments[0]);\n return inner ? descriptorType(inner, checker) : \"unknown\";\n }\n if (name === \"list\" && call.arguments[0]) {\n const inner = unwrapCall(call.arguments[0]);\n return `${inner ? descriptorType(inner, checker) : \"unknown\"}[]`;\n }\n if (name === \"json\") {\n const type = checker.getTypeAtLocation(call);\n const property = type.getProperty(\"__value\");\n if (property) return checker.typeToString(checker.getTypeOfSymbolAtLocation(property, call), call, ts.TypeFormatFlags.NoTruncation);\n }\n return \"unknown\";\n}\n\nfunction apiAuthoredResult(\n handler: ts.ArrowFunction | ts.FunctionExpression,\n args: ts.ObjectLiteralExpression | undefined,\n tables: Map<string, TableInfo>,\n checker: ts.TypeChecker,\n): ApiType | undefined {\n const environment: ApiTypeEnvironment = { bindings: new Map() };\n for (const parameter of handler.parameters) {\n for (const name of apiBindingNames(parameter.name)) environment.bindings.set(name, { kind: \"local\" });\n }\n const context = handler.parameters[0]?.name;\n if (context && ts.isObjectBindingPattern(context)) {\n for (const element of context.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const name = element.propertyName ? propertyName(element.propertyName) : element.name.text;\n if (name === \"args\") environment.bindings.set(element.name.text, { kind: \"args\" });\n if (name === \"ctx\") {\n const viewer = { text: \"Principal\", special: true };\n environment.bindings.set(element.name.text, {\n kind: \"local\",\n type: { text: \"unknown\", special: true, fields: { viewer } },\n });\n }\n }\n }\n if (!ts.isBlock(handler.body)) return apiExpressionType(handler.body, args, tables, checker, environment);\n const returns: ApiType[] = [];\n const terminated = apiStatements(handler.body.statements, args, tables, checker, environment, returns);\n const result = returns.reduce<ApiType | undefined>((current, item) => current ? apiUnionType(current, item) : item, undefined);\n return result && terminated && returns.length > 1 && !result.text.includes(\"unknown\") ? { ...result, special: true } : result;\n}\n\nfunction apiStatements(\n statements: ts.NodeArray<ts.Statement> | readonly ts.Statement[],\n args: ts.ObjectLiteralExpression | undefined,\n tables: Map<string, TableInfo>,\n checker: ts.TypeChecker,\n environment: ApiTypeEnvironment,\n returns: ApiType[],\n): boolean {\n for (const statement of statements) {\n if (apiStatement(statement, args, tables, checker, environment, returns)) return true;\n }\n return false;\n}\n\nfunction apiStatement(\n statement: ts.Statement,\n args: ts.ObjectLiteralExpression | undefined,\n tables: Map<string, TableInfo>,\n checker: ts.TypeChecker,\n environment: ApiTypeEnvironment,\n returns: ApiType[],\n): boolean {\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n const type = declaration.initializer\n ? apiExpressionType(declaration.initializer, args, tables, checker, environment)\n : undefined;\n for (const name of apiBindingNames(declaration.name)) {\n environment.bindings.set(name, apiLocalBinding(type));\n }\n }\n return false;\n }\n if (ts.isExpressionStatement(statement)) {\n apiExpressionEffect(statement.expression, args, tables, checker, environment);\n return false;\n }\n if (ts.isReturnStatement(statement) && statement.expression) {\n returns.push(apiExpressionType(statement.expression, args, tables, checker, environment));\n return true;\n }\n if (ts.isBlock(statement)) {\n return apiStatements(statement.statements, args, tables, checker, environment, returns);\n }\n if (ts.isIfStatement(statement)) {\n const before = apiCloneEnvironment(environment);\n const whenTrue = apiCloneEnvironment(before);\n const whenFalse = apiCloneEnvironment(before);\n apiNarrowNullGuard(statement.expression, whenTrue, whenFalse);\n const trueTerminates = apiStatement(statement.thenStatement, args, tables, checker, whenTrue, returns);\n const falseTerminates = statement.elseStatement\n ? apiStatement(statement.elseStatement, args, tables, checker, whenFalse, returns)\n : false;\n if (trueTerminates && falseTerminates) return true;\n apiMergeEnvironments(environment, before, [whenTrue, whenFalse]);\n return false;\n }\n if (ts.isForOfStatement(statement)) {\n const loop = apiCloneEnvironment(environment);\n const source = apiExpressionType(statement.expression, args, tables, checker, environment);\n if (ts.isVariableDeclarationList(statement.initializer)) {\n for (const declaration of statement.initializer.declarations) {\n for (const name of apiBindingNames(declaration.name)) loop.bindings.set(name, apiLocalBinding(source.element));\n }\n }\n apiStatement(statement.statement, args, tables, checker, loop, returns);\n apiMergeEnvironments(environment, environment, [environment, loop]);\n return false;\n }\n return false;\n}\n\nfunction apiExpressionEffect(\n node: ts.Expression,\n args: ts.ObjectLiteralExpression | undefined,\n tables: Map<string, TableInfo>,\n checker: ts.TypeChecker,\n environment: ApiTypeEnvironment,\n): void {\n const value = unwrapExpression(node);\n if (ts.isBinaryExpression(value) && value.operatorToken.kind === ts.SyntaxKind.EqualsToken\n && ts.isIdentifier(unwrapExpression(value.left))) {\n const name = (unwrapExpression(value.left) as ts.Identifier).text;\n const type = apiExpressionType(value.right, args, tables, checker, environment);\n environment.bindings.set(name, apiLocalBinding(type));\n return;\n }\n if (!ts.isCallExpression(value) || !ts.isPropertyAccessExpression(value.expression)\n || value.expression.name.text !== \"push\" || value.arguments.length === 0) return;\n const receiver = unwrapExpression(value.expression.expression);\n if (!ts.isIdentifier(receiver)) return;\n const binding = environment.bindings.get(receiver.text);\n if (binding?.kind !== \"local\") return;\n const pushed = apiExpressionType(value.arguments[0]!, args, tables, checker, environment);\n const element = binding.type?.element ? apiUnionType(binding.type.element, pushed) : pushed;\n environment.bindings.set(receiver.text, apiLocalBinding(apiArrayType(element)));\n}\n\nfunction apiExpressionType(\n node: ts.Expression,\n args: ts.ObjectLiteralExpression | undefined,\n tables: Map<string, TableInfo>,\n checker: ts.TypeChecker,\n environment: ApiTypeEnvironment,\n expected?: AuthoredType,\n): ApiType {\n const asserted = apiHasNonNullAssertion(node);\n const value = unwrapExpression(node);\n const target = expected && requiredType(expected);\n if (target?.kind === \"decimal\") return { text: apiAuthoredType(target), special: true };\n if (target?.kind === \"enum\" && ts.isStringLiteralLike(value)) return { text: apiAuthoredType(target), special: true };\n if (ts.isNumericLiteral(value)) return { text: \"number\", special: false };\n if (ts.isStringLiteralLike(value) || ts.isTemplateExpression(value)) return { text: \"string\", special: false };\n if (value.kind === ts.SyntaxKind.TrueKeyword || value.kind === ts.SyntaxKind.FalseKeyword) return { text: \"boolean\", special: false };\n if (value.kind === ts.SyntaxKind.NullKeyword) return { text: \"null\", special: false };\n if (ts.isIdentifier(value)) {\n const binding = environment.bindings.get(value.text);\n if (binding?.kind === \"local\" && binding.type) return asserted ? apiWithoutNull(binding.type) : binding.type;\n }\n if (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.MinusToken) {\n return apiExpressionType(value.operand, args, tables, checker, environment);\n }\n const propertyBase = ts.isPropertyAccessExpression(value) ? unwrapExpression(value.expression) : undefined;\n const propertyBinding = propertyBase && ts.isIdentifier(propertyBase)\n ? environment.bindings.get(propertyBase.text)\n : undefined;\n if (ts.isPropertyAccessExpression(value) && propertyBase && ts.isIdentifier(propertyBase)\n && propertyBinding?.kind === \"args\" && args) {\n const descriptor = propertyEntries(args).find((item) => item.name === value.name.text)?.value;\n const call = descriptor && unwrapCall(descriptor);\n if (call) {\n const text = `${descriptorType(call, checker)}${callLeaf(call) === \"optional\" ? \" | undefined\" : \"\"}`;\n return { text, special: apiTypeIsSpecial(text) };\n }\n }\n if (ts.isPropertyAccessExpression(value) && propertyBase) {\n const base = propertyBinding?.kind === \"local\" && propertyBinding.type\n ? propertyBinding.type\n : apiExpressionType(propertyBase, args, tables, checker, environment);\n const field = apiTypeField(base, value.name.text);\n if (field) {\n const optionalChain = Boolean(value.questionDotToken) && apiIncludesNull(base);\n return optionalChain ? apiUnionType(field, { text: \"undefined\", special: true, optional: true }) : field;\n }\n if (value.name.text === \"length\" && base.element) return { text: \"number\", special: base.special };\n }\n if (ts.isObjectLiteralExpression(value)) {\n let special = false;\n const fields: string[] = [];\n const fieldTypes: Record<string, ApiType> = {};\n const rowSpreads: TableInfo[] = [];\n for (const item of value.properties) {\n if (ts.isSpreadAssignment(item)) {\n const spread = apiExpressionType(item.expression, args, tables, checker, environment);\n if (spread.row) {\n rowSpreads.push(spread.row);\n special = true;\n }\n continue;\n }\n if (ts.isShorthandPropertyAssignment(item)) {\n const type = apiExpressionType(item.name, args, tables, checker, environment);\n special ||= type.special;\n fields.push(apiObjectField(item.name.text, type));\n fieldTypes[item.name.text] = type;\n continue;\n }\n if (!ts.isPropertyAssignment(item)) continue;\n const name = propertyName(item.name);\n if (!name) continue;\n const type = apiExpressionType(item.initializer, args, tables, checker, environment);\n special ||= type.special;\n fields.push(apiObjectField(name, type));\n fieldTypes[name] = type;\n }\n const spreadRows = [...new Map(rowSpreads.map((row) => [row.name, row])).values()];\n const aliases = spreadRows.map((row) => {\n const collisions = Object.keys(fieldTypes)\n .filter((name) => name === \"id\" || Object.hasOwn(row.columns ?? {}, name));\n const alias = apiRowName(row.name);\n return collisions.length === 0\n ? alias\n : `Omit<${alias}, ${collisions.map((name) => JSON.stringify(name)).join(\" | \")}>`;\n });\n const object = `{ ${fields.join(\"; \")} }`;\n const text = aliases.length === 0 ? object : [...aliases, ...(fields.length > 0 ? [object] : [])].join(\" & \");\n return {\n text,\n special,\n fields: fieldTypes,\n ...(rowSpreads.length === 1 ? { row: rowSpreads[0] } : {}),\n groupedInArray: aliases.length + Number(fields.length > 0) > 1,\n };\n }\n if (ts.isArrayLiteralExpression(value)) {\n if (value.elements.length === 1 && ts.isSpreadElement(value.elements[0]!)) {\n const spread = apiExpressionType(value.elements[0]!.expression, args, tables, checker, environment);\n if (spread.element) return apiArrayType(spread.element);\n }\n const items = value.elements\n .filter((item): item is ts.Expression => !ts.isSpreadElement(item))\n .map((item) => apiExpressionType(item, args, tables, checker, environment));\n const element = items.reduce<ApiType | undefined>((result, item) => result ? apiUnionType(result, item) : item, undefined);\n return element ? apiArrayType(element) : { text: \"unknown[]\", special: false };\n }\n if (ts.isConditionalExpression(value)) {\n const left = apiExpressionType(value.whenTrue, args, tables, checker, environment, target);\n const right = apiExpressionType(value.whenFalse, args, tables, checker, environment, target);\n return apiUnionType(left, right);\n }\n if (ts.isBinaryExpression(value)) {\n const left = apiExpressionType(value.left, args, tables, checker, environment);\n const right = apiExpressionType(value.right, args, tables, checker, environment);\n if ([\n ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken, ts.SyntaxKind.GreaterThanToken,\n ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken,\n ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken,\n ].includes(value.operatorToken.kind)) return { text: \"boolean\", special: false };\n if (value.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken && (left.special || right.special)) {\n return { ...apiWithoutUndefined(left.special ? left : right), special: true };\n }\n const branded = [left, right].filter((item) => /^(Decimal|Money)</.test(item.text));\n if (value.operatorToken.kind === ts.SyntaxKind.AsteriskToken && branded.length > 0) {\n return branded.find((item) => item.text.startsWith(\"Money<\")) ?? branded[0]!;\n }\n if (branded.length > 0 && [ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken]\n .includes(value.operatorToken.kind)) return branded[0]!;\n }\n if (ts.isCallExpression(value)) {\n const name = callLeaf(value);\n if ((name === \"scan\" || name === \"get\") && value.arguments[0]) {\n const table = apiTable(value.arguments[0], tables);\n if (table) {\n const row = apiNamedRowType(table);\n return name === \"scan\"\n ? { text: `Page<${row.text}>`, special: true, element: row }\n : apiUnionType(row, { text: \"null\", special: false });\n }\n }\n if (name === \"decimal\") {\n return { text: `Decimal<${numberValue(value.arguments[1]) ?? \"number\"}>`, special: true };\n }\n if (name === \"recurse\" && value.arguments[1]) {\n const row = apiRecurseRow(value.arguments[1], tables);\n if (row) return apiArrayType(apiNamedRowType(row));\n }\n if (name === \"divmod\" && value.arguments[0]) {\n const carried = apiExpressionType(value.arguments[0], args, tables, checker, environment);\n return {\n text: `{ quotient: ${carried.text}; remainder: ${carried.text} }`,\n special: carried.special,\n fields: { quotient: carried, remainder: carried },\n };\n }\n if (name === \"deterministicShare\" && value.arguments[0]) {\n return apiExpressionType(value.arguments[0], args, tables, checker, environment);\n }\n if (name === \"min\" || name === \"max\") {\n const branded = value.arguments.map((item) => apiExpressionType(item, args, tables, checker, environment))\n .find((item) => /^(Decimal|Money)</.test(item.text));\n if (branded) return branded;\n }\n }\n const text = checker.typeToString(\n checker.getTypeAtLocation(value),\n value,\n ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.InTypeAlias,\n ).replaceAll('import(\"snapback2\").', \"\");\n return { text, special: apiTypeIsSpecial(text) };\n}\n\nfunction apiLocalBinding(type: ApiType | undefined): ApiTypeBinding {\n return {\n kind: \"local\",\n ...(type ? { type } : {}),\n ...(type?.row ? { row: type.row } : {}),\n ...(type?.element?.row ? { elementRow: type.element.row } : {}),\n };\n}\n\nfunction apiCloneEnvironment(environment: ApiTypeEnvironment): ApiTypeEnvironment {\n return {\n bindings: new Map([...environment.bindings].map(([name, binding]) => [\n name,\n binding.kind === \"args\" ? binding : { ...binding },\n ])),\n };\n}\n\nfunction apiMergeEnvironments(\n target: ApiTypeEnvironment,\n before: ApiTypeEnvironment,\n branches: ApiTypeEnvironment[],\n): void {\n for (const [name, original] of before.bindings) {\n if (original.kind === \"args\") continue;\n const bindings = branches.map((branch) => branch.bindings.get(name)).filter((item): item is ApiTypeBinding => Boolean(item));\n const locals = bindings.filter((item): item is Extract<ApiTypeBinding, { kind: \"local\" }> => item.kind === \"local\");\n const types = locals.flatMap((binding) => binding.type ? [binding.type] : []);\n const type = types.reduce<ApiType | undefined>((result, item) => result ? apiUnionType(result, item) : item, undefined);\n target.bindings.set(name, apiLocalBinding(type));\n }\n}\n\nfunction apiNarrowNullGuard(condition: ts.Expression, whenTrue: ApiTypeEnvironment, whenFalse: ApiTypeEnvironment): void {\n const value = unwrapExpression(condition);\n if (!ts.isBinaryExpression(value)) return;\n const left = unwrapExpression(value.left);\n const right = unwrapExpression(value.right);\n const identifier = ts.isIdentifier(left) && right.kind === ts.SyntaxKind.NullKeyword\n ? left\n : ts.isIdentifier(right) && left.kind === ts.SyntaxKind.NullKeyword ? right : undefined;\n if (!identifier) return;\n const equal = value.operatorToken.kind === ts.SyntaxKind.EqualsEqualsToken\n || value.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken;\n const unequal = value.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsToken\n || value.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken;\n if (!equal && !unequal) return;\n const present = unequal ? whenTrue : whenFalse;\n const binding = present.bindings.get(identifier.text);\n if (binding?.kind === \"local\" && binding.type) present.bindings.set(identifier.text, apiLocalBinding(apiWithoutNull(binding.type)));\n}\n\nfunction apiNamedRowType(table: TableInfo): ApiType {\n return { text: apiRowName(table.name), special: true, row: table };\n}\n\nfunction apiTypeField(type: ApiType, name: string): ApiType | undefined {\n const explicit = type.fields?.[name];\n if (explicit) return explicit;\n if (!type.row) return undefined;\n if (name === \"id\") return { text: \"string\", special: true };\n const authored = type.row.columns?.[name];\n if (!authored) return undefined;\n const optional = authored.kind === \"optional\";\n return {\n text: `${apiAuthoredType(optional ? authored.of : authored)}${optional ? \" | undefined\" : \"\"}`,\n special: true,\n optional,\n };\n}\n\nfunction apiObjectField(name: string, type: ApiType): string {\n return `${quoteProperty(name)}${type.optional ? \"?\" : \"\"}: ${type.text}`;\n}\n\nfunction apiArrayType(element: ApiType): ApiType {\n return {\n text: `${element.groupedInArray ? `(${element.text})` : element.text}[]`,\n special: element.special,\n element,\n };\n}\n\nfunction apiUnionType(left: ApiType, right: ApiType): ApiType {\n if (left.text === right.text) return {\n ...left,\n special: left.special || right.special,\n optional: left.optional || right.optional,\n };\n if (left.text === \"unknown[]\" && !left.element && (right.element || right.text.endsWith(\"[]\"))) return right;\n if (right.text === \"unknown[]\" && !right.element && (left.element || left.text.endsWith(\"[]\"))) return left;\n if (left.element && right.element) return apiArrayType(apiUnionType(left.element, right.element));\n const items = [left, right].sort((a, b) => Number(apiNullishType(a)) - Number(apiNullishType(b)));\n const members = [...new Set(items.flatMap((item) => apiUnionMembers(item.text)))];\n const shaped = items.find((item) => item.fields || item.row);\n return {\n text: members.join(\" | \"),\n special: left.special || right.special,\n ...(shaped?.fields ? { fields: shaped.fields } : {}),\n ...(shaped?.row ? { row: shaped.row } : {}),\n optional: left.optional || right.optional,\n groupedInArray: true,\n };\n}\n\nfunction apiWithoutNull(type: ApiType): ApiType {\n return { ...type, text: apiRemoveUnionMember(type.text, \"null\") };\n}\n\nfunction apiWithoutUndefined(type: ApiType): ApiType {\n return { ...type, text: apiRemoveUnionMember(type.text, \"undefined\"), optional: false };\n}\n\nfunction apiRemoveUnionMember(text: string, member: string): string {\n const parts = apiUnionMembers(text).filter((item) => item !== member);\n return parts.join(\" | \") || \"never\";\n}\n\nfunction apiIncludesNull(type: ApiType): boolean {\n return apiUnionMembers(type.text).includes(\"null\");\n}\n\nfunction apiNullishType(type: ApiType): boolean {\n return type.text === \"null\" || type.text === \"undefined\";\n}\n\nfunction apiHasNonNullAssertion(node: ts.Expression): boolean {\n let value = node;\n while (ts.isParenthesizedExpression(value) || ts.isAsExpression(value)) value = value.expression;\n return ts.isNonNullExpression(value);\n}\n\nfunction apiUnionMembers(text: string): string[] {\n const members: string[] = [];\n let start = 0;\n let depth = 0;\n let quote = \"\";\n for (let index = 0; index < text.length; index += 1) {\n const character = text[index]!;\n if (quote) {\n if (character === quote && text[index - 1] !== \"\\\\\") quote = \"\";\n continue;\n }\n if (character === '\"' || character === \"'\") {\n quote = character;\n continue;\n }\n if (\"{[(<\".includes(character)) depth += 1;\n else if (\"}])>\".includes(character)) depth -= 1;\n else if (depth === 0 && text.slice(index, index + 3) === \" | \") {\n members.push(text.slice(start, index));\n start = index + 3;\n index += 2;\n }\n }\n members.push(text.slice(start));\n return members;\n}\n\nfunction apiRecurseRow(node: ts.Expression, tables: Map<string, TableInfo>): TableInfo | undefined {\n const callback = unwrapExpression(node);\n if (!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)) return undefined;\n let row: TableInfo | undefined;\n const find = (item: ts.Node): void => {\n if (row) return;\n if (ts.isCallExpression(item) && callLeaf(item) === \"get\" && item.arguments[0]) {\n row = apiTable(item.arguments[0], tables);\n if (row) return;\n }\n ts.forEachChild(item, find);\n };\n find(callback.body);\n return row;\n}\n\nfunction apiBindingNames(name: ts.BindingName): string[] {\n if (ts.isIdentifier(name)) return [name.text];\n return name.elements.flatMap((element) => ts.isBindingElement(element) ? apiBindingNames(element.name) : []);\n}\n\nfunction apiAuthoredType(value: AuthoredType): string {\n if (value.kind === \"int\") return \"number\";\n if (value.kind === \"string\") return \"string\";\n if (value.kind === \"principal\") return \"Principal\";\n if (value.kind === \"bytes\") return \"Bytes\";\n if (value.kind === \"asset\") return value.asset === \"image\" ? \"ImageAsset\" : \"VideoAsset\";\n if (value.kind === \"bool\") return \"boolean\";\n if (value.kind === \"json\") return \"Json\";\n if (value.kind === \"decimal\") {\n return value.currency ? `Money<${JSON.stringify(value.currency)}, ${value.scale}>` : `Decimal<${value.scale}>`;\n }\n if (value.kind === \"enum\") return value.variants.map((item) => JSON.stringify(item)).join(\" | \") || \"never\";\n if (value.kind === \"list\") return `${apiAuthoredType(value.of)}[]`;\n if (value.kind === \"optional\") return apiAuthoredType(value.of);\n if (value.kind === \"row\") return apiRowName(value.table);\n return \"unknown\";\n}\n\nfunction apiTypeIsSpecial(text: string): boolean {\n return /\\b(?:Decimal|Money)</.test(text)\n || /\\b(?:ImageAsset|VideoAsset)\\b/.test(text)\n || text.includes(\" | \");\n}\n\nfunction apiTable(node: ts.Expression, tables: Map<string, TableInfo>): TableInfo | undefined {\n const path = staticMemberPath(node);\n if (!path) return undefined;\n const direct = tables.get(path);\n if (direct) return direct;\n const separator = path.lastIndexOf(\".\");\n return separator > 0 ? tables.get(path.slice(0, separator)) : undefined;\n}\n\nfunction quoteProperty(value: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(value) ? value : JSON.stringify(value);\n}\n"],
5
+ "mappings": "AAAA,OAAS,cAAAA,GAAY,gBAAAC,OAAoB,UACzC,OAAS,SAAAC,GAAO,SAAAC,GAAO,WAAAC,GAAS,WAAAC,GAAS,YAAAC,GAAU,YAAAC,GAAU,UAAAC,GAAQ,MAAAC,GAAI,aAAAC,OAAiB,mBAC1F,OAAS,YAAAC,GAAU,WAAAC,GAAS,cAAAC,GAAY,QAAAC,GAAM,YAAAC,GAAU,WAAAC,GAAS,OAAAC,OAAW,YAC5E,OAAS,iBAAAC,GAAe,iBAAAC,OAAqB,WAC7C,OAAOC,OAAQ,aCJf,OAAOC,MAAQ,aCAf,OAAOC,OAAQ,aCAf,OAAOC,MAAQ,aAKf,IAAMC,GAAkB,IAAI,IAAoB,CAC9C,QAAS,WAAY,SAAU,UAAW,QAAS,SAAU,OAAQ,MACvE,CAAC,EAEM,SAASC,GAAiBC,EAAyBC,EAAaD,EAAK,cAAc,EAA+B,CACvH,IAAME,EAAQ,IAAI,IACZC,EAAa,IAAI,IACvB,QAAWC,KAAaH,EAAW,WAAY,CAC7C,GAAI,CAACJ,EAAG,oBAAoBO,CAAS,GAAK,CAACP,EAAG,gBAAgBO,EAAU,eAAe,GAClFA,EAAU,gBAAgB,OAAS,YAAa,SACrD,IAAMC,EAAWD,EAAU,cAAc,cACzC,GAAIC,GAAYR,EAAG,eAAeQ,CAAQ,EACxC,QAAWC,KAAQD,EAAS,SAAU,CACpC,IAAME,EAAWD,EAAK,cAAc,MAAQA,EAAK,KAAK,KAClDR,GAAgB,IAAIS,CAA0B,GAAGL,EAAM,IAAII,EAAK,KAAK,KAAMC,CAA0B,CAC3G,MACSF,GAAYR,EAAG,kBAAkBQ,CAAQ,GAClDF,EAAW,IAAIE,EAAS,KAAK,IAAI,CAErC,CACA,GAAIR,EAAG,aAAaG,EAAK,U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ASyH,CAAkB,EAAIxF,CACrF,CAEA,SAAS9F,GAAarB,EAAciB,EAAsB,CACxD,OAAOyJ,GAAS1K,EAAM4K,GAAW3J,CAAI,EAAIA,EAAOb,GAAQa,CAAI,CAAC,EAAE,MAAM0J,EAAG,EAAE,KAAK,GAAG,CACpF,CAMA,SAASkC,GAAQC,EAAyB,CACxC,OAAO,KAAK,OAAO,YAAY,IAAI,EAAIA,GAAW,GAAG,EAAI,GAC3D",
6
+ "names": ["existsSync", "readFileSync", "lstat", "mkdir", "mkdtemp", "readdir", "readFile", "realpath", "rename", "rm", "writeFile", "basename", "dirname", "isAbsolute", "join", "relative", "resolve", "sep", "fileURLToPath", "pathToFileURL", "ts", "ts", "ts", "ts", "snapbackSymbols", "snapbackCallName", "call", "sourceFile", "named", "namespaces", "statement", "bindings", "item", "imported", "findAncestor", "node", "predicate", "parent", "replaceNode", "source", "replacement", "applyEdits", "edits", "a", "b", "text", "edit", "containsIncrement", "found", "walk", "child", "containsCall", "suffix", "callName", "firstDescendantCall", "findNarrowestNode", "position", "best", "visit", "previousStatement", "statements", "statementSiblings", "index", "nextStatement", "hasExport", "modifier", "hasAsyncModifier", "isFunctionLike", "isEffectFunction", "current", "unwrapCall", "value", "unwrapExpression", "staticMemberPath", "base", "memberName", "node", "ts", "collectionConstructor", "value", "unwrapExpression", "isDb", "binding", "isDbMember", "isDbWriteCall", "call", "unwrapCall", "isDbInsertCall", "isNullableDbGet", "nonNullIdentifier", "temporary", "holder", "label", "temp", "syntheticIdentifier", "_sourceFile", "name", "propertyName", "expressionProperty", "object", "item", "numberProperty", "numericLiteral", "expandedNumericLiteral", "text", "match", "integer", "authoredFraction", "exponent", "digits", "point", "whole", "fraction", "stringLiteral", "stringArgument", "isZero", "literal", "encoded", "binaryOperator", "kind", "singular", "table", "identifierFromArgsOrLocal", "node", "isOperationArgs", "value", "unwrapExpression", "ts", "base", "expansionContext", "parent", "sourceFile", "contextualNodeKey", "context", "expandArgumentObject", "object", "constants", "moduleArgumentObjects", "entries", "active", "invalidSpread", "invalidProperty", "expand", "value", "property", "ts", "spread", "unwrapExpression", "target", "name", "propertyName", "argumentSpreadRewrite", "source", "replaceNode", "sourceFile", "objects", "statement", "declaration", "Refusal", "diagnostic", "module", "code", "node", "message", "rewrite", "location", "span", "diagnosticFamily", "diagnosticRule", "diagnosticGuide", "refuse", "module", "code", "node", "message", "rewrite", "Refusal", "diagnostic", "typeDiagnostic", "family", "file", "line", "col", "guide", "diagnosticRule", "boundedDiagnostics", "values", "limit", "scope", "seen", "unique", "item", "key", "left", "right", "kept", "exemplar", "more", "total", "represented", "span", "start", "position", "diagnosticFamily", "diagnosticGuide", "ts", "ts", "ts", "MAX_RECURSION_DEPTH", "guardedWalk", "env", "node", "kind", "walk", "activeKinds", "refuseRecursiveWalk", "remaining", "expression", "ts", "rewrite", "replaceNode", "refuse", "ts", "ts", "expandHelper", "node", "env", "call", "unwrapCall", "ts", "helper", "refuse", "body", "helperBodyExpression", "next", "name", "info", "expansionContext", "parameter", "index", "argument", "resolveSubstitution", "value", "environment", "seen", "unwrapped", "unwrapExpression", "substitution", "refuseRecursiveWalk", "ts", "UNKNOWN_DIRECT_ORIGIN", "assignedBindings", "handler", "assigned", "functionScope", "parameter", "declareBinding", "visitBindingMutations", "collectionSharingSites", "edges", "directEscapes", "visitCollectionSharing", "graph", "edge", "addAliasEdge", "aliases", "escapes", "bindings", "binding", "pending", "seen", "aliasSites", "escapeSites", "current", "site", "isLocallyCreatedCollection", "node", "value", "unwrapExpression", "ts", "collectionConstructor", "initializer", "collectionMutationRewrite", "info", "mutation", "owner", "env", "conflictingCollectionEscapeSites", "sharingSites", "copySite", "spreadCopyRewrite", "declaration", "copy", "method", "replaceNode", "argument", "requireCollectionMutation", "reason", "refuse", "operationCompositeBindings", "element", "property", "propertyName", "isOperationCompositeBinding", "name", "composite", "resolvesOperationComposite", "substitution", "scope", "block", "statement", "loop", "nested", "resolveBinding", "child", "source", "target", "origin", "right", "recordEscapeContexts", "other", "adjacent", "sites", "edits", "left", "rewritten", "edit", "mutationStart", "sharesEnclosingLoopBody", "leftBodies", "enclosingLoopBodies", "body", "isWithin", "bodies", "ancestor", "expression", "recordEscapedExpression", "recordEscapedIdentifier", "replacement", "directOriginCandidates", "guardedWalk", "directOriginCandidatesInner", "args", "candidate", "directCandidatesForOrigins", "candidates", "direct", "withDirectRewrite", "candidateAmbiguity", "recordAssignmentOrigin", "discovered", "distinct", "origins", "moduleBasename", "fileName", "collectionElementOrigins", "node", "env", "guardedWalk", "collectionElementOriginsInner", "value", "unwrapExpression", "ts", "substituted", "info", "flattenCollectionOrigins", "elementOrigin", "selected", "selectExpressionMember", "origins", "elementEnvironment", "snapshotEnvironment", "element", "spread", "whenTrue", "whenFalse", "call", "unwrapCall", "expanded", "expandHelper", "callName", "isDbMember", "binding", "isOperationCompositeBinding", "rowFields", "rows", "method", "owner", "callback", "callbackEnv", "collectionElementBinding", "elements", "origin", "nested", "selectOriginMembers", "member", "descriptor", "unwrapped", "max", "item", "mergeMemberAlternatives", "laterOptional", "property", "propertyName", "originDirectCandidates", "candidates", "candidate", "directOriginCandidates", "alternatives", "found", "name", "_max", "_boundSource", "_elementOrigins", "_alternativeOrigins", "target", "staticMemberPath", "columns", "readProvenance", "node", "env", "result", "classify", "refuseAmbiguous", "provenanceBinding", "candidateAmbiguity", "UNKNOWN_DIRECT_ORIGIN", "combinedProvenanceBinding", "nodes", "bindings", "ambiguous", "binding", "combineProvenance", "collectionElementBinding", "origins", "collectionElementOrigins", "classified", "combineAlternatives", "origin", "classifyOrigin", "originDirectCandidates", "collectionOriginsBinding", "authoredNode", "path", "guardedWalk", "classifyInner", "value", "unwrapExpression", "substituted", "ts", "classifyIdentifier", "known", "classifyObject", "classifyObjectMember", "combineClassifications", "element", "expression", "expanded", "expandHelper", "isRowCall", "classifyRow", "children", "child", "info", "merged", "descriptor", "absent", "classifyBoundRow", "classifyBinding", "members", "property", "selected", "rest", "laterOptional", "candidate", "selectedOrigins", "selectExpressionMember", "withCandidates", "directOriginCandidates", "propertyName", "call", "fields", "rowFields", "values", "ambiguousValue", "provenances", "presence", "candidates", "knownValues", "inherited", "allCandidates", "incomplete", "first", "provenance", "directRewrite", "callName", "isDbMember", "isOperationCompositeBinding", "target", "staticMemberPath", "columns", "directCandidates", "choices", "replacementFor", "direct", "choice", "honestRewrite", "replacement", "candidateMessage", "refuse", "replaceNode", "discovered", "sentinelRewrite", "description", "meaningful", "isRowExpression", "isRowExpressionInner", "unwrapCall", "isRowCollectionExpression", "isRowCollectionExpressionInner", "callback", "body", "callbackEnv", "snapshotEnvironment", "ts", "knownObjectFields", "node", "env", "guardedWalk", "knownObjectFieldsInner", "value", "unwrapExpression", "ts", "substituted", "info", "selected", "selectedObjectMember", "fields", "property", "spread", "field", "name", "propertyName", "call", "unwrapCall", "expanded", "expandHelper", "callName", "isDbMember", "binding", "isOperationCompositeBinding", "rowFields", "member", "origin", "rowCollectionFields", "rowCollectionFieldsInner", "callback", "isFunctionLike", "body", "isRowCollectionExpression", "nullableReadSpread", "nullableSpreadRefusal", "rewrite", "refuse", "objectSpreadRewrite", "replaceNode", "arraySpreadRewrite", "target", "columns", "ts", "operationArgumentList", "node", "env", "value", "unwrapExpression", "ts", "base", "argument", "derivedBound", "known", "staticBound", "guardedWalk", "staticBoundInner", "substituted", "info", "alternativeOriginBound", "operationList", "selected", "selectExpressionMember", "bounds", "origin", "originBound", "bound", "total", "element", "whenTrue", "whenFalse", "collectionConstructor", "initializer", "call", "unwrapCall", "expanded", "expandHelper", "callName", "take", "scanTake", "numericLiteral", "method", "owner", "start", "end", "callback", "isFunctionLike", "inner", "values", "options", "expressionProperty", "collectionMutationIncrement", "info", "name", "env", "identity", "addCollectionMutationCount", "target", "count", "prior", "total", "maintainCollectionFacts", "facts", "setOrDelete", "collectionFactsFor", "node", "max", "boundSource", "elementOrigins", "collectionElementOrigins", "appendCollectionFacts", "value", "summarize", "candidates", "directCandidatesForBinding", "originDirectCandidates", "candidateAmbiguity", "origins", "snapshotEnvironment", "summary", "mergeAssignedCollectionFacts", "nextMax", "nextBoundSource", "nextOrigins", "priorOrigins", "mergeCollectionFactAlternatives", "alternatives", "maxima", "maximum", "items", "key", "ts", "unknownType", "intType", "idType", "isIdType", "value", "authoredTypeFromColumn", "descriptor", "requiredType", "sameDecimal", "left", "right", "checkScanPrefix", "node", "env", "table", "index", "prefixLength", "indexInfo", "candidate", "diagnostic", "overlongPrefixRewrite", "checkTupleCursor", "value", "unwrapExpression", "remainingColumns", "expectedTypes", "removeCursorProperties", "totalOrderColumns", "column", "expanded", "expandHelper", "shapeValue", "shapeEnv", "authored", "expressionType", "elements", "ts", "knownNonScalar", "staticallyObjectExpression", "knownRuntimeScalar", "argumentTupleRewrite", "shapeMatches", "tuple", "tupleExpression", "tupleRewrite", "replaceNode", "rewrite", "components", "bound", "propertyName", "component", "offset", "actual", "expected", "cursorTypeMatches", "cursorTypeName", "seen", "substitution", "origin", "property", "object", "optionsWithoutCursorProperties", "columnCount", "prefix", "element", "call", "options", "edits", "replaceRanges", "name", "base", "authoredTypeFromColumn", "baseType", "contextualNodeKey", "row", "requiredType", "field", "type", "nonNull", "left", "right", "isIdType", "columns", "rowBase", "unwrapped", "bindingTable", "bases", "first", "authoredBase", "rowBinding", "info", "types", "operation", "enclosingOperation", "argsNode", "handler", "argsObject", "used", "names", "uniqueArgument", "declarations", "descriptor", "rewrittenArgs", "binding", "parameter", "uniqueBinding", "text", "parent", "callName", "suffix", "source", "ranges", "rewritten", "range", "concatExpressions", "expressions", "left", "right", "rowFields", "target", "env", "value", "unwrapExpression", "binding", "ts", "columns", "isKnownRowOrObject", "expression", "knownObjectFields", "isRowExpression", "lowerPropertyValue", "base", "collection", "lowerOptionalPropertyChain", "lowerValue", "hint", "segments", "baseNode", "baseName", "temporary", "result", "lowerSegments", "index", "current", "segment", "accessed", "body", "next", "literal", "loopDomainMaximum", "domain", "recurse", "total", "lowerPatch", "node", "env", "ts", "refuse", "callbackEnv", "cloneEnvironment", "name", "lowerExpr", "lowerDomain", "expression", "binding", "hint", "guardedWalk", "lowerDomainInner", "expanded", "expandHelper", "call", "unwrapCall", "callName", "reference", "tableReference", "lowerScan", "rowFields", "start", "numericLiteral", "end", "value", "lowerRecurse", "operationList", "operationArgumentList", "collectionElementBinding", "identifier", "identifierFromArgsOrLocal", "info", "maximum", "staticBound", "seed", "step", "options", "isFunctionLike", "depth", "numberProperty", "fanout", "row", "body", "get", "isDbMember", "isOperationCompositeBinding", "ref", "key", "allocateReadSite", "lowerExprInner", "substituted", "unwrapped", "unwrapExpression", "literal", "scaled", "contextualNodeKey", "expandedNumericLiteral", "fractional", "scale", "replaceNode", "authored", "isIdType", "segments", "plain", "flush", "element", "arraySpreadRewrite", "error", "captureRefusal", "concatExpressions", "object", "property", "nullable", "nullableReadSpread", "nullableSpreadRefusal", "fields", "knownObjectFields", "objectSpreadRewrite", "field", "base", "propertyName", "composite", "isKnownRowOrObject", "op", "binaryOperator", "parts", "span", "lowerCall", "Refusal", "compositeMember", "compositeCall", "lowerRead", "conversation", "combineProvenance", "readProvenance", "builtin", "args", "arg", "required", "left", "right", "method", "owner", "lowerSort", "comparator", "lowerSortExpression", "leftParam", "rightParam", "firstParam", "secondParam", "order", "target", "lowerKey", "prefix", "takeNode", "expressionProperty", "take", "literalTake", "operationArgument", "max", "orderNode", "authoredOrder", "stringLiteral", "rangeNode", "loweredPrefix", "afterNode", "beforeNode", "opaqueCursorNode", "opaqueCursor", "checkScanPrefix", "checkTupleCursor", "mergeSiteNode", "mergeSite", "optionalLower", "path", "staticMemberPath", "direct", "separator", "identity", "lowered", "enterLexicalScope", "site", "reserveWriteSite", "containsRead", "seen", "MAX_RECURSION_DEPTH", "result", "item", "kind", "lowerArrayMethod", "lowerValue", "callback", "expectedParameters", "parameter", "loopEnv", "domainStatements", "domain", "bindingInfo", "lowerCollectionDomain", "temporary", "resultOrigin", "withDirectRewrite", "provenanceBinding", "callbackValue", "identityMap", "preservesRows", "elementOrigins", "bindingOrigins", "bound", "derivedBound", "maintainCollectionFacts", "innerBinding", "inner", "loopDomainMaximum", "initial", "accumulator", "reduceEnv", "syntheticIdentifier", "loweredDomain", "rowCollection", "isRowCollectionExpression", "rowCollectionFields", "_elements", "valueBinding", "forkBranchEnvironment", "env", "environment", "cloneEnvironment", "collectionMutationCounts", "mergeBranchEnvironments", "branches", "site", "name", "target", "alternatives", "branch", "candidates", "info", "candidateAmbiguity", "mergeCollectionFactAlternatives", "identities", "identity", "maximum", "entry", "addCollectionMutationCount", "LOOP_MUTATION_FIXPOINT_LIMIT", "lowerLoopBodyWithMutationPlan", "statement", "env", "iterations", "domainIdentity", "lowerBody", "ancestorDeferred", "inherited", "inheritedCollections", "plan", "settleLoopMutationPlan", "applyLoopMutationPlan", "parentMutationCounts", "body", "identity", "mutation", "scaled", "refuse", "addCollectionMutationCount", "name", "info", "priorCounts", "priorFacts", "pass", "probe", "isolatedAnalysisEnvironment", "collection", "variableByIdentity", "prior", "copyCollectionBounds", "maximum", "maintainCollectionFacts", "unbound", "diagnostic", "Refusal", "counts", "facts", "sameMutationCounts", "target", "source", "cloneEnvironment", "copyCollectionState", "preferredName", "preferred", "left", "right", "ts", "lowerMergeByIndex", "call", "env", "hint", "lowerValue", "lowerExpr", "rows", "fields", "order", "stringArgument", "limit", "site", "table", "ts", "unwrapExpression", "refuse", "lowered", "sorted", "field", "name", "deduped", "literal", "ts", "lowerCollectionConstructor", "expression", "env", "lowerValue", "hint", "kind", "collectionConstructor", "refuse", "initializer", "lowerSetConstructor", "entries", "unwrapExpression", "ts", "statements", "result", "temporary", "maximum", "entry", "pair", "requirePrimitiveCollectionIdentity", "key", "value", "lowerMapAssignment", "lowered", "max", "staticBound", "sourceValue", "element", "source", "item", "existing", "found", "literal", "target", "boundSource", "authoredKey", "authoredValue", "keyName", "valueName", "replacement", "lowerCollectionLookup", "owner", "needle", "mode", "info", "binding", "needleName", "candidate", "assignment", "node", "label", "listElement", "type", "contextualNodeKey", "required", "requiredType", "upsertIdentityMatches", "key", "row", "binding", "resolveRowContainer", "id", "sameIr", "expressionConsumesNewId", "expression", "seen", "value", "item", "left", "right", "index", "leftRecord", "rightRecord", "leftKeys", "rightKeys", "ts", "findPolicyRefusals", "module", "limit", "found", "add", "item", "visit", "node", "currentFunction", "isFunctionLike", "isEffectFunction", "ts", "diagnostic", "rewriteWhile", "hasAsyncModifier", "name", "callName", "rewriteAmbientTime", "child", "reductions", "scans", "forLoops", "structuralSorts", "walk", "memberName", "isZero", "containsCall", "reduction", "scan", "firstDescendantCall", "scanTake", "rewriteUnboundCount", "scanIsPrivate", "structuralDiagnostic", "access", "loop", "containsIncrement", "structuralLoopDiagnostic", "boundedSplit", "rewriteSplit", "rewriteMapReturns", "rewriteAllScans", "boundRefusals", "replacement", "maintainedReplacement", "replaceNode", "start", "end", "previous", "previousStatement", "next", "nextStatement", "target", "prefix", "table", "tableReference", "maintained", "info", "key", "sourceFile", "source", "edits", "options", "at", "applyEdits", "callback", "binding", "base", "value", "numericLiteral", "variable", "body", "rewritten", "_match", "bindings", "values", "db", "results", "visitLoop", "factors", "takeNode", "expressionProperty", "take", "rowBytes", "declaredRowMax", "product", "total", "factor", "largest", "a", "b", "other", "widestRow", "outputRows", "closureRows", "allowance", "statement", "findAncestor", "tables", "tableName", "candidate", "size", "column", "declaredColumnMax", "variant", "ref", "unwrapExpression", "columns", "pinned", "ruleFields", "field", "rule", "fields", "record", "terms", "term", "ruleTermField", "exists", "children", "path", "staticMemberPath", "direct", "separator", "owner", "call", "expression", "text", "ts", "MAX_TYPE_ANALYSIS_DEPTH", "MAX_TYPE_ANALYSIS_NODES", "analyzeOperationTypes", "module", "call", "analyzer", "Analyzer", "callName", "argsObject", "unwrapExpression", "args", "ts", "property", "expandArgumentObject", "descriptorType", "handler", "isFunctionLike", "env", "assignedBindings", "parameter", "name", "bindingNames", "setBinding", "unknownType", "composite", "operationCompositeBindings", "programKind", "operation", "statements", "statement", "declaration", "type", "bindings", "bindingType", "identifier", "namedBinding", "mutable", "binding", "thenEnv", "cloneEnv", "narrowed", "nonNullIdentifier", "requiredType", "domain", "loop", "node", "expected", "quietFraction", "value", "target", "memoKey", "cached", "expressionKey", "contextualNodeKey", "result", "isIdType", "identityValueMatches", "isRuntimeValidatedIdentitySink", "authoredTypeName", "entries", "replaceNode", "constant", "opaqueScalarInitializer", "base", "field", "assetFieldType", "available", "replacement", "expressions", "span", "types", "expression", "identityScalar", "elementTarget", "values", "item", "commonType", "row", "fields", "spread", "propertyName", "left", "right", "argument", "nested", "quiet", "digits", "fractionalDigits", "decimalName", "minor", "scaledInteger", "operator", "operands", "flattenPlus", "operand", "retargetIdentity", "idType", "comparison", "decimal", "zero", "isIntegerZero", "same", "sameDecimal", "operatorText", "helper", "expansionContext", "index", "parameterName", "returned", "scaleNode", "scale", "input", "numericExpression", "method", "table", "rowType", "indexTypes", "key", "options", "valid", "numeratorNode", "divisorNode", "dropped", "surviving", "expectedDivisor", "integerLiteralValue", "numerator", "carried", "amount", "lists", "owner", "callback", "path", "staticMemberPath", "direct", "separator", "cursorTypes", "cursor", "element", "range", "bound", "isInsertIdSink", "ctx", "insertIdReplacement", "enclosingFunction", "uniqueBindingName", "inserted", "replaceSourceRanges", "directArgument", "directArgsProperty", "argsNode", "candidate", "idArgument", "uniqueArgumentName", "rewrittenArgs", "ranges", "argsBinding", "text", "initializer", "overall", "visit", "source", "fallback", "sourceEnv", "structural", "elementFallback", "elementSource", "helperReturnExpression", "array", "seen", "stable", "idOperands", "_", "code", "message", "rewrite", "diagnostic", "current", "parent", "object", "suffix", "rewritten", "unwrapCall", "maxNode", "variants", "scaleAt", "currencyNode", "inner", "found", "first", "asset", "expandedNumericLiteral", "expanded", "kind", "ts", "typecheckSource", "source", "fileName", "libText", "sourceName", "files", "options", "host", "name", "languageVersion", "text", "program", "item", "formatTypeDiagnostic", "diagnostic", "ts", "ts", "callLeaf", "node", "call", "unwrapCall", "snapback", "snapbackCallName", "leaf", "ts", "objectOf", "node", "value", "unwrapExpression", "ts", "property", "object", "name", "expressionProperty", "propertyEntries", "entries", "item", "propertyName", "stringValue", "numberValue", "booleanValue", "stringArray", "result", "staticJson", "constants", "bool", "number", "string", "output", "lowered", "spread", "entry", "moduleJsonConstants", "sourceFile", "statement", "declaration", "typeDiagnosticSite", "node", "file", "declaration", "ancestor", "ts", "call", "unwrapCall", "kind", "callLeaf", "property", "propertyName", "args", "guard", "current", "ts", "ir_contract_default", "IR_CONTRACT", "ir_contract_default", "ts", "RULE_TYPE_REWRITE", "validateRuleTypes", "module", "tableCalls", "channelCalls", "tableJson", "channelJson", "diagnostics", "catalog", "ruleTableCatalog", "name", "call", "config", "objectOf", "rules", "property", "subject", "side", "node", "validateRuleType", "validateFinalExistsTypes", "lowered", "args", "validateMaintainRuleTypes", "value", "unwrapExpression", "ts", "item", "readable", "target", "stringValue", "record", "columns", "indexes", "ruleUse", "unwrapCall", "callLeaf", "field", "actual", "ruleFieldType", "compatible", "ruleTypeDiagnostic", "ruleTypeLabel", "left", "ruleTermType", "right", "probe", "tableName", "indexName", "key", "targetShape", "index", "position", "term", "column", "expected", "ruleTypeFromDescriptor", "compatibleExists", "sourceTable", "constraints", "constraint", "finalNode", "finalExists", "tableNode", "indexNode", "keyNode", "compatibleFinalExists", "literal", "staticJson", "ruleLiteralType", "kind", "descriptor", "inner", "sameRuleType", "jsonLiteral", "targetTable", "targetColumn", "subjectTable", "termCall", "expectedRef", "message", "diagnostic", "lowerSchema", "source", "fileName", "sourceFile", "ts", "module", "diagnostics", "tableCalls", "channelCalls", "defaultCall", "statement", "call", "unwrapCall", "callLeaf", "schemaDiagnostic", "hasExport", "declaration", "tables", "name", "tableJson", "lowered", "lowerTable", "channelJson", "lowerChannel", "validateRuleTypes", "root", "objectOf", "validateKnownKeys", "validateRootRefs", "maintains", "lowerMaintains", "property", "validateMaintainRuleTypes", "item", "value", "info", "authObject", "key", "node", "booleanValue", "auth", "config", "columnsObject", "validateRecordShape", "columns", "entry", "propertyEntries", "lowerColumn", "authoredColumns", "column", "authoredTypeFromColumn", "indexes", "indexesObject", "names", "stringArray", "before", "uniqueNode", "unique", "indexableColumnDescriptor", "columnDescriptorName", "authoredIndexes", "index", "descriptor", "indexColumns", "unknownType", "tableInfo", "rulesObject", "ruleDiagnostic", "rules", "side", "lowerRule", "retainNode", "authoredRetention", "stringValue", "retain", "IR_CONTRACT", "constraints", "lowerConstraints", "isPublicRule", "detail", "invalidDescriptorRefusal", "variants", "validEnumVariants", "scale", "numberValue", "validScale", "currency", "max", "validPositiveInteger", "maxBytes", "target", "table", "unwrapExpression", "inner", "options", "leftExpected", "ruleFieldType", "rightExpected", "left", "lowerTerm", "right", "values", "tableName", "keyNode", "expected", "failed", "position", "term", "ruleProvenance", "requiredType", "scaled", "scaledRuleLiteral", "numericRuleLiteral", "diagnostic", "fractional", "findFractionalLiteral", "literal", "staticJson", "encoded", "encodeValue", "numeric", "expanded", "expandedNumericLiteral", "magnitude", "signed", "found", "visit", "output", "object", "cap", "by", "field", "immutable", "text", "min", "format", "textDescriptorMax", "finalNode", "finalExists", "finalExistsRewrite", "loweredTerms", "targetOwners", "dependencyEdges", "count", "sumObject", "validKind", "sumField", "firstOwner", "sourceColumns", "loweredTableColumns", "targetColumns", "groupFields", "assetColumnDescriptor", "numericMaintainDescriptor", "expectedValue", "sameColumnDescriptor", "allowedTargetColumns", "extra", "readableNode", "maintainSources", "edge", "leftRecord", "rightRecord", "leftKeys", "rightKeys", "argsObject", "args", "authoredArgs", "lowerArgDescriptor", "publishNode", "subscribeNode", "ttl", "known", "of", "validArgDescriptor", "path", "staticMemberPath", "lowerLegacyArgDescriptor", "declarations", "included", "exported", "entries", "itemExpected", "items", "variant", "callee", "sibling", "dot", "correctedScale", "authored", "rewrites", "invalidNativeDescriptorRefusal", "nativeDescriptorName", "owner", "bindings", "label", "code", "allowed", "message", "replacement", "rewrite", "schemaDeclarationRewrite", "current", "kind", "prefix", "ts", "duplicateHandlerBinding", "handler", "pattern", "ts", "bindings", "element", "property", "propertyName", "elements", "duplicateHandlerBindingRewrite", "module", "duplicate", "parameter", "body", "winner", "winnerName", "duplicateSet", "aliases", "name", "edits", "bodyStart", "rewritten", "edit", "left", "right", "nestedHandlerBinding", "nestedHandlerDestructuringRewrite", "occupied", "walk", "node", "declarations", "base", "alias", "suffix", "root", "collectDeclarations", "defaultText", "prefix", "declaration", "access", "sourceFile", "index", "binding", "bindingNames", "selected", "objectMemberAccess", "value", "ts", "inspectModule", "sourceFile", "source", "fileName", "options", "tables", "effects", "helpers", "statement", "ts", "declaration", "name", "call", "unwrapCall", "imported", "snapbackCallName", "localHelper", "callee", "tableName", "stringArgument", "maintainedFrom", "ts", "boundOperationDiagnostics", "diagnostics", "operations", "module", "assigned", "result", "name", "call", "selected", "item", "index", "match", "position", "boundedDiagnostics", "localConstructorShadow", "sourceFile", "constructors", "statement", "ts", "declaration", "refuseReservedAuthCode", "node", "code", "refuse", "replaceNode", "node", "statement", "builtinKind", "value", "entry", "expressionOrigin", "expr", "bindings", "kind", "data", "domainOrigin", "domain", "directPushTargets", "body", "resultPageSite", "program", "returned", "conditionalReturn", "containsReturn", "binding", "origin", "targets", "attachResultPageSite", "site", "captureRefusal", "diagnostics", "error", "Refusal", "lowerSource", "source", "fileName", "libText", "options", "sourceFile", "ts", "module", "inspectModule", "findPolicyRefusals", "operationSpans", "typed", "typecheckSource", "item", "node", "findNarrowestNode", "siteKind", "typeDiagnosticSite", "schemaLabelRewrite", "diagnostic", "formatTypeDiagnostic", "recognizableExports", "programs", "statement", "hasExport", "declaration", "call", "unwrapCall", "kind", "snapbackCallName", "name", "handler", "duplicateBinding", "isFunctionLike", "duplicateHandlerBinding", "duplicateHandlerBindingRewrite", "nestedBinding", "nestedHandlerBinding", "nestedHandlerDestructuringRewrite", "plan", "analyzeOperationTypes", "lowerOperation", "shadow", "localConstructorShadow", "bounded", "boundOperationDiagnostics", "boundedDiagnostics", "exportName", "kindName", "typePlan", "argObject", "refuse", "offending", "args", "expandedArgs", "expandArgumentObject", "argumentSpreadRewrite", "property", "argName", "loweredDescriptor", "lowerArgDescriptor", "invalid", "invalidNativeDescriptorRefusal", "lowered", "lowerLegacyArgDescriptor", "variables", "type", "info", "maintainCollectionFacts", "handlerBindings", "operationCompositeBindings", "collectionSharing", "collectionSharingSites", "environment", "moduleBasename", "assignedBindings", "body", "lowerStatements", "isDbWriteCall", "binding", "isOperationCompositeBinding", "lowerExpressionStatement", "lowerValue", "attachResultPageSite", "nodes", "env", "result", "lowerStatement", "out", "defaulted", "element", "identifiers", "argument", "values", "index", "temporary", "origin", "withDirectRewrite", "combinedProvenanceBinding", "identifier", "collection", "collectionConstructor", "isConst", "stableBinding", "loweredBinding", "rowCollection", "isRowCollectionExpression", "objectFields", "knownObjectFields", "rowCollectionFields", "classified", "provenanceBinding", "bindTime", "cloneEnvironment", "bound", "derivedBound", "facts", "collectionFactsFor", "isLocallyCreatedCollection", "isRowExpression", "isNullableDbGet", "literal", "condition", "thenBranch", "forkBranchEnvironment", "elseBranch", "thenEnv", "narrowed", "nonNullIdentifier", "thenBody", "lowerControlled", "elseBody", "mergeBranchEnvironments", "loopEnv", "enterLexicalScope", "statements", "domain", "bindingInfo", "lowerCollectionDomain", "iterations", "loopDomainMaximum", "domainIdentity", "lowerLoopBodyWithMutationPlan", "expression", "effectNode", "payloadNode", "effectPath", "staticMemberPath", "effect", "reserveWriteSite", "payload", "owner", "method", "requireCollectionMutation", "value", "appendCollectionFacts", "collectionMutationIncrement", "collectionOriginsBinding", "key", "requirePrimitiveCollectionIdentity", "loweredKey", "loweredValue", "priorMax", "increment", "lowerMapAssignment", "valueName", "found", "lowerCollectionLookup", "isDb", "lowerDbStatement", "recordAssignmentOrigin", "mergeAssignedCollectionFacts", "lowerExpr", "codeNode", "code", "stringArgument", "refuseReservedAuthCode", "target", "table", "tableReference", "row", "unwrapExpression", "lowerCallbackWrite", "lowerPatch", "upsertIdentityMatches", "callback", "callbackResult", "finalCallbackReturn", "ref", "site", "allocateReadSite", "authoredKey", "lowerKey", "keyTemporary", "containsRead", "singular", "scalarKey", "current", "callbackEnv", "syntheticIdentifier", "lowerBlockCallback", "readProvenance", "final", "hint", "returned", "whenTrue", "whenFalse", "op", "binaryOperator", "nullish", "left", "right", "leftName", "operand", "lowerOptionalPropertyChain", "base", "lowerPropertyValue", "object", "nullable", "nullableReadSpread", "nullableSpreadRefusal", "fields", "spread", "replaceNode", "field", "propertyName", "segments", "plain", "flush", "staticBound", "concatExpressions", "lowerCollectionConstructor", "memberName", "lowerSortExpression", "lowerArrayMethod", "isDbInsertCall", "loweredRow", "rowName", "lowerMergeByIndex", "lowerCollectionBuiltin", "expressions", "valueNode", "inputs", "limitNode", "ts", "collectEffectCatalog", "modules", "catalog", "module", "statement", "ts", "hasExport", "declaration", "call", "unwrapCall", "callLeaf", "name", "effectBindings", "bindings", "item", "targetModule", "moduleNameFromSpecifier", "imports", "qualified", "effect", "imported", "lowerEffects", "operations", "effects", "diagnostics", "left", "right", "lowered", "lowerEffect", "config", "objectOf", "grants", "stringArray", "property", "grant", "validGrant", "effectDiagnostic", "runNode", "run", "unwrapExpression", "closure", "validateClosure", "then", "thenNode", "resolved", "resolveOperation", "validThenArgs", "transpiled", "constants", "moduleJsonConstants", "constant", "value", "source", "roots", "root", "walk", "node", "parameter", "collectScopedBindings", "bindingOwner", "isScopedFunction", "allowed", "escaped", "isReferenceIdentifier", "binding", "isWithin", "spread", "invalidConstantSpread", "sourceFile", "invalid", "staticJson", "owner", "output", "fallback", "current", "parent", "isInsideType", "path", "staticMemberPath", "local", "prefix", "entry", "exported", "args", "entries", "expandArgumentObject", "descriptors", "url", "specifier", "code", "message", "callee", "rewrite", "diagnostic", "basename", "QuarryError", "site", "message", "code", "rewrite", "guide", "guideFor", "expanded", "contextualMessage", "refuse", "syntax", "unsupported", "construct", "alternative", "ambiguous", "typeError", "site", "message", "rewrite", "QuarryError", "retention", "guideFor", "code", "buildCatalog", "documents", "catalog", "document", "table", "refuse", "columns", "column", "indexes", "indexNames", "index", "ruleEffects", "rule", "info", "validateType", "channelNames", "channel", "validateArgs", "programNames", "program", "args", "names", "arg", "type", "site", "orderedTables", "selectIndex", "catalog", "table", "keys", "mode", "explicit", "infer", "site", "info", "refuse", "selected", "index", "validateIndexKeys", "named", "key", "candidates", "offset", "compatible", "columnType", "type", "exact", "spelling", "ambiguous", "item", "column", "actual", "expected", "fractionalNumericLiteral", "typeError", "typeName", "expr", "name", "MAX_SHAPE_DEPTH", "expandDocuments", "documents", "diagnostics", "document", "definitions", "shape", "QuarryError", "expander", "Expander", "error", "caught", "programs", "program", "statement", "uniqueDiagnostics", "name", "useSite", "depth", "stack", "declaration", "siteText", "item", "read", "expr", "nested", "value", "outerUse", "authoredFields", "field", "key", "lane", "fields", "annotate", "site", "seen", "diagnostic", "TWO_CHARACTER", "SYMBOLS", "HYPHENATED_WORDS", "lex", "file", "source", "tokens", "diagnostics", "report", "site", "message", "indents", "grouping", "lines", "lineIndex", "raw", "line", "leading", "offset", "current", "token", "emitted", "char", "pair", "quote", "value", "closed", "next", "escaped", "match", "prior", "afterRetain", "policyWord", "word", "col", "kind", "narrowThenBindings", "condition", "bindings", "target", "binding", "current", "emitSchema", "documents", "catalog", "sourceFile", "rootSite", "document", "lines", "withSite", "header", "table", "orderedTables", "emitTable", "channels", "declaration", "emitChannel", "identity", "maintains", "maintainCode", "item", "column", "property", "typeCode", "index", "ruleLines", "rule", "refuse", "emitRule", "constraints", "emitConstraints", "immutable", "fields", "finalExists", "read", "context", "selectIndex", "value", "ruleTermType", "key", "ruleTerm", "arg", "ruleExpr", "kind", "readable", "expr", "flattenBoolean", "leftType", "rightType", "fractionalNumericLiteral", "typeError", "compatibleRuleTypes", "brandedLiteralPair", "left", "right", "keys", "literalCode", "method", "type", "numericLiteral", "op", "code", "variant", "file", "mark", "line", "col", "siteMark", "site", "text", "Writer", "site", "text", "siteMark", "run", "Environment", "_Environment", "catalog", "program", "effects", "arg", "clone", "name", "binding", "emitPrograms", "programs", "sourceFile", "rootSite", "writer", "header", "effect", "emitProgram", "env", "args", "property", "typeCode", "emitBody", "body", "completion", "discardLast", "index", "statement", "isLast", "emitStatement", "discard", "refuse", "left", "emitExpr", "right", "value", "finishNull", "condition", "requireBoolean", "payload", "code", "inserted", "temporary", "thenEnv", "narrowThenBindings", "domain", "itemType", "nested", "emitMatch", "found", "emitRead", "local", "discardBranchValues", "branchCompletion", "result", "expr", "literalCode", "literalType", "emitName", "items", "item", "scalarOrUnknown", "types", "field", "numericAmountType", "typeError", "boolType", "emitBinary", "emitMember", "emitCall", "emitMerge", "read", "nonNullable", "emitShape", "info", "column", "seed", "walked", "current", "emitWrite", "operator", "refuseFractionalInt", "branded", "brandedType", "other", "otherExpr", "numericLiteral", "brandedName", "valueTypeName", "simpleExpr", "isScalar", "compatible", "isNullableValue", "leftText", "optionalComparisonOperand", "rightText", "member", "leftBrand", "rightBrand", "dropped", "divisor", "fractionalNumericLiteral", "directBinding", "base", "isRef", "refType", "key", "fields", "narrowed", "nullableValue", "target", "unsupported", "numerator", "resultType", "amount", "recipients", "recipient", "boundedItemType", "sameRecipientType", "argument", "literalExpressionText", "start", "literalNumber", "end", "max", "type", "fractional", "exists", "mode", "selectIndex", "inferExpr", "keys", "keyBinding", "remainingColumns", "_cursor", "_cursorKind", "range", "quarryExpression", "columns", "formatSite", "cursor", "options", "candidate", "lane", "width", "seen", "offset", "position", "actual", "expected", "mergeSite", "union", "emitLane", "scan", "row", "suffix", "deref", "emitPageShape", "rowType", "focalName", "shapeCode", "shapeType", "shapeObject", "table", "page", "focal", "prior", "properties", "emitFields", "validateAddressedKeyFields", "part", "emitted", "addressedFields", "emitIndexedWrite", "writeFields", "mentionsFocal", "rowName", "emitEvaluatedFields", "patch", "sourceFields", "emitEvaluatedFieldEntries", "authoredNames", "injected", "addressedId", "rowFields", "fieldCode", "validateFieldType", "replacements", "replacement", "authoredId", "quarryWriteWithoutField", "removed", "quarryKeyPart", "quarryObjectField", "rendered", "lanes", "validateFieldType", "field", "actual", "expected", "env", "expression", "fractionalNumericLiteral", "typeError", "literalExpressionText", "numericLiteral", "brandedName", "valueTypeName", "refuse", "expectedAsset", "nestedAssetShape", "actualAsset", "acceptsAsset", "assetExpressionAcceptsExpected", "wrapperMismatch", "wanted", "assetShapeName", "received", "inferredItem", "item", "inferExpr", "assetShapeAccepts", "type", "nested", "wrapper", "index", "shape", "name", "expr", "binding", "isScalar", "literalType", "base", "digits", "fractionalDigits", "scalarOrUnknown", "isRef", "nonNullable", "nullableValue", "isNullableValue", "requireBoolean", "construct", "nullable", "spelling", "simpleExpr", "optionalComparisonOperand", "rendered", "value", "quarryExpression", "boolType", "keyBinding", "compatible", "left", "right", "brandedType", "numericAmountType", "boundedItemType", "sameRecipientType", "text", "dot", "literalCode", "refuseFractionalInt", "fractional", "literalNumber", "property", "temporary", "kind", "site", "formatSite", "mentionsFocal", "expr", "key", "lane", "field", "RESERVED_BINDINGS", "PRECEDENCE", "parseDocument", "file", "source", "lexical", "lex", "parser", "Parser", "tokens", "diagnostics", "token", "unsupported", "syntax", "error", "site", "kind", "password", "guests", "name", "columns", "indexes", "rules", "immutable", "finalExists", "retain", "publicDecl", "publicSite", "retention", "policy", "value", "type", "unique", "explicit", "inferred", "title", "aggregateToken", "column", "by", "read", "readable", "effect", "declaration", "module", "effectToken", "bindings", "label", "binding", "quarryExpression", "focalizeRuleBinding", "args", "publish", "subscribe", "ttlSeconds", "key", "amount", "kindToken", "body", "fields", "refuse", "item", "min", "max", "format", "currency", "explicitScale", "variants", "payload", "names", "condition", "thenBody", "elseBody", "domain", "code", "someName", "someBody", "noneBody", "minimum", "stops", "left", "precedence", "right", "table", "items", "first", "initial", "predicate", "assertion", "named", "keys", "keySite", "order", "take", "cursor", "cursorKind", "index", "highestRank", "seen", "violation", "rank", "candidate", "point", "range", "bound", "cursorText", "lanes", "laneSite", "prefix", "loop", "expr", "base", "fieldSite", "opToken", "op", "depth", "rewrite", "scale", "offset", "QuarryError", "declarations", "field", "part", "FALLBACK", "whereRepairDiagnostics", "documents", "catalog", "diagnostics", "document", "program", "walkStatements", "expr", "repair", "read", "intent", "fallback", "info", "terms", "equalityTerms", "base", "baseIndex", "prefixColumns", "suffixColumns", "predicateColumns", "predicateValues", "seen", "term", "column", "indexable", "rendered", "quarryExpression", "prior", "prefixOffset", "leading", "compatible", "index", "total", "offset", "selected", "indexLine", "schemaMessage", "renderIndex", "siteText", "predicateSet", "columns", "unique", "collisionFreeName", "repaired", "value", "diagnostic", "indexes", "key", "named", "candidates", "left", "right", "type", "stem", "title", "names", "suffix", "site", "message", "rewrite", "statements", "visit", "statement", "walk", "item", "field", "lane", "compileQuarry", "inputs", "diagnostics", "documents", "input", "parsed", "parseDocument", "placementDiagnostics", "frontend", "expansion", "expandDocuments", "catalog", "materializeMaintains", "buildCatalog", "error", "caughtDiagnostic", "whereRepairDiagnostics", "schemaDocument", "document", "basename", "schemaInput", "schemaSource", "emitSchema", "moduleSources", "item", "valid", "program", "emitPrograms", "schema", "virtualModule", "modules", "remapVirtualDiagnostic", "diagnostic", "virtual", "generatedTypeError", "site", "parseSite", "authored", "mapGeneratedLine", "quarryDecimalRewrite", "remapVirtualSource", "quarryInspection", "module", "placement", "isSchema", "declarationSite", "stem", "declaration", "table", "QuarryError", "source", "columns", "name", "sourceColumn", "column", "summed", "indexName", "title", "deny", "effect", "assetGrouped", "containsAsset", "target", "type", "path", "authoredSource", "lineMap", "previous", "line", "match", "file", "col", "message", "rewrite", "offset", "mapped", "authoredLine", "value", "basename", "dirname", "isAbsolute", "relative", "resolve", "sep", "ts", "createProjectProgram", "schemaPath", "schemaSource", "moduleSources", "libText", "libPath", "resolve", "dirname", "files", "options", "ts", "host", "literals", "containingFile", "_redirectedReference", "compilerOptions", "literal", "name", "sourceFile", "read", "exists", "languageVersion", "onError", "shouldCreateNewSourceFile", "text", "program", "projectTypeDiagnostics", "projectRoot", "checker", "item", "sep", "selfTableReference", "exportedStaticTableUsedBeforeAssigned", "position", "file", "relativeSite", "message", "node", "findNarrowestNode", "siteKind", "typeDiagnosticSite", "typeDiagnostic", "typeDiagnosticRewrite", "declaration", "ancestor", "call", "unwrapCall", "callLeaf", "basename", "statement", "hasExport", "guard", "current", "lineStarts", "start", "next", "root", "path", "relative", "isAbsolute", "ts", "AuthoredSeedNumber", "text", "staticSeedJson", "node", "constants", "value", "unwrapExpression", "ts", "bool", "booleanValue", "string", "stringValue", "output", "item", "lowered", "spread", "entry", "propertyName", "moduleSeedJsonConstants", "sourceFile", "statement", "declaration", "validateSeedRow", "module", "table", "index", "columns", "diagnostics", "diagnostic", "row", "field", "type", "isOptionalColumn", "normalized", "normalizeSeedValue", "seedMismatch", "message", "path", "descriptor", "normalizeWholeUnits", "items", "plain", "plainSeedValue", "mismatch", "seedValueMismatch", "named", "scale", "match", "fractional", "digits", "minor", "maximum", "key", "IR_CONTRACT", "codePoint", "disallowedTextControlCodePoint", "encodedObject", "encoded", "jsonWireMismatch", "variants", "kind", "character", "sortSerdeMaps", "program", "left", "right", "sortNestedMaps", "value", "mapValue", "item", "entries", "ordered", "key", "readFile", "basename", "relative", "resolve", "sep", "ts", "authoredDeclarations", "quarryOnlyDiagnostics", "projectRoot", "hasTypeScriptSchema", "modulePaths", "diagnostics", "typeDiagnostic", "path", "source", "readFile", "fileName", "relativeSite", "sourceFile", "ts", "module", "locals", "statement", "declaration", "call", "unwrapCall", "kind", "snapbackCallName", "hasExport", "pushAuthored", "specifier", "local", "directKind", "authored", "name", "site", "diagnostic", "authoringMessage", "quarryHeader", "basename", "args", "objectOf", "fields", "expandArgumentObject", "entry", "quarryType", "node", "staticMemberPath", "numberValue", "options", "max", "property", "item", "stringValue", "root", "relative", "resolve", "sep", "ts", "generateApiDts", "operations", "program", "checker", "tables", "bindingsByModule", "grouped", "operation", "left", "right", "checkedCall", "checkedOperationCall", "args", "objectOf", "argsText", "apiArgsType", "handler", "resultText", "ts", "signature", "authored", "apiAuthoredResult", "items", "quoteProperty", "rowTypes", "apiRowType", "channels", "apiChannels", "modulesText", "name", "channelsText", "channelByName", "item", "channelOperations", "operationItems", "index", "channel", "operationNames", "channelItems", "catalog", "occupiedRoots", "aliases", "members", "schema", "statement", "hasExport", "declaration", "call", "unwrapCall", "callLeaf", "config", "property", "table", "fields", "type", "optional", "apiAuthoredType", "field", "apiRowName", "part", "file", "object", "acceptFiles", "expandArgumentObject", "entry", "argumentDescriptorType", "brand", "argumentBrand", "inner", "value", "descriptorType", "numberValue", "stringValue", "stringArray", "environment", "parameter", "apiBindingNames", "context", "element", "propertyName", "viewer", "apiExpressionType", "returns", "terminated", "apiStatements", "result", "current", "apiUnionType", "statements", "apiStatement", "apiLocalBinding", "apiExpressionEffect", "before", "apiCloneEnvironment", "whenTrue", "whenFalse", "apiNarrowNullGuard", "trueTerminates", "falseTerminates", "apiMergeEnvironments", "loop", "source", "node", "unwrapExpression", "receiver", "binding", "pushed", "apiArrayType", "expected", "asserted", "apiHasNonNullAssertion", "target", "requiredType", "apiWithoutNull", "propertyBase", "propertyBinding", "descriptor", "propertyEntries", "text", "apiTypeIsSpecial", "base", "apiTypeField", "apiIncludesNull", "special", "fieldTypes", "rowSpreads", "spread", "apiObjectField", "row", "collisions", "alias", "apiWithoutUndefined", "branded", "apiTable", "apiNamedRowType", "apiRecurseRow", "carried", "branches", "original", "branch", "condition", "identifier", "equal", "unequal", "present", "explicit", "a", "b", "apiNullishType", "apiUnionMembers", "shaped", "apiRemoveUnionMember", "member", "start", "depth", "quote", "character", "callback", "find", "path", "staticMemberPath", "direct", "separator", "lowerProject", "root", "options", "started", "projectRoot", "resolve", "authoredRoot", "join", "tsSchemaPath", "qSchemaPath", "hasTsSchema", "existsSync", "hasQuarrySchema", "typeDiagnostic", "elapsed", "discoveredModulePaths", "discoverModulePaths", "tsModulePaths", "path", "authored", "quarryOnlyDiagnostics", "quarryPaths", "relativeSite", "schemaPath", "schemaSource", "readFile", "virtualModules", "inputs", "compiled", "compileQuarry", "boundedDiagnostics", "virtualByFile", "module", "diskModuleSources", "virtualModuleSources", "moduleSources", "left", "right", "modules", "source", "moduleName", "ts", "schemaFileName", "schema", "lowerSchema", "programPaths", "basename", "diagnostics", "nestedModuleDiagnostics", "duplicateModuleBasenameDiagnostics", "rowAliasDiagnostics", "libText", "loadCompilerLib", "checked", "createProjectProgram", "projectTypeDiagnostics", "item", "remapDiagnostic", "operations", "collectOperations", "reservedApiPathDiagnostics", "catalog", "collectEffectCatalog", "loweredEffects", "lowerEffects", "programs", "sources", "bindingsByModule", "tables", "tableBindings", "effects", "effectBindings", "lowered", "lowerSource", "sortSerdeMaps", "declaration", "position", "operationBounded", "boundProjectOperationDiagnostics", "apiDts", "generateApiDts", "name", "site", "virtual", "remapVirtualSource", "quarryInspection", "directory", "paths", "entry", "readdir", "grouped", "group", "dirname", "names", "table", "alias", "apiRowName", "lowerSeed", "fileName", "sourceFile", "expression", "statement", "call", "unwrapCall", "callLeaf", "object", "objectOf", "constants", "moduleJsonConstants", "seedConstants", "moduleSeedJsonConstants", "value", "staticSeedJson", "record", "invalidSpread", "firstInvalidStaticSpread", "diagnostic", "personas", "personaNames", "loweredSchema", "rows", "seeded", "columns", "index", "row", "validateSeedRow", "listJourneys", "tests", "compileJourneys", "sourceFiles", "file", "buildRoot", "outputRoot", "unsafeOutput", "journeyOutputDiagnostic", "mkdir", "stagedOutput", "mkdtemp", "replaceDirectoryAtomically", "packageDist", "compilerPackageDist", "clientDts", "testDts", "stagedApi", "writeFile", "program", "sourceSet", "rm", "clientModule", "pathToFileURL", "testModule", "files", "sourcePath", "transpiled", "rewritten", "rewriteModuleSpecifiers", "outputName", "outputPath", "racedOutput", "target", "staged", "backup", "rename", "error", "components", "canonicalRoot", "realpath", "component", "lstat", "canonical", "fromRoot", "relative", "sep", "isAbsolute", "replacements", "edits", "add", "node", "replacement", "walk", "text", "edit", "here", "fileURLToPath", "hasExport", "kind", "operation", "schemaModule", "remaining", "result", "local", "spans", "boundOperationDiagnostics", "declared", "bindings", "imports", "exported", "invalid", "staticJson", "moduleCandidates", "subsetCandidates", "modulePath", "subsetPath", "readFileSync", "generatedTypeError", "remapVirtualDiagnostic", "elapsed", "started"]
7
+ }