@lunora/codegen 1.0.0-alpha.15 → 1.0.0-alpha.150

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 (90) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +3140 -1043
  4. package/dist/index.d.ts +3140 -1043
  5. package/dist/index.mjs +1 -32
  6. package/dist/packem_shared/AGENTS_FILENAME-B1Abt3Gl.mjs +1 -0
  7. package/dist/packem_shared/CONTAINERS_FILENAME-CtcysaKS.mjs +1 -0
  8. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_TARGET-lPq34YeN.mjs +1 -0
  10. package/dist/packem_shared/FLAGS_FILENAME-B3VZ6vTw.mjs +1 -0
  11. package/dist/packem_shared/GENERATED_HEADER--PCtJMQc.mjs +1 -0
  12. package/dist/packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs +1 -0
  13. package/dist/packem_shared/MUTATORS_FILENAME-DHX1qUP5.mjs +1 -0
  14. package/dist/packem_shared/NOTIFY_FILENAME-CKO5gtGe.mjs +1 -0
  15. package/dist/packem_shared/OPENRPC_VERSION-C4UXIUyy.mjs +3 -0
  16. package/dist/packem_shared/QUEUES_FILENAME-C-pzLGy4.mjs +1 -0
  17. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DazENDSB.mjs +9 -0
  18. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-B1BUjuG5.mjs +2 -0
  19. package/dist/packem_shared/SDK_LANGUAGES-CFyux-74.mjs +371 -0
  20. package/dist/packem_shared/SHAPES_FILENAME-DhZ3JkkH.mjs +1 -0
  21. package/dist/packem_shared/SchemaSnapshotParseError-yZc-1mxR.mjs +18 -0
  22. package/dist/packem_shared/WORKFLOWS_FILENAME-BfvqsG9Z.mjs +1 -0
  23. package/dist/packem_shared/ast-BYoSZlae.mjs +1 -0
  24. package/dist/packem_shared/buildOpenApiDocument-D5xOB07T.mjs +3 -0
  25. package/dist/packem_shared/chain-Dygm2apY.mjs +1 -0
  26. package/dist/packem_shared/classify-procedure-call-Ib2EMtFH.mjs +1 -0
  27. package/dist/packem_shared/context-property-calls-Br0sVv8E.mjs +1 -0
  28. package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
  29. package/dist/packem_shared/discoverAuthApiCalls-DoNQSgso.mjs +1 -0
  30. package/dist/packem_shared/discoverCrons-DCxl4hty.mjs +1 -0
  31. package/dist/packem_shared/discoverFunctions-CXURzTDU.mjs +1 -0
  32. package/dist/packem_shared/discoverHttpRoutes-2XhMbeh5.mjs +1 -0
  33. package/dist/packem_shared/discoverHyperdriveCalls-DTq4PKT5.mjs +1 -0
  34. package/dist/packem_shared/discoverInserts-qU5F4W4g.mjs +1 -0
  35. package/dist/packem_shared/discoverMaskProcedures-BZsC5dHd.mjs +1 -0
  36. package/dist/packem_shared/discoverMigrations-BFkJQ8Sy.mjs +1 -0
  37. package/dist/packem_shared/discoverNondeterministicCalls-B-NNzzPW.mjs +1 -0
  38. package/dist/packem_shared/discoverQueries-B4emAFn5.mjs +1 -0
  39. package/dist/packem_shared/discoverR2sqlCalls-C2GtrFnl.mjs +1 -0
  40. package/dist/packem_shared/discoverRlsMetadata-BKcUnSNr.mjs +1 -0
  41. package/dist/packem_shared/discoverRlsProcedures-fAhxiIyD.mjs +1 -0
  42. package/dist/packem_shared/discoverSandboxUsage-CJhnKA0_.mjs +1 -0
  43. package/dist/packem_shared/discoverSchema-D5XGH2wu.mjs +1 -0
  44. package/dist/packem_shared/discoverStorageRulesMetadata-C7XmORWp.mjs +1 -0
  45. package/dist/packem_shared/emit-CXfWb_pY.mjs +2302 -0
  46. package/dist/packem_shared/emitApp-DcrQNgaz.mjs +694 -0
  47. package/dist/packem_shared/exported-procedure-chains-M40rbSYM.mjs +1 -0
  48. package/dist/packem_shared/formatAdvisories-CkEu1eye.mjs +2 -0
  49. package/dist/packem_shared/index-xGhyK9J_.mjs +1 -0
  50. package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -0
  51. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  52. package/dist/packem_shared/parse-validator-CMV0eq2a.mjs +1 -0
  53. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  54. package/dist/packem_shared/queries-Ddvo5dCs.mjs +1 -0
  55. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  56. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  57. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  58. package/dist/packem_shared/unwrap-handler-return-CmIWbykC.mjs +1 -0
  59. package/package.json +16 -7
  60. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  61. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  62. package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
  63. package/dist/packem_shared/GENERATED_HEADER-CkZUgM4_.mjs +0 -2944
  64. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  65. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  66. package/dist/packem_shared/OPENRPC_VERSION-VINwUAxf.mjs +0 -60
  67. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  68. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DsBxQ5C_.mjs +0 -963
  69. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  70. package/dist/packem_shared/WORKFLOWS_FILENAME-D62dcBGg.mjs +0 -84
  71. package/dist/packem_shared/buildOpenApiDocument-BSoDzIn8.mjs +0 -183
  72. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  73. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  74. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  75. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  76. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  77. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  78. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  79. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  80. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  81. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  82. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  83. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  84. package/dist/packem_shared/discoverSchema-BnWHHJ4T.mjs +0 -822
  85. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  86. package/dist/packem_shared/emitApp-DGmlt5fq.mjs +0 -617
  87. package/dist/packem_shared/formatAdvisories-8NIv1k0I.mjs +0 -69
  88. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  89. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  90. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,2302 @@
1
+ import{agentComponent as dt}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as xn,hashSchemaSnapshot as vn}from"./SCHEMA_SNAPSHOT_VERSION-B1BUjuG5.mjs";import{s as $}from"./paths-C-9fwEgQ.mjs";const ut=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",serverCtxField:{field:`
2
+ /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
3
+ readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",serverCtxField:{field:`
4
+ /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
5
+ readonly browser: import("@lunora/browser").Browser;`,tier:"action"}},{contextProperty:"containers",key:"container",moduleSpecifier:"@lunora/container"},{contextProperty:"flags",key:"flags",moduleSpecifier:"@lunora/flags"},{appMethod:{configKey:"sql",doc:"Wire the Hyperdrive SQL client backing `ctx.sql` — build it with `createHyperdrive` + `fromPostgresJs`/`fromNodePg`/`fromMysql2`.",method:"hyperdrive"},contextProperty:"sql",key:"hyperdrive",moduleSpecifier:"@lunora/hyperdrive",serverCtxField:{field:`
6
+ /**
7
+ * External database access via Hyperdrive. Non-deterministic — available only in actions. Writes here are NOT tracked by Lunora live queries; subscriptions will not re-run on external DB changes.
8
+ */
9
+ readonly sql: import("@lunora/hyperdrive").SqlClient;`,tier:"action"}},{appMethod:{configKey:"images",doc:"Override the Images binding backing `ctx.images` (defaults to `env.IMAGES`).",method:"images"},contextProperty:"images",key:"images",moduleSpecifier:"@lunora/bindings/images",serverCtxField:{field:`
10
+ /** Cloudflare Images transforms (resize/format/optimize). Non-deterministic — available only in actions. */
11
+ readonly images: import("@lunora/bindings/images").Images;`,tier:"action"}},{appMethod:{configKey:"kv",doc:"Override the Workers KV binding backing `ctx.kv` (defaults to `env.KV`).",method:"kv"},contextProperty:"kv",key:"kv",moduleSpecifier:"@lunora/bindings/kv",serverCtxField:{field:`
12
+ readonly kv: import("@lunora/bindings/kv").Kv;`,tier:"every"}},{key:"mail",moduleSpecifier:"@lunora/mail"},{contextProperty:"notify",key:"notify",moduleSpecifier:"@lunora/notify"},{appMethod:{configKey:"payment",doc:"Wire the payment options backing `ctx.payments`.",method:"payment"},contextProperty:"payments",key:"payments",moduleSpecifier:"@lunora/payment"},{appMethod:{configKey:"x402",doc:"Wire the x402 agent-wallet pay rail backing `ctx.x402` — a payment-enabled `fetch` that answers `402` challenges under a mandatory spend policy (ActionCtx-only; spends real funds).",method:"x402"},contextProperty:"x402",key:"x402",moduleSpecifier:"@lunora/x402/pay"},{contextProperty:"pipelines",key:"pipelines",moduleSpecifier:"@lunora/bindings/pipelines",serverCtxField:{field:`
13
+ /** Pipelines ingestion sink (durable, R2-backed). Fire-and-forget and batched; do not read it back in-handler. */
14
+ readonly pipelines: import("@lunora/bindings/pipelines").PipelineClient;`,tier:"action"}},{appMethod:{configKey:"r2sql",doc:"Wire the R2 SQL client backing `ctx.r2sql` — build it with `createR2Sql({ accountId, apiToken, bucket })` (defaults to env `R2_SQL_TOKEN` / `R2_SQL_ACCOUNT_ID` / `R2_SQL_BUCKET`).",method:"r2sql"},contextProperty:"r2sql",key:"r2sql",moduleSpecifier:"@lunora/bindings/r2sql",serverCtxField:{field:`
15
+ /**
16
+ * R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
17
+ */
18
+ readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],Rn=ut,Sn=new Map(Rn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),eo=ut.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),pt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,$n=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),ht=e=>e.column!==void 0,Nn=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
19
+ `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
20
+ `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
21
+ `;case"null":return`if (${t} !== null) return DEFER;
22
+ `;default:return`if (typeof ${t} !== "string") return DEFER;
23
+ `}},Tn=(e,t)=>e.stringMaxLength===void 0?"":`if (${t}.length > ${String(e.stringMaxLength)}) return DEFER;
24
+ `,An=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!pt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
25
+ `}},Ge=(e,t,n)=>{if(!ht(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if($n.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Nn(e.kind,t)+Tn(e,t)};switch(e.kind){case"array":return On(e,t,n);case"literal":return An(e,t);case"object":return Ln(e,t,n);default:return}}},On=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),s=`__arr${String(o)}`,i=`__i${String(o)}`,a=`__e${String(o)}`,c=Ge(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
26
+ const ${s} = new Array(${t}.length);
27
+ for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
28
+ const ${a} = ${t}[${i}];
29
+ ${c.pre}${s}[${i}] = ${c.out};
30
+ }
31
+ `;return{out:s,pre:d}},In=(e,t,n,r)=>{const o=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||ht(t))return;const{inner:i}=t;if(!i)return;const a=Ge(i,n,r);if(!a)return;const c=r.next(),d=`__has${String(c)}`,p=`__val${String(c)}`,m=`let ${d} = false;
32
+ let ${p};
33
+ if (${n} !== undefined) {
34
+ ${a.pre}${p} = ${a.out};
35
+ ${d} = true;
36
+ }
37
+ `;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:m}}const s=Ge(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},Cn=new Set(Object.getOwnPropertyNames(Object.prototype)),mt=(e,t,n)=>{let r="";const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)return;const a=JSON.stringify(s);let c=`${t}[${a}]`;if(Cn.has(s)){const p=`__f${String(n.next())}`;r+=`const ${p} = Object.hasOwn(${t}, ${a}) ? ${t}[${a}] : undefined;
38
+ `,c=p}const d=In(s,i,c,n);if(!d)return;r+=d.pre,o.push(d.entry)}return{entries:o.join(", "),pre:r}},gt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
39
+ `},Ln=(e,t,n)=>{const r=e.shape??{},o=mt(r,t,n);if(!o)return;const s=n.next(),i=`__obj${String(s)}`,a=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
40
+ ${gt(t)}${o.pre}const ${i} = { ${o.entries} };
41
+ `;return{out:i,pre:a}},_n=e=>{let t=0;const r=mt(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
42
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
43
+ ${gt("source")}${r.pre}return { ${r.entries} };
44
+ }`},S=`// GENERATED by @lunora/codegen — do not edit.
45
+ // Run \`lunora codegen\` to regenerate.
46
+
47
+ `,ae=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},ft=/^[A-Za-z_$][\w$]*$/u,En=/^[\w./-]+$/u,b=(e,t)=>{if(!ft.test(e))throw new Z("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},He=e=>e.charAt(0).toUpperCase()+e.slice(1),j=e=>ft.test(e)?e:JSON.stringify(e),X=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:j(e),Dn={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},Pn=e=>{if(e===void 0)return"unknown";if(!pt.test(e))throw new Z("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},A=e=>{const t=Dn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?A(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return b(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Pn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>bt(r,o)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?A(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?A(e.keyType):"string",r=e.valueType?A(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>A(n)).join(" | "):"never";default:return"unknown"}},bt=(e,t)=>{const n=j(e);if(t.kind==="optional"){const r=t.inner?A(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${A(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>bt(n,r)).join("; ")} }`},yt=e=>e.kind==="optional"||!!e.column?.hasDefault,se=e=>e.kind==="optional"&&e.inner?e.inner:e,Fn=e=>{b(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=se(o),i=A(s),a=j(r);return yt(o)?` ${a}?: ${i};`:` ${a}: ${i};`}).join(`
48
+ `),n=t?`
49
+ ${t}
50
+ `:"";return`export interface Insert_${e.name} {
51
+ _id?: Id<"${e.name}">;
52
+ _creationTime?: number;${n}}`},Je="schema",to=e=>{for(const u of e.tables)b(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,k])=>{const N=j(x);if(k.kind==="optional"){const T=k.inner?A(k.inner):"unknown";return` ${N}?: ${T};`}return` ${N}: ${A(k)};`}).join(`
53
+ `),y=l?`
54
+ ${l}
55
+ `:"",R=u.commitOrdered===!0?`
56
+ _commitSeq: number;`:"";return`export interface Doc_${u.name} {
57
+ _id: Id<"${u.name}">;
58
+ _creationTime: number;${R}${y}}`}).join(`
59
+
60
+ `),o=e.tables.map(u=>` ${u.name}: Doc_${u.name};`).join(`
61
+ `),s=e.tables.map(u=>{const l=u.indexes.map(y=>JSON.stringify(y.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
62
+ `),i=e.tables.map(u=>{const l=u.searchIndexes.map(y=>JSON.stringify(y.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
63
+ `),a=e.tables.map(u=>{const l=u.rankIndexes.map(y=>JSON.stringify(y.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
64
+ `),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(y=>JSON.stringify(y.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
65
+ `),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>Fn(u)).join(`
66
+
67
+ `),m=e.tables.map(u=>` ${u.name}: Insert_${u.name};`).join(`
68
+ `),w=e.tables.map(u=>{const l=u.relations.map(y=>(b(y.table,"relation target table"),` ${j(y.name)}: ${y.kind==="one"?"OneRelation":"ManyRelation"}<"${y.table}">;`)).join(`
69
+ `);return l?` ${u.name}: {
70
+ ${l}
71
+ };`:` ${u.name}: {};`}).join(`
72
+ `);return _(`${S}export type TableName = ${t};
73
+
74
+ /**
75
+ * The tables **this app declared** — every {@link TableName} except those an add-on
76
+ * contributed through \`defineSchema(...).extend(...)\`.
77
+ *
78
+ * An add-on's tables are real tables and stay in \`TableName\` (they are queryable,
79
+ * they appear in \`DataModel\`), but an app enumerating "my tables" should not have to
80
+ * know they exist: an account-deletion sweep, an export, a migration allowlist, or a
81
+ * helper generic over a table union is about the app's own data, and every add-on
82
+ * added or removed would otherwise silently change the correct answer.
83
+ *
84
+ * \`\`\`ts
85
+ * // Doesn't need to mention \`ratelimit_buckets\`, and won't drift when an add-on lands.
86
+ * const EXPORTED: readonly AppTableName[] = ["nodes", "tagColors"];
87
+ * \`\`\`
88
+ */
89
+ export type AppTableName = ${n};
90
+
91
+ export type Id<TName extends string> = string & { readonly __table: TName };
92
+
93
+ ${r}
94
+
95
+ export interface DataModel {
96
+ ${o}
97
+ }
98
+
99
+ export type Doc<T extends keyof DataModel> = DataModel[T];
100
+
101
+ /**
102
+ * Per-table index name union. \`never\` for tables without secondary indexes.
103
+ * Used by \`TableReader.withIndex()\` to constrain callers to declared names.
104
+ */
105
+ export interface IndexNamesByTable {
106
+ ${s}
107
+ }
108
+
109
+ export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
110
+
111
+ /** Per-table search-index name union. \`never\` for tables without searchIndex. */
112
+ export interface SearchIndexNamesByTable {
113
+ ${i}
114
+ }
115
+
116
+ export type SearchIndexName<T extends keyof DataModel> = SearchIndexNamesByTable[T];
117
+
118
+ /** Per-table rank-index name union. \`never\` for tables without a rankIndex. */
119
+ export interface RankIndexNamesByTable {
120
+ ${a}
121
+ }
122
+
123
+ export type RankIndexName<T extends keyof DataModel> = RankIndexNamesByTable[T];
124
+
125
+ /** Per-table geo-index name union. \`never\` for tables without a geoIndex. */
126
+ export interface GeoIndexNamesByTable {
127
+ ${c}
128
+ }
129
+
130
+ export type GeoIndexName<T extends keyof DataModel> = GeoIndexNamesByTable[T];
131
+
132
+ /** Union of declared vector index names. \`never\` when none are declared. */
133
+ export type VectorIndexName = ${d};
134
+
135
+ ${p}
136
+
137
+ /** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
138
+ export interface InsertModel {
139
+ ${m}
140
+ }
141
+
142
+ export type Insert<T extends keyof DataModel> = InsertModel[T];
143
+
144
+ /**
145
+ * Phantom relation descriptors. They carry the relation kind and target table
146
+ * as type parameters only — there is no runtime value — so the \`with\` argument
147
+ * and its return type can be inferred from {@link Relations}.
148
+ */
149
+ export interface OneRelation<Target extends keyof DataModel> {
150
+ readonly __relationKind: "one";
151
+ readonly __target: Target;
152
+ }
153
+
154
+ export interface ManyRelation<Target extends keyof DataModel> {
155
+ readonly __relationKind: "many";
156
+ readonly __target: Target;
157
+ }
158
+
159
+ /** Per-table relation map keyed by accessor name. \`{}\` for tables with none. */
160
+ export interface Relations {
161
+ ${w}
162
+ }
163
+
164
+ `,Je)},Mn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,wt=/^(?:\.\.?\/)*_generated\//u,kt=/\.[A-Za-z]\w*$/u,Bn=e=>e.replaceAll(Mn,(t,n)=>{const r=n.replace(wt,"./");return`import("${kt.test(r)?r:`${r}.js`}")`}),jn=/import\("(?<spec>[^"]+)"\)/gu,it="node_modules/",qn=/^@types\//u,Wn=e=>e.replaceAll(jn,(t,n)=>{const r=n.lastIndexOf(it);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+it.length);return o===""||qn.test(o)?t:`import("${o}")`}),Un=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Kn=/^(?:\.\.?\/)+/u,Qn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Vn=(e,t)=>e.replaceAll(Un,(n,r)=>{if(wt.test(r.replace(Kn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Qn(`${o}/${r}`)}`;return`import("${kt.test(i)?i:`${i}.js`}")`}),_=(e,t)=>Bn(Vn(Wn(e),t)),Hn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Gn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Hn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Jn={flags:new Set(["/web"]),platform:new Set},xt=(e,t)=>t?e.replaceAll(Gn,(n,r,o)=>{const s=Jn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),vt=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:A(e.output),Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},lt=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=_(xe(s.args),s.filePath),a=_(vt(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
165
+ `);return` ${j($(n))}: {
166
+ ${o}
167
+ };`};return Ye(e).map(n=>t(n)).join(`
168
+ `)},zn=(e,t)=>{if(e.length===0&&t.length===0)return{block:"",importLine:""};const n=[];let r="";if(e.length>0&&(r+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),r+=`
169
+ /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
170
+ export interface WorkflowReference<Params = Record<string, unknown>> {
171
+ readonly isLunoraWorkflow: true;
172
+ readonly __params?: Params;
173
+ readonly binding: string;
174
+ readonly name: string;
175
+ }
176
+ `,e.length>0){const o=[...e].toSorted((a,c)=>a.exportName.localeCompare(c.exportName)),s=o.map(a=>` ${a.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${a.exportName}>>;`).join(`
177
+ `),i=o.map(a=>` ${X(a.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.exportName)} },`).join(`
178
+ `);r+=`
179
+ /** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
180
+ export interface WorkflowsRef {
181
+ ${s}
182
+ }
183
+
184
+ export const workflows: WorkflowsRef = {
185
+ ${i}
186
+ };
187
+ `,n.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
188
+ `)}if(t.length>0){const o=[...t].toSorted((a,c)=>a.exportName.localeCompare(c.exportName)),s=o.map(a=>` ${a.exportName}: WorkflowReference<AgentRunInput>;`).join(`
189
+ `),i=o.map(a=>` ${X(a.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(a.bindingName)}, name: ${JSON.stringify(a.name)} },`).join(`
190
+ `);r+=`
191
+ /** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
192
+ export interface AgentsRef {
193
+ ${s}
194
+ }
195
+
196
+ export const agents: AgentsRef = {
197
+ ${i}
198
+ };
199
+ `,n.push(`import type { AgentRunInput } from "@lunora/agent";
200
+ `)}return{block:r,importLine:n.join("")}},Yn=()=>Object.keys(dt().functions).toSorted((e,t)=>e.localeCompare(t)),Rt=e=>new Set(e.filter(t=>$(t.filePath)==="agents").map(t=>t.exportName)),Xn=()=>new Set(Object.entries(dt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Zn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Rt(t),o=Xn(),s=t.find(a=>$(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new Z("INTERNAL",`@lunora/codegen: "agents:${s.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${s.exportName}" export in ${s.filePath}`);const i=Yn().filter(a=>!r.has(a));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
201
+ `,lines:i.map(a=>` "agents:${a}": lunoraAgentRuntimeFunctions.${a} as unknown as RegisteredLunoraFunction,`).join(`
202
+ `),prelude:`
203
+ /**
204
+ * The \`@lunora/agent\` runtime component — auto-registered because \`lunora/agents.ts\`
205
+ * declares agents. The durable loop dispatches the internal mutations; clients
206
+ * subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
207
+ */
208
+ const lunoraAgentRuntimeFunctions = agentComponent().functions;
209
+ `}},er=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>$(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new Z("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
210
+ `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},tr=(e,t)=>{if(e.length===0)return[];const n=Rt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},nr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>$(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},rr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=_(d.chunkType??"unknown",d.filePath),m=_(xe(d.searchParams),d.filePath),w=_(xe(d.params),d.filePath);return` ${j(d.exportName)}: HttpStreamRef<${p}, ${m}, ${w}>;`}).join(`
211
+ `);return` ${j($(i))}: {
212
+ ${c}
213
+ };`}).join(`
214
+ `),o=n.map(([i,a])=>{const c=a.map(d=>` ${X(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
215
+ `);return` ${X($(i))}: {
216
+ ${c}
217
+ },`}).join(`
218
+ `);return{block:`
219
+ /** This project's HTTP-SSE stream routes (\`httpRoute.<verb>(path).stream()\`), addressable as typed references for \`client.httpStream\` / \`useHttpStream\`. */
220
+ export interface HttpStreamsRef {
221
+ ${r}
222
+ }
223
+
224
+ export const httpStreams: HttpStreamsRef = {
225
+ ${o}
226
+ };
227
+ `,body:r}},no=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:s=!1,workflows:i=[]}=e,a=ae(s),c=[...n.filter(C=>C.visibility!=="internal"),...tr(t,n),...nr(o,n)],d=n.filter(C=>C.visibility==="internal"),p=lt(c),m=lt(d),w=rr(r),u=`${p}
228
+ ${m}
229
+ ${w.body}`,l=ze(u),y=l.length>0?`
230
+ import type { ${l.join(", ")} } from "./dataModel.js";
231
+ `:"",R=p?`
232
+ ${p}
233
+ `:"",x=m?`
234
+ ${m}
235
+ `:"",k=zn(i,t),N=`export interface ApiTypes {${R}}
236
+
237
+ export const api = anyApi as unknown as ApiTypes;
238
+
239
+ /** Internal functions — callable only server-side via \`ctx.run*\`, never from a client. */
240
+ export interface InternalApiTypes {${x}}
241
+
242
+ export const internal = anyApi as unknown as InternalApiTypes;
243
+ ${k.block}${w.block}`,T=[...N.includes("FunctionReference<")?["FunctionReference"]:[],...w.block===""?[]:["HttpStreamRef"]],D=T.length>0?`import type { ${T.join(", ")} } from "${a.client}";
244
+ `:"";return xt(`${S}import { anyApi } from "${a.client}";
245
+ ${D}${k.importLine}${y}
246
+ ${N}`,s)},ro=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
247
+ import type { SeedClient, SeedClientOptions } from "@lunora/seed";
248
+
249
+ import schema from "../schema.js";
250
+ import type { InsertModel } from "./dataModel.js";
251
+
252
+ /**
253
+ * Schema-aware seed client with this project's \`InsertModel\` and runtime schema
254
+ * pre-bound. Each table is a method; call it with a count, a range, explicit
255
+ * partial rows, or per-field overrides. Foreign keys connect to rows seeded
256
+ * earlier in the run, and FK-parent tables are seeded automatically.
257
+ * @example
258
+ * const seed = createSeedClient({ seed: 1 });
259
+ * const { users } = await seed.users(5);
260
+ * const { posts } = await seed.posts((x) => x([10, 20]));
261
+ */
262
+ export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
263
+ `:"",oo=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=ae(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,s=e.map(c=>{b(c.exportName,"shape export name");const d=o(c),p=_(xe(c.args),c.filePath),m=Object.keys(c.args).length>0,w=m?` args: ${p};`:` args?: ${p};`,u=m?`(args: ${p}) => void`:`(args?: ${p}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
264
+ export interface ${He(l)} {
265
+ ${w}
266
+ /**
267
+ * Share the optimistic-overlay gate with other collections + mutators on this
268
+ * shard. Defaults to the shared per-shard registry, which is almost always what
269
+ * you want — pass one only to isolate this collection's gate.
270
+ */
271
+ checkpoints?: CheckpointRegistry;
272
+ /** The Lunora client to subscribe through. */
273
+ client: LunoraClient;
274
+ /** Row key extractor — defaults to \`row._id\`. Override when the app keys rows by a natural column. */
275
+ getKey?: (row: ${d}) => string;
276
+ /** \`"eager"\` starts syncing at creation; \`"lazy"\` (default) on the first subscriber. */
277
+ load?: "eager" | "lazy";
278
+ /** Notified when the underlying subscription errors; the collection always leaves \`loading\`. */
279
+ onError?: (error: SubscriptionError) => void;
280
+ /** Routes the subscription to a shard's DO. **Required for a \`.shardBy()\` table** — without it the watermark lands in the default bucket. */
281
+ shardKey?: string;
282
+ }
283
+
284
+ /**
285
+ * Collection options for the \`${c.exportName}\` replication shape: \`config\` for
286
+ * \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
287
+ * \`scope\` to re-point the subscription.
288
+ */
289
+ export const ${c.exportName}CollectionOptions = (options: ${He(l)}): LunoraCollectionOptions<${d}> =>
290
+ lunoraCollectionOptions<${d}>({
291
+ client: options.client,
292
+ ...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
293
+ ...(options.getKey === undefined ? {} : { getKey: options.getKey }),
294
+ ...(options.load === undefined ? {} : { load: options.load }),
295
+ ...(options.onError === undefined ? {} : { onError: options.onError }),
296
+ ...(options.shardKey === undefined ? {} : { shardKey: options.shardKey }),
297
+ shape: { args: options.args, name: ${JSON.stringify(c.exportName)}, ...(options.shardKey === undefined ? {} : { shardKey: options.shardKey }) },
298
+ });
299
+
300
+ /** Live collection for the \`${c.exportName}\` shape, with its sync controls. */
301
+ export const ${c.exportName}Collection = (
302
+ options: ${He(l)},
303
+ ): { checkpoints: CheckpointRegistry; collection: Collection<${d}, string>; scope: ${u} } => {
304
+ const { checkpoints, config, scope } = ${c.exportName}CollectionOptions(options);
305
+
306
+ return { checkpoints, collection: createCollection(config), scope };
307
+ };`}).join(`
308
+
309
+ `),i=ze(s),a=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
310
+ `:"";return`${S}import type { LunoraClient, SubscriptionError } from "${r.client}";
311
+ import { lunoraCollectionOptions } from "@lunora/db/collections";
312
+ import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
313
+ import type { Collection } from "@tanstack/db";
314
+ import { createCollection } from "@tanstack/db";
315
+ ${a}
316
+ ${s}
317
+ `},or=(e,t)=>`lunora_${$(e)}_${String(t)}`,ar=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
318
+ const registered = LUNORA_FUNCTIONS[functionPath];
319
+
320
+ if (!registered) {
321
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
322
+ }
323
+
324
+ return (await registered.handler(context, args ?? {})) as R;
325
+ };`,sr=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,or(l,o.size))};for(const l of e)s(l.filePath);for(const l of t)s(l.filePath);for(const l of n)s(l.filePath);for(const l of r)s(l.filePath);const i=[...o.entries()].map(([l,y])=>{if(!En.test(l))throw new Z("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${y} from "../${l}.js";`}).join(`
326
+ `),a=e.map(l=>` "${$(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
327
+ `),c=t.map(l=>` ${JSON.stringify(l.id)}: ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
328
+ `),d=n.map(l=>` "${$(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
329
+ `),p=r.map(l=>` "${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
330
+ `),m=n.map(l=>`${$(l.filePath)}:${l.exportName}`),w=[a,d].filter(l=>l.length>0).join(`
331
+ `),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const y=_n(l.args);return y===void 0?void 0:`installCompiledValidatorMap(${o.get(l.filePath)??""}.${l.exportName}.args, ${y});`}).filter(l=>l!==void 0).join(`
332
+ `);return{dispatchBody:w.length>0?`
333
+ ${w}
334
+ `:"",importBlock:i.length>0?`${i}
335
+
336
+ `:"",installBlock:u,migrationBody:c.length>0?`
337
+ ${c}
338
+ `:"",mutatorPaths:m,shapeBody:p.length>0?`
339
+ ${p}
340
+ `:""}},ir=e=>{const t=Ye(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=_(xe(a.args),a.filePath),d=c==="{}"?"?":"",p=_(vt(a),a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
341
+ `);return` ${j($(o))}: {
342
+ ${i}
343
+ };`}).join(`
344
+ `);return{implementation:t.map(([o,s])=>{const i=$(o),a=s.map(c=>` ${X(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
345
+ `);return` ${X(i)}: {
346
+ ${a}
347
+ },`}).join(`
348
+ `),types:n}},lr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=se(o);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&n.add(s.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},ao=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:o=!1,hasAnalytics:s=!1,hasBrowser:i=!1,hasVectors:a=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:p=!1,hasKv:m=!1,hasNotify:w=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:y=!1,hasX402:R=!1,identity:x,queues:k=[],schema:N,storageRuleBuckets:T=[],useUmbrella:D=!1,workflows:C=[]}={})=>{const f=ae(D),P=lr(N??{tables:[]},T).map(h=>JSON.stringify(h)).join(" | "),ie=o?`import type { LunoraAi } from "@lunora/ai";
349
+ `:"",F=o?`
350
+ readonly ai: LunoraAi;`:"",le=u?`import type { LunoraPayment } from "@lunora/payment";
351
+ `:"",ce=u?`
352
+ readonly payments: LunoraPayment;`:"",q=R?`import type { X402Pay } from "@lunora/x402/pay";
353
+ `:"",I=R?`
354
+ readonly x402: X402Pay;`:"",ee=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
355
+ `:"",L=t.length>0?`
356
+ readonly containers: {${t.map(h=>`
357
+ readonly ${h.exportName}: ContainerAccessor;`).join("")}
358
+ };`:"",v=[...o?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(h=>(b(h.bindingName,`container binding "${h.bindingName}"`),` /** Durable Object namespace for the \`${h.exportName}\` container. */
359
+ readonly ${h.bindingName}?: unknown;`)),...C.map(h=>(b(h.bindingName,`workflow binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` workflow. */
360
+ readonly ${h.bindingName}?: unknown;`)),...k.map(h=>(b(h.bindingName,`queue binding "${h.bindingName}"`),` /** Queue producer binding for the \`${h.exportName}\` queue. */
361
+ readonly ${h.bindingName}?: unknown;`)),...e.map(h=>(b(h.bindingName,`agent binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` agent. */
362
+ readonly ${h.bindingName}?: unknown;`))].join(`
363
+ `),Ae=`
364
+
365
+ /**
366
+ * This project's Cloudflare bindings, as far as codegen can discover them from
367
+ * \`lunora/\` source — the container/workflow Durable Object namespaces and the
368
+ * conventional Workers AI binding. Bindings the config layer reconciles from
369
+ * user-named wrangler config (R2/KV/D1/\`services\`/queues/…) aren't statically
370
+ * visible here, so the open index signature keeps them reachable (cast at the
371
+ * use site). Service bindings (\`env.<SERVICE>.fetch(...)\` / RPC stubs) live
372
+ * under this signature too — Lunora can't type a third-party worker's RPC
373
+ * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
374
+ */
375
+ export interface CloudflareBindings {
376
+ readonly [binding: string]: unknown;${v?`
377
+ ${v}`:""}
378
+ }
379
+
380
+ /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
381
+ export type Env = CloudflareBindings;`,M=(h,We,Ne)=>{const re=Sn.get(h);if(re!==void 0&&re.tier!==Ne)throw new Z("INTERNAL",`@lunora/codegen: capability "${h}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Ne}" context — update whichever is wrong.`);return We?re?.field??"":""},de=M("kv",m,"every"),ue=M("analytics",s,"every"),Oe=M("hyperdrive",d,"action"),Ie=M("browser",i,"action"),pe=M("images",p,"action"),V=M("pipelines",l,"action"),H=M("r2sql",y,"action"),W=a&&(N?.vectorIndexes.length??0)>0,G=W?' | "vectors"':"",te=W?`
382
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",J=W?`
383
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",ne=W?`import type { VectorSearch, VectorSearchReader } from "${f.server}";
384
+ import type { VectorIndexName } from "./dataModel.js";
385
+ `:"",U=r?`
386
+ /** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
387
+ readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",K=c?`
388
+ /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
389
+ readonly flags: import("${f.flags}").LunoraFlags;`:"",Q=w?`
390
+ /** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
391
+ readonly notify: import("@lunora/notify").LunoraNotify;
392
+ /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
393
+ readonly push: import("@lunora/notify").LunoraPush;`:"",B=C.length>0,Ce=B?`import type { WorkflowHandle } from "@lunora/workflow";
394
+ import type * as lunoraWorkflowDefinitions from "../workflows.js";
395
+ `:"",Le=B?`
396
+
397
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
398
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
399
+ ? unknown extends Params
400
+ ? Record<string, unknown>
401
+ : NonNullable<Params>
402
+ : Record<string, unknown>;
403
+
404
+ /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
405
+ export interface LunoraWorkflows {
406
+ ${C.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
407
+ `)}
408
+ }`:"",ve=B?' | "workflows"':"",Re=B?`
409
+ readonly workflows: LunoraWorkflows;`:"",he=k.length>0,_e=he?`import type { QueueProducer } from "@lunora/queue";
410
+ import type * as lunoraQueueDefinitions from "../queues.js";
411
+ `:"",Ee=he?`
412
+
413
+ /** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
414
+ type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
415
+
416
+ /** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
417
+ export interface LunoraQueues {
418
+ ${k.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${h.exportName}>>;`).join(`
419
+ `)}
420
+ }`:"",Se=he?`
421
+ readonly queues: LunoraQueues;`:"",me=e.length>0,De=me?`import type { AgentHandle } from "@lunora/agent";
422
+ `:"",Pe=me?`
423
+
424
+ /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
425
+ export interface LunoraAgents {
426
+ ${e.map(h=>(b(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
427
+ `)}
428
+ }`:"",$e=me?`
429
+ readonly agents: LunoraAgents;`:"",Fe=x?`import type { InferIdentity } from "${f.server}";
430
+ import type * as lunoraIdentityContract from "../identity.js";
431
+ `:"",Me=x?`
432
+
433
+ /** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
434
+ export type Identity = InferIdentity<typeof lunoraIdentityContract.${x.exportName}>;
435
+
436
+ /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
437
+ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",ge=x?' | "auth"':"",fe=x?`
438
+ readonly auth: NarrowedAuth;`:"",Be=x?", Identity":"",je=n?`import type * as lunoraEnvContract from "../env.js";
439
+ `:"",qe=n?`
440
+
441
+ /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
442
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",be=n?' | "env"':"",ye=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${S}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${f.server}";
443
+ import type {
444
+ ActionBuilder,
445
+ ActionCtx as ActionCtxBase,
446
+ ColumnValidator,
447
+ DatabaseReader,
448
+ DatabaseWriter,
449
+ EmptyArgs,
450
+ InternalActionBuilder,
451
+ InternalMutationBuilder,
452
+ InternalQueryBuilder,
453
+ MutationBuilder,
454
+ MutationCtx as MutationCtxBase,
455
+ MutationStorage,
456
+ MutatorDefinition,
457
+ QueryBuilder,
458
+ QueryCtx as QueryCtxBase,
459
+ ReadOnlyStorage,
460
+ RegisteredMutator,
461
+ Storage as StorageBase,
462
+ TableReader,
463
+ Validator,
464
+ } from "${f.server}";
465
+
466
+ import type {
467
+ DatabaseReaderFacade as DatabaseReaderFacadeOf,
468
+ DatabaseWriterFacade as DatabaseWriterFacadeOf,
469
+ LoadWith as LoadWithOf,
470
+ TableReaderFacade as TableReaderFacadeOf,
471
+ TableWriterFacade as TableWriterFacadeOf,
472
+ WithArg as WithArgOf,
473
+ } from "${f.serverDataModel}";
474
+
475
+ export type {
476
+ AggregateOp,
477
+ GroupByEntry,
478
+ OrderBy,
479
+ QueryArgs,
480
+ QueryPage,
481
+ RankPage,
482
+ RankResult,
483
+ RestrictableQueryOptions,
484
+ RestrictableQueryOptionsOf,
485
+ SearchFilterBuilder,
486
+ SearchReader,
487
+ TableAggregateOptions,
488
+ TableAggregateOptionsOf,
489
+ TableGroupByOptions,
490
+ TableGroupByOptionsOf,
491
+ TableRankOptions,
492
+ TableRankPageOptions,
493
+ Where,
494
+ WhereOf,
495
+ WhereOperators,
496
+ } from "${f.serverDataModel}";
497
+
498
+ import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
499
+ ${ne}${ie}${le}${q}${ee}${Ce}${_e}${De}${Fe}${je}
500
+ export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
501
+
502
+ /**
503
+ * The query-DSL bindings: \`@lunora/server/data-model\`'s generics parameterized
504
+ * over this project's \`DataModel\` / \`InsertModel\` / \`Relations\` / index maps.
505
+ *
506
+ * They live here rather than in \`dataModel.ts\` because they are the half that
507
+ * needs the SERVER package. Keeping \`dataModel.ts\` free of it lets a sibling
508
+ * package — a web app, another Worker — compile \`api.ts\` for its \`Doc\`/\`Id\`
509
+ * types without installing a server dependency to do it.
510
+ */
511
+
512
+ /** The \`with\` argument for table \`T\` — see \`@lunora/server/data-model\`. */
513
+ export type WithArg<T extends keyof DataModel> = WithArgOf<DataModel, Relations, T>;
514
+
515
+ /** \`Doc<T>\` narrowed to exactly the relations requested in the with-arg \`W\`. */
516
+ export type LoadWith<T extends keyof DataModel, W> = LoadWithOf<DataModel, Relations, T, W>;
517
+
518
+ /** Read-only typed table accessor exposed on \`QueryCtx.db.<table>\`. */
519
+ export type TableReaderFacade<T extends keyof DataModel> = TableReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
520
+
521
+ /** Read-write typed table accessor exposed on \`MutationCtx.db.<table>\` / \`ActionCtx.db.<table>\`. */
522
+ export type TableWriterFacade<T extends keyof DataModel> = TableWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
523
+
524
+ /** Per-table read facade — \`ctx.db.<table>\` on a \`QueryCtx\`. */
525
+ export type DatabaseReaderFacade = DatabaseReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
526
+
527
+ /** Per-table read-write facade — \`ctx.db.<table>\` on a \`MutationCtx\` / \`ActionCtx\`. */
528
+ export type DatabaseWriterFacade = DatabaseWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
529
+
530
+ /** Insert builder returned by \`ctx.orm.insert(table)\`. */
531
+ export interface OrmInsertBuilder<T extends keyof DataModel> {
532
+ values: (values: Insert<T>) => Promise<IdOfTable<T>>;
533
+ }
534
+
535
+ /** Replace builder returned by \`ctx.orm.replace(table, id)\` — swaps the whole document. */
536
+ export interface OrmReplaceBuilder<T extends keyof DataModel> {
537
+ with: (values: Insert<T>) => Promise<void>;
538
+ }
539
+
540
+ /** Update builder returned by \`ctx.orm.update(table, id)\` — patches the named fields. */
541
+ export interface OrmUpdateBuilder<T extends keyof DataModel> {
542
+ set: (values: Partial<Insert<T>>) => Promise<void>;
543
+ }
544
+
545
+ /** Read-only ORM surface — \`ctx.orm\` on a \`QueryCtx\`. Mirrors \`ctx.db\` reads under a kitcn-style \`query\` namespace. */
546
+ export interface OrmReader {
547
+ query: DatabaseReaderFacade;
548
+ }
549
+
550
+ /** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
551
+ export interface OrmWriter extends OrmReader {
552
+ delete: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => Promise<void>;
553
+ insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
554
+ replace: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmReplaceBuilder<T>;
555
+ update: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmUpdateBuilder<T>;
556
+ }
557
+
558
+ /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
559
+ export type StorageBucketName = ${P};${Ae}${Le}${Ee}${Pe}${Me}${qe}
560
+
561
+ /**
562
+ * Project-typed contexts. The base contexts from \`@lunora/server\` are
563
+ * untyped against the schema; here \`db\` is widened to the generated per-table
564
+ * facade (\`ctx.db.<table>.findMany(...)\`) while keeping the legacy structural
565
+ * \`db.get\`/\`db.query\` surface for back-compat, and \`storage\` is narrowed so
566
+ * \`ctx.storage.bucket(name)\` autocompletes the declared buckets.
567
+ */
568
+ /**
569
+ * The Convex-style fluent reader \`ctx.db.query(table)\`, bound to this schema:
570
+ * a table-name literal narrows the row type, so \`.collect()\` / \`.first()\` /
571
+ * \`.take()\` (and the \`.withIndex()\` / \`.filter()\` / \`.order()\` chain) resolve
572
+ * as \`Doc<table>\` with no \`as unknown as Doc<...>\` casts. The per-table accessor
573
+ * \`ctx.db.<table>\` stays available alongside it via the facade.
574
+ *
575
+ * Intersected with the wide \`(string) => TableReader\` signature so the bound
576
+ * \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
577
+ * call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
578
+ *
579
+ * The three index-name unions are what make \`.withIndex("by_TYPO")\` a compile
580
+ * error: each resolves to the table's declared names, or \`never\` when it
581
+ * declares none of that kind. Without them a renamed or dropped index left
582
+ * every call site typechecking, and the query either threw at runtime or
583
+ * degraded silently to a full table scan.
584
+ */
585
+ type TypedTableQuery = (<T extends TableName>(
586
+ table: T,
587
+ ) => TableReader<Doc<T>, IndexNamesByTable[T], SearchIndexNamesByTable[T], GeoIndexNamesByTable[T]>) &
588
+ ((table: string) => TableReader);
589
+
590
+ /**
591
+ * The point read \`ctx.db.get(id)\`, bound to this schema: an \`Id<"table">\`
592
+ * carries its table name, so the resolved document is typed \`Doc<table>\` (or
593
+ * \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
594
+ */
595
+ type TypedTableGet = <T extends TableName>(id: IdOfTable<T>) => Promise<Doc<T> | null>;
596
+
597
+ /**
598
+ * Resolves the \`asId\` table argument: a literal in {@link TableName} passes through, a
599
+ * genuinely-wide \`string\` (a computed name) passes through, and any OTHER literal
600
+ * collapses to \`never\` so it fails to typecheck.
601
+ *
602
+ * The \`string extends T\` arm is what distinguishes "the caller passed a computed
603
+ * string" from "the caller passed a misspelled literal" — only the wide \`string\` type
604
+ * is a supertype of \`string\`.
605
+ */
606
+ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ? T : never;
607
+
608
+ /**
609
+ * The id parse boundary \`ctx.db.asId(table, id)\`, bound to this schema: a misspelled
610
+ * table literal is a compile error rather than a call that hands back a confidently-
611
+ * branded id for a table that does not exist. Mirrors {@link TypedTableQuery} /
612
+ * {@link TypedTableGet}.
613
+ *
614
+ * Deliberately NOT an intersection with a wide \`(string, string) => string\` overload:
615
+ * overload resolution would fall through to it for a bad literal, silently restoring
616
+ * the very typo hole this narrowing exists to close. {@link AsIdTable} instead keeps a
617
+ * computed table name working — and keeps \`ctx.db\` structurally assignable to
618
+ * schema-agnostic consumers — without accepting an invalid literal.
619
+ */
620
+ type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
621
+
622
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${G}${ge}${be}> {
623
+ readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
624
+ readonly orm: OrmReader;
625
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${J}${U}${de}${K}${Q}${ue}${ye}${fe}
626
+ }
627
+
628
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${G}${ve}${ge}${be}> {
629
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
630
+ readonly orm: OrmWriter;
631
+ readonly storage: MutationStorage<StorageBucketName>;${te}${U}${de}${K}${Q}${ue}${ye}${Re}${Se}${$e}${fe}
632
+ }
633
+
634
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${G}${ve}${ge}${be}> {
635
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
636
+ readonly orm: OrmWriter;
637
+ readonly storage: StorageBase<StorageBucketName>;${te}${U}${F}${ce}${I}${L}${de}${K}${Q}${Oe}${Ie}${pe}${ue}${V}${H}${ye}${Re}${Se}${$e}${fe}
638
+ }
639
+
640
+ /**
641
+ * Procedure builders bound to this project's typed contexts. Chain
642
+ * \`.input({...})\` to declare args, \`.use(middleware)\` for rate limiting / RLS /
643
+ * masking (each middleware may refine \`ctx\`), then the terminal
644
+ * \`.query()\` / \`.mutation()\` / \`.action()\` with a \`({ ctx, args }) => ...\`
645
+ * handler. \`.output(validator)\` and (queries) \`.stream()\` are also available.
646
+ */
647
+ const lunoraBuilders = initLunora.dataModel<DataModel>().create();
648
+
649
+ /** \`query\` builder bound to this project's typed {@link QueryCtx}. */
650
+ export const query = lunoraBuilders.query as unknown as QueryBuilder<QueryCtx, EmptyArgs>;
651
+
652
+ /** \`mutation\` builder bound to this project's typed {@link MutationCtx}. */
653
+ export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder<MutationCtx, EmptyArgs>;
654
+
655
+ /** \`action\` builder bound to this project's typed {@link ActionCtx}. */
656
+ export const action = lunoraBuilders.action as unknown as ActionBuilder<ActionCtx, EmptyArgs>;
657
+
658
+ /** \`internalQuery\` builder bound to this project's typed {@link QueryCtx} — never exposed on \`api\`. */
659
+ export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder<QueryCtx, EmptyArgs>;
660
+
661
+ /** \`internalMutation\` builder bound to this project's typed {@link MutationCtx} — never exposed on \`api\`. */
662
+ export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder<MutationCtx, EmptyArgs>;
663
+
664
+ /** \`internalAction\` builder bound to this project's typed {@link ActionCtx} — never exposed on \`api\`. */
665
+ export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder<ActionCtx, EmptyArgs>;
666
+
667
+ /**
668
+ * \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
669
+ * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
670
+ * \`${f.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
671
+ * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
672
+ * \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
673
+ * no \`as unknown as\` cast. Runtime-identical to the package export; only the
674
+ * context type narrows, so discovery finds a mutator authored either way.
675
+ * @example
676
+ * export const setText = defineMutator({
677
+ * args: { id: v.id("nodes"), text: v.string() },
678
+ * server: async (ctx, args) => { await ctx.db.patch(args.id, { text: args.text }); },
679
+ * });
680
+ */
681
+ export const defineMutator = defineMutatorBase as unknown as <Args extends Record<string, Validator> = Record<string, Validator>, ClientTx = unknown, R = unknown>(
682
+ definition: MutatorDefinition<Args, MutationCtx, ClientTx, R>,
683
+ ) => RegisteredMutator<Args, MutationCtx, ClientTx, R>;
684
+
685
+ /**
686
+ * \`definePolicy\` bound to THIS schema's {@link DataModel} + {@link Relations}.
687
+ * Import it from here (\`./_generated/server\`) instead of \`@lunora/server\` to get
688
+ * a relation-aware RLS authoring surface: \`table\` autocompletes to a real table
689
+ * name and the \`when\` predicate type-checks against the table's columns **and**
690
+ * its declared relations — \`{ author: { is: {...} } }\`, \`{ posts: { some: {...} } }\`,
691
+ * etc. (the \`@lunora/do\` pre-resolver resolves relation predicates on reads).
692
+ * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
693
+ * so the \`rls()\` chain discovers a policy authored either way the same.
694
+ */
695
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Be}>();
696
+
697
+ /**
698
+ * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
699
+ * table names — so the argument autocompletes and returns a precise
700
+ * \`Id<"table">\`. Identical to \`@lunora/server\`'s \`v\` at runtime; the only
701
+ * difference is the tightened \`id\` type.
702
+ *
703
+ * Import \`v\` from here (\`./_generated/server\`) in your queries/mutations/actions
704
+ * to get table-name autocomplete. \`lunora/schema.ts\` can't use it — it is the
705
+ * file that defines the table names, so they aren't known yet there; pass the
706
+ * names as string literals and the generated \`Id<"table">\` types still catch a
707
+ * typo wherever the id is used.
708
+ */
709
+ export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
710
+ id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
711
+ };
712
+ `},cr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${$(n.filePath)}:${n.exportName}`);return t},so=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=ae(i),{dispatchBody:p,importBlock:m,installBlock:w,migrationBody:u,mutatorPaths:l,shapeBody:y}=sr(n,r,o,s),R=Zn(t,n),x=er(a,n),k=[R.lines,x.lines].filter(v=>v.length>0).join(`
713
+ `);let N=p;k.length>0&&(N=p.length>0?`${p.trimEnd()}
714
+ ${k}
715
+ `:`
716
+ ${k}
717
+ `);const T=cr(n),D=s.length>0?`import type { RegisteredShape } from "${d.server}";
718
+ `:"",C=s.length>0?`
719
+ /**
720
+ * Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
721
+ * The generated ShardDO's \`resolveShape\` override looks a shape up by name and
722
+ * evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
723
+ * \`shape_subscribe\` (reads-as-permissions).
724
+ */
725
+ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${y}};
726
+ `:"",f=l.length>0?`
727
+ /**
728
+ * Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
729
+ * ShardDO's \`isCustomMutator\` override routes through the client-watermark push
730
+ * protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
731
+ */
732
+ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(v=>JSON.stringify(v)).join(", ")}]);
733
+ `:"",P=w.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
734
+ `:"",ie=w.length>0?`
735
+ /**
736
+ * AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
737
+ * onto its function's live \`.args\` object and consulted by the interpreted
738
+ * parser as a zero-allocation fast path; anything it can't model is deferred.
739
+ */
740
+ ${w}
741
+ `:"",F=ir(n),le=F.types?`
742
+ ${F.types}
743
+ `:"",ce=F.implementation?`
744
+ ${F.implementation}
745
+ `:"",q=ze(F.types),I=q.length>0?`import type { ${q.join(", ")} } from "./dataModel.js";
746
+ `:"",ee=c?"context":"_context",L=c?`${ar}
747
+
748
+ `:"";return xt(`${S}${m}${R.importLine}${x.importLine}${P}${D}import { LunoraError } from "${d.server}";
749
+ import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
750
+ ${I}
751
+ /**
752
+ * Single registered function, narrowed to the shape \`handleRpc\` needs.
753
+ * The real argument validators / return types are checked elsewhere — at
754
+ * the dispatch site we erase to \`unknown\` so a single map can host every
755
+ * registered function.
756
+ */
757
+ export interface RegisteredLunoraFunction {
758
+ kind: "action" | "mutation" | "query" | "stream";
759
+ args: Record<string, unknown>;
760
+ /**
761
+ * Present on a \`"stream"\` declared \`durable\`: its run is persisted and
762
+ * survives the socket that opened it. Absent on every other kind, and on an
763
+ * ephemeral stream.
764
+ */
765
+ durable?: { ttlMs?: number };
766
+ /**
767
+ * For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
768
+ * For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
769
+ * \`AbortSignal\` as a third argument — the runtime drives it frame-by-frame.
770
+ */
771
+ handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
772
+ /**
773
+ * The lifecycle moment a hook fires on, when this registration came from
774
+ * \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`. Read at
775
+ * dispatch to decide whether the function runs system-trusted: \`init\` and
776
+ * \`reactor\` have no caller identity, so RLS has no user to scope to.
777
+ */
778
+ lifecycle?: "connect" | "disconnect" | "init" | "reactor";
779
+ /** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
780
+ visibility?: "internal" | "public";
781
+ }
782
+ ${R.prelude}${x.prelude}
783
+ /**
784
+ * Static dispatch table. The key matches the \`__lunoraRef\` the client
785
+ * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
786
+ */
787
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${N}};
788
+ ${ie}${C}${f}
789
+ /**
790
+ * Lifecycle manifest: the function paths the generated ShardDO dispatches when a
791
+ * client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
792
+ * per Durable Object instance before any handler runs (\`init\`), and after a
793
+ * write flush when a watched read's result changed (\`reactor\`). Each path also
794
+ * resolves through {@link LUNORA_FUNCTIONS}. The socket sides run under the
795
+ * socket's verified identity; \`init\` and \`reactor\` have no caller, so they run
796
+ * anonymous — all via system dispatch.
797
+ */
798
+ export const LUNORA_LIFECYCLE_HOOKS: { connect: readonly string[]; disconnect: readonly string[]; init: readonly string[]; reactor: readonly string[] } = {
799
+ connect: [${T.connect.map(v=>JSON.stringify(v)).join(", ")}],
800
+ disconnect: [${T.disconnect.map(v=>JSON.stringify(v)).join(", ")}],
801
+ init: [${T.init.map(v=>JSON.stringify(v)).join(", ")}],
802
+ reactor: [${T.reactor.map(v=>JSON.stringify(v)).join(", ")}],
803
+ };
804
+
805
+ /**
806
+ * Resolve and invoke a registered function from an external caller. Throws a
807
+ * LunoraError-shaped object (404) when the path is unknown — the runtime's
808
+ * structural error mapper turns that into the right HTTP status. Internal
809
+ * functions are treated as not-found so their existence never leaks to clients.
810
+ */
811
+ export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
812
+ const registered = LUNORA_FUNCTIONS[functionPath];
813
+
814
+ if (!registered || registered.visibility === "internal") {
815
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
816
+ }
817
+
818
+ return registered.handler(context, args);
819
+ };
820
+
821
+ /**
822
+ * A handler context accepted by {@link createCaller}. The runtime context the
823
+ * shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
824
+ */
825
+ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
826
+
827
+ /**
828
+ * Typed, in-process server-to-server caller. Every registered function — public
829
+ * *and* internal — is reachable; each call dispatches against the same shard
830
+ * with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
831
+ * \`runAction\` but without re-stating the function path.
832
+ */
833
+ export interface Caller {${le}}
834
+
835
+ ${L}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
836
+ export const createCaller = (${ee}: CallerCtx): Caller => ({${ce}});
837
+
838
+ /**
839
+ * Single registered data migration, narrowed to the shape the per-shard runner
840
+ * consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
841
+ * validation lives in \`defineMigration\`.
842
+ */
843
+ export interface RegisteredDataMigration {
844
+ batchSize?: number;
845
+ down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
846
+ id: string;
847
+ table: string;
848
+ up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
849
+ }
850
+
851
+ /**
852
+ * Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
853
+ * shard DO's admin RPC and the CLI resolve migrations to run through this map.
854
+ */
855
+ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
856
+ `,i)},dr=e=>{const t={};for(const n of e.tables){const r={};for(const[o,s]of Object.entries(n.shape)){const i=se(s);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},ur=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,s]of Object.entries(n.shape))se(s).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},pr=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(o=>({fields:[...o.fields],name:o.name,type:"index",...o.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(o=>({fields:[o.field,...o.filterFields??[]],name:o.name,type:"search"})),...(n.geoIndexes??[]).map(o=>({fields:[o.field],name:o.name,type:"geo"})),...n.rankIndexes.map(o=>({fields:o.sortBy.map(s=>s.field),name:o.name,type:"rank"})),...n.vectorIndexes.map(o=>({fields:o.field===void 0?[]:[o.field],name:o.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},hr=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},mr=e=>{if(e.kind!=="union"||e.members===void 0||e.members.length===0)return;const t=[];for(const n of e.members){if(n.kind!=="literal"||n.literalValue===void 0)return;try{const r=JSON.parse(n.literalValue);if(typeof r!="string")return;t.push(r)}catch{return}}return t},gr=(e,t)=>{const n=se(t),r={name:e,optional:yt(t),type:n.kind};n.kind==="id"&&n.tableName!==void 0&&(r.ref=n.tableName),n.kind==="storage"&&(r.isStorage=!0,n.bucket!==void 0&&(r.bucket=n.bucket));const o=mr(n);return o!==void 0&&(r.enumValues=o),n.column?.notNull===!1&&(r.nullable=!0),r},fr=e=>{const t={};for(const n of e.tables){const r=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...n.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]];for(const[o,s]of Object.entries(n.shape))r.push(gr(o,s));t[n.name]=r}return t},br=e=>e?{importFragment:"serveRelationFanout, ",override:`
857
+ protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
858
+ this.ensureMigrated();
859
+
860
+ const { db } = this.buildCtx({ functionPath }) as { db: DatabaseWriterLike };
861
+
862
+ return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
863
+ }
864
+ `}:{importFragment:"",override:""},yr=e=>{if(!e)return{build:"",configField:"",contextField:"",stub:""};const t='throw new Error("ctx.ai: no AI binding found. Add an \\`ai\\` binding (env.AI) to wrangler.jsonc, or pass \\`ai\\` to createShardDO().");';return{build:`
865
+ const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
866
+ // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
867
+ // function path + trace id into createAi, which folds them into the
868
+ // gateway's native \`metadata\` only when a gateway is configured (absent
869
+ // otherwise). Mirror the tracer's anchor guard — a deferred subscription
870
+ // re-run must not borrow a concurrent dispatch's trace, so read
871
+ // \`getCurrentTrace()\` only on the synchronous (non-threaded-identity) path.
872
+ const aiTrace = options.identity ? undefined : this.getCurrentTrace();
873
+ const ai: LunoraAi = aiBinding
874
+ ? createAi({ binding: aiBinding as AiBindingLike, env: env as Record<string, unknown>, metadata: { functionPath: options.functionPath, traceId: aiTrace?.traceId } })
875
+ : aiStub;
876
+ `,configField:`
877
+ ai?: (env: Record<string, unknown>) => AiBindingLike;`,contextField:`
878
+ ai,`,stub:`
879
+ const aiStub: LunoraAi = {
880
+ embeddingModel: () => {
881
+ ${t}
882
+ },
883
+ model: () => {
884
+ ${t}
885
+ },
886
+ run: async () => {
887
+ ${t}
888
+ },
889
+ // workersai is a callable-with-properties; a bare throwing arrow isn't
890
+ // structurally assignable, so cast it. Never invoked (the stub throws first).
891
+ workersai: (() => {
892
+ ${t}
893
+ }) as unknown as LunoraAi["workersai"],
894
+ };
895
+ `}},O=(e,t,n,{cast:r="",sync:o=[]}={})=>{const s=n.map(i=>` ${i}: ${o.includes(i)?"":"async "}() => {
896
+ ${t}
897
+ },`).join(`
898
+ `);return`
899
+ const ${e} = {
900
+ ${s}
901
+ }${r};
902
+ `},E={build:"",configField:"",contextField:"",importLines:[],stub:""},wr=e=>e?{build:`
903
+ const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
904
+ // KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
905
+ // when a value changes — a subscription that read one can never be proven
906
+ // current on reconnect and must re-snapshot. Reads only; \`put\`/\`delete\`
907
+ // are writes and stay unstamped.
908
+ const kv: Kv = markUnvouchableReads(kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub, options.onRead, [
909
+ "get",
910
+ "getRaw",
911
+ "getWithMetadata",
912
+ "list",
913
+ ]);
914
+ `,configField:`
915
+ kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
916
+ kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:O("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:E,kr=(e,t)=>e?{build:`
917
+ const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
918
+ provider: () => config.flags?.(env),
919
+ targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
920
+ });
921
+ `,configField:`
922
+ flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
923
+ flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:E,xr=e=>e?{build:`
924
+ const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
925
+ `,configField:"",contextField:`
926
+ notify,
927
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:E,vr=e=>e?{build:`
928
+ const envConfig = lunoraEnvContract.${e.exportName}(env);
929
+ `,configField:"",contextField:`
930
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:E,Rr=e=>e?{build:`
931
+ const access = accessFacade(identity, userId);
932
+ `,configField:"",contextField:`
933
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:E,Sr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=a=>`
934
+ const env = (this.env ?? {}) as Record<string, unknown>;
935
+ const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
936
+ provider: () => config.flags?.(env),
937
+ targetingKey: ${a},
938
+ });`,o=`
939
+ /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
940
+ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }> = ${JSON.stringify(e,void 0,4)};
941
+ `,s=`
942
+ protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${r("undefined")}
943
+ const evalContext = context as import("${n}").EvaluationContext | undefined;
944
+ const evaluations: FlagsResult["flags"] = [];
945
+
946
+ for (const entry of LUNORA_FLAG_KEYS) {
947
+ // eslint-disable-next-line no-await-in-loop -- flags evaluate sequentially; each shares the single memoized provider client
948
+ const details =
949
+ entry.type === "boolean"
950
+ ? await flags.details.boolean(entry.key, false, evalContext)
951
+ : entry.type === "number"
952
+ ? await flags.details.number(entry.key, 0, evalContext)
953
+ : entry.type === "string"
954
+ ? await flags.details.string(entry.key, "", evalContext)
955
+ : await flags.details.object(entry.key, {}, evalContext);
956
+
957
+ evaluations.push({ errorCode: details.errorCode, key: entry.key, reason: details.reason, type: entry.type, value: details.value, variant: details.variant });
958
+ }
959
+
960
+ return { configured: true, flags: evaluations };
961
+ }
962
+ `,i=`
963
+ protected override runFlagSubscriptionRead(_functionPath: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<unknown> {${r("() => flagsConfig.identify?.({ identity: identity?.identity ?? null, userId: identity?.userId ?? null })")}
964
+ const key = typeof args.key === "string" ? args.key : "";
965
+
966
+ // SECURITY: the reactive channel is public (any socket, no auth). Serve
967
+ // ONLY statically-discovered flag keys — an arbitrary client-supplied key
968
+ // would let a subscriber probe the value of internal/unreleased flags the
969
+ // app never exposes. Unknown key ⇒ the "nothing to deliver" sentinel.
970
+ // eslint-disable-next-line unicorn/no-null -- the base hook's "nothing to deliver" sentinel
971
+ if (key.length === 0 || !LUNORA_FLAG_KEYS.some((entry) => entry.key === key)) {
972
+ return Promise.resolve(null);
973
+ }
974
+
975
+ // SECURITY: evaluate under the socket's server-verified identity ONLY
976
+ // (the targetingKey resolved above). Client-supplied targeting context is
977
+ // NOT honored on this public channel — otherwise a subscriber could spoof
978
+ // targeting attributes (e.g. plan/role) to unlock a flag gated on them.
979
+ const context = undefined;
980
+
981
+ if (args.type === "number") {
982
+ return flags.number(key, typeof args.default === "number" ? args.default : 0, context);
983
+ }
984
+
985
+ if (args.type === "string") {
986
+ return flags.string(key, typeof args.default === "string" ? args.default : "", context);
987
+ }
988
+
989
+ if (args.type === "object") {
990
+ return flags.object(key, (args.default ?? {}) as import("${n}").JsonValue, context);
991
+ }
992
+
993
+ return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
994
+ }
995
+ `;return{constant:o,evaluateOverride:s,subscriptionOverride:i}},$r=e=>e?{build:`
996
+ const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
997
+ const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
998
+ `,configField:`
999
+ analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
1000
+ analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:O("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:E,Nr=e=>e?{build:`
1001
+ const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
1002
+ const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
1003
+ `,configField:`
1004
+ images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
1005
+ images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:O("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:E,Tr=e=>e?{build:`
1006
+ const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
1007
+ `,configField:`
1008
+ sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
1009
+ sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:O("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:E,Ar=e=>e?{build:`
1010
+ const browser: Browser = config.browser ? config.browser(env) : browserStub;
1011
+ `,configField:`
1012
+ browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
1013
+ browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:O("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:E,Or=e=>e?{build:`
1014
+ const r2sqlEnv = env as Record<string, unknown>;
1015
+ const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
1016
+ const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
1017
+ const r2sqlBucket = r2sqlEnv.R2_SQL_BUCKET as string | undefined;
1018
+ const r2sql: R2SqlClient = config.r2sql
1019
+ ? config.r2sql(env)
1020
+ : r2sqlAccountId && r2sqlToken && r2sqlBucket
1021
+ ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
1022
+ : r2sqlStub;
1023
+ `,configField:`
1024
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:O("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:E,Ir=e=>e?{build:`
1025
+ const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
1026
+ const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
1027
+ `,configField:`
1028
+ pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:O("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,io=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(b(s.exportName,`container export "${s.exportName}"`),b(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
1029
+ export class ${s.className} extends LunoraContainer {
1030
+ public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1031
+ super(ctx, env, ${s.exportName}, "${s.exportName}"${n});
1032
+ }
1033
+ }
1034
+ `)).join(`
1035
+ `),o=e.map(s=>s.exportName).join(", ");return`${S}/**
1036
+ * Container-enabled Durable Object classes for the containers declared in
1037
+ * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
1038
+ * requires each \`containers[].class_name\` to be exported by the worker:
1039
+ *
1040
+ * \`export * from "./lunora/_generated/containers.js";\`
1041
+ *
1042
+ * \`ContainerProxy\` is re-exported alongside them: the egress-interception path
1043
+ * (\`allowedHosts\`/\`deniedHosts\`/\`interceptHttps\` and the runtime
1044
+ * \`handle.egress\` controls) routes container outbound traffic through this
1045
+ * WorkerEntrypoint, so it too must be exported by the deployed worker.
1046
+ */
1047
+ import { LunoraContainer } from "@lunora/container/do";
1048
+
1049
+ import { ${o} } from "../containers.js";
1050
+
1051
+ export { ContainerProxy } from "@lunora/container/do";
1052
+
1053
+ ${r}`},Cr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)b(r.exportName,`container export "${r.exportName}"`),b(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
1054
+ `);return{build:`
1055
+ const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
1056
+ `,contextField:`
1057
+ containers,`,importLines:['import type { ContainerBindingSpec } from "@lunora/container";','import { createContainerContext } from "@lunora/container";'],specs:`
1058
+ /** Wiring specs for \`ctx.containers\` (codegen-derived from \`lunora/containers.ts\`). */
1059
+ const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
1060
+ ${n}
1061
+ ];
1062
+ `}},lo=e=>{if(e.length===0)return"";const t=e.map(r=>(b(r.exportName,`workflow export "${r.exportName}"`),b(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
1063
+ export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
1064
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1065
+ super(ctx, env, ${r.exportName}, "${r.exportName}");
1066
+ }
1067
+ }
1068
+ `)).join(`
1069
+ `),n=e.map(r=>r.exportName).join(", ");return`${S}/**
1070
+ * WorkflowEntrypoint classes for the workflows declared in
1071
+ * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
1072
+ * requires each \`workflows[].class_name\` to be exported by the worker:
1073
+ *
1074
+ * \`export * from "./lunora/_generated/workflows.js";\`
1075
+ */
1076
+ import LunoraWorkflow from "@lunora/workflow/do";
1077
+
1078
+ import { ${n} } from "../workflows.js";
1079
+
1080
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`), so each entrypoint keeps the authored \`ctx.params\` type. */
1081
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
1082
+ ? unknown extends Params
1083
+ ? Record<string, unknown>
1084
+ : NonNullable<Params>
1085
+ : Record<string, unknown>;
1086
+
1087
+ /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
1088
+ type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
1089
+
1090
+ ${t}`},co=e=>{if(e.length===0)return"";const n=e.filter(a=>a.voice).length>0,r=e.map(a=>{b(a.exportName,`agent export "${a.exportName}"`),b(a.className,`agent class "${a.className}"`);const c=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
1091
+ export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1092
+ public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1093
+ super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
1094
+ }
1095
+ }
1096
+ `;if(!a.voice)return c;const d=a.voiceClassName??"",p=a.voiceBindingName??"";b(d,`agent voice class "${d}"`);const m=`
1097
+ /** Voice-session Durable Object for the \`${a.exportName}\` agent (binding \`${p}\`). */
1098
+ export class ${d} extends VoiceSessionDO {
1099
+ public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
1100
+ super(ctx, env, ${a.exportName}, "${a.exportName}");
1101
+ }
1102
+ }
1103
+ `;return`${c}${m}`}).join(`
1104
+ `),o=e.map(a=>a.exportName).join(", ");return`${S}/**
1105
+ * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
1106
+ * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
1107
+ * Workflow. Re-export them from your worker entry — wrangler requires each
1108
+ * \`workflows[].class_name\` to be exported by the worker:
1109
+ *
1110
+ * \`export * from "./lunora/_generated/agents.js";\`${n?"\n *\n * Voice-enabled agents ALSO get a `VoiceSessionDO` subclass here — a real\n * Durable Object (unlike the Workflow), so wrangler needs both its\n * `durable_objects` binding and its `class_name` export (the same re-export\n * line covers it).":""}
1111
+ */
1112
+ import LunoraWorkflow from "@lunora/workflow/do";
1113
+ ${n?'import { compileAgentWorkflow, VoiceSessionDO } from "@lunora/agent";':'import { compileAgentWorkflow } from "@lunora/agent";'}
1114
+ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
1115
+
1116
+ import { ${o} } from "../agents.js";
1117
+
1118
+ ${r}`},uo=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)b(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
1119
+ `);return`${S}/**
1120
+ * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
1121
+ * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
1122
+ * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
1123
+ * by \`defineApp\` — you don't import this directly.
1124
+ */
1125
+ import type { QueueRegistry } from "@lunora/queue";
1126
+
1127
+ import { ${n} } from "../queues.js";
1128
+
1129
+ /** Stable wrangler queue name → { definition, exportName } for batch routing. */
1130
+ export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
1131
+ ${r}
1132
+ };
1133
+ `},Lr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)b(n.exportName,`workflow export "${n.exportName}"`),b(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
1134
+ `);return{build:`
1135
+ const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
1136
+ `,contextField:`
1137
+ workflows,`,importLines:['import type { WorkflowBindingSpec } from "@lunora/workflow";','import { createWorkflowContext } from "@lunora/workflow";'],specs:`
1138
+ /** Wiring specs for \`ctx.workflows\` (codegen-derived from \`lunora/workflows.ts\`). */
1139
+ const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
1140
+ ${t}
1141
+ ];
1142
+ `}},_r=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)b(n.exportName,`queue export "${n.exportName}"`),b(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
1143
+ `);return{build:`
1144
+ const queues = createQueueContext(env, LUNORA_QUEUES);
1145
+ `,contextField:`
1146
+ queues,`,importLines:['import type { QueueBindingSpec } from "@lunora/queue";','import { createQueueContext } from "@lunora/queue";'],specs:`
1147
+ /** Wiring specs for \`ctx.queues\` (codegen-derived from \`lunora/queues.ts\`). */
1148
+ const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
1149
+ ${t}
1150
+ ];
1151
+ `}},Er=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)b(n.exportName,`agent export "${n.exportName}"`),b(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
1152
+ `);return{build:`
1153
+ const agents = createAgentContext(env, LUNORA_AGENTS);
1154
+ `,contextField:`
1155
+ agents,`,importLines:['import { createAgentContext } from "@lunora/agent";','import type { AgentBindingSpec } from "@lunora/agent";'],specs:`
1156
+ /** Wiring specs for \`ctx.agents\` (codegen-derived from \`lunora/agents.ts\`). */
1157
+ const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
1158
+ ${t}
1159
+ ];
1160
+ `}},St=(e,t,n,r,o)=>({constant:`
1161
+ ${o}
1162
+ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1163
+ `,override:`
1164
+ protected override ${n}(): ${t} {
1165
+ return ${e};
1166
+ }
1167
+ `}),Dr=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return St("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Pr=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return St("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Fr=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
1168
+ const payments: LunoraPayment = config.payment
1169
+ ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
1170
+ : paymentStub;
1171
+ `,configField:`
1172
+ payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
1173
+ payments,`,stub:O("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},Mr=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
1174
+ const x402: X402Pay = config.x402
1175
+ ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1176
+ : x402Stub;
1177
+ `,configField:`
1178
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:O("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Br=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],po=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:m=!1,hasImages:w=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:y=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasX402:k=!1,maskMetadata:N,mutators:T=[],queues:D=[],rlsMetadata:C,schema:f,schemaSnapshot:P,shapes:ie=[],storageRules:F,studioFeatures:le,useUmbrella:ce=!1,workflows:q=[]})=>{const I=ae(ce),ee=T.length>0,L=ie.length>0,v=P===void 0?"":xn(P),Ae=P===void 0?"":`
1179
+ /** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
1180
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(vn(P))}, json: ${JSON.stringify(v)} };
1181
+ `,M=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:ue,contextField:Oe,stub:Ie}=yr(a),pe=Rr(i),V=wr(u),H=kr(p,I.flags),W=Sr(s,p,I.flags),G=xr(l),te=vr(o),J=$r(c),ne=Nr(w),U=Tr(m),K=Ar(d),Q=Or(x),B=Ir(R),{build:Ce,contextField:Le,importLines:ve,specs:Re}=_r(D),{build:he,contextField:_e,importLines:Ee,specs:Se}=Cr(r,f.jurisdiction),{build:me,contextField:De,importLines:Pe,specs:$e}=Lr(q),{build:Fe,contextField:Me,importLines:ge,specs:fe}=Er(n),{build:Be,configField:je,contextField:qe,imports:be,stub:ye}=Fr(y),{build:Ze,configField:h,imports:We,stub:Ne}=Mr(k),re=e,Nt=t,Tt=C??{policies:[],roles:[]},At=N??{columns:[]},Ot=F??{rules:[]},It=le??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ct,override:Lt}=Dr(q),{constant:_t,override:Et}=Pr(D),z=f.vectorIndexes.length>0,et=new Set(f.tables.filter(g=>typeof g.shardMode=="object"&&g.shardMode.kind==="shardBy").map(g=>g.name)),Te=f.vectorIndexes.some(g=>et.has(g.table)),we=f.tables.some(g=>g.shardMode==="global"),Ue=f.tables.some(g=>g.shardMode==="global"&&g.globalBackend==="hyperdrive"),tt=f.tables.some(g=>g.shardMode==="global"&&g.globalBackend!=="hyperdrive"),oe=f.tables.some(g=>g.externalSource!==void 0),nt=f.tables.some(g=>g.memory===!0),Ke=f.tables.some(g=>g.shardMode!=="global"&&g.searchIndexes.length>0);if(tt&&Ue)throw new Z("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=f.tables.length>0,Dt=dr(f),Pt=pr(f),Ft=fr(f),Mt=ur(f),rt=hr(f),ot=Br(z,q.length>0,D.length>0,p,Ke);L&&ot.push("WhereInput");const at=br(we),Bt=L?`
1182
+ protected override resolveShape(name: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
1183
+ const shape = LUNORA_SHAPES[name];
1184
+
1185
+ if (!shape) {
1186
+ return undefined;
1187
+ }
1188
+
1189
+ this.ensureMigrated();
1190
+
1191
+ // Trusted ctx from the socket's OWN verified identity — the client
1192
+ // supplies only the shape name + args; \`compileWhere\` validates the
1193
+ // args then runs the shape's \`where(ctx, args)\` under that identity,
1194
+ // so which rows replicate is a server decision (reads-as-permissions).
1195
+ const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity });
1196
+ // \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
1197
+ // \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
1198
+ // rather than every shape restating the ownership check in its \`where\`.
1199
+ const shapeWhere = shape.compileWhere(ctx, args, {
1200
+ ownerField: (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField,
1201
+ }) as unknown as WhereInput;
1202
+
1203
+ // AND-compose with the table's RLS read base-where. A shape runs no
1204
+ // procedure, so the \`.use(rls(...))\` middleware never fires; without
1205
+ // this merge its reads would bypass every read policy on the table
1206
+ // (rows the caller can't see would replicate). \`composeShapeReadWhere\`
1207
+ // evaluates the table's read policies under this same trusted ctx —
1208
+ // exactly the request-time path — and fails closed under a
1209
+ // \`.rls("required")\` schema for a non-\`.public()\`, policy-less table.
1210
+ const effectiveWhere = composeShapeReadWhere(LUNORA_RLS_READ_REGISTRY, {
1211
+ ctx,
1212
+ identity: identity?.identity ?? null,
1213
+ rlsRequired: (schema as unknown as { rlsMode?: string }).rlsMode === "required",
1214
+ shapeWhere,
1215
+ table: shape.table,
1216
+ tablePublic: (schema as unknown as { tables: Record<string, { isPublic?: boolean }> }).tables[shape.table]?.isPublic === true,
1217
+ userId: identity?.userId ?? null,
1218
+ });
1219
+
1220
+ // A live shape pokes only from its OWN shard's op-log, so a \`where()\`
1221
+ // that joins to a \`.shardBy()\` table (rows in another DO) is rejected
1222
+ // here — the first point the compiled predicate + shard modes are both
1223
+ // known. Remedy: denormalize, or move the joined table to \`.global()\`.
1224
+ assertShapeShardable(effectiveWhere, schema as unknown as SchemaLike, shape.table);
1225
+
1226
+ // A \`.global()\` table lives in D1 (no per-DO op-log): flag it so the
1227
+ // base serves it through the latency-tiered poll path (\`readGlobalShapeRows\`)
1228
+ // instead of the CDC poke path.
1229
+ const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global";
1230
+
1231
+ return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
1232
+ }
1233
+ `:"",jt=ee?`
1234
+ protected override isCustomMutator(functionPath: string): boolean {
1235
+ return LUNORA_MUTATOR_PATHS.has(functionPath);
1236
+ }
1237
+ `:"",qt=L?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Wt=L?"assertShapeShardable, ":"",ke=[`import type { ${ot.join(", ")} } from "${I.do}";`,`import { applyCdcChanges, ${Ke?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${nt?"clearMemoryTables, ":""}${Wt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${oe?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Te?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${at.importFragment}ShardDO as ShardDOBase } from "${I.do}";`,...oe?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${I.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes } from "${I.server}";`:`import { asBucketStorage, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes } from "${I.server}";`];Qe&&ke.push(`import { bindOrm, bindTableFacade } from "${I.server}";`),z&&ke.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&ke.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ke.push(...pe.importLines,...V.importLines,...H.importLines,...G.importLines,...te.importLines,...J.importLines,...ne.importLines,...U.importLines,...K.importLines,...Q.importLines,...B.importLines,...Ee,...Pe,...ve,...ge,...be,...We,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ee?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ut=z?`
1238
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Kt=tt?`
1239
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Qt=Ue?`
1240
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Vt=oe?`
1241
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Ht='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Gt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Jt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',zt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Yt=we?O("globalDbStub: DatabaseWriterLike",Ht,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Xt=z?O("vectorsStub: VectorSearchLike",Gt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Zt=Te?`
1242
+ const vectorShardKey = this.currentShardKey();
1243
+ `:"",en=Te?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",tn=Te?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${f.vectorIndexes.filter(g=>et.has(g.table)).map(g=>JSON.stringify(g.name)).join(", ")}] }`:"",nn=z?`
1244
+ let vectors: VectorSearchLike;
1245
+ let onWrite: WriteHook | undefined;
1246
+
1247
+ if (config.vectors) {
1248
+ const lunora = createVectors({ indexes: config.vectors(env) });
1249
+ ${Zt}
1250
+ vectors = createContextVectors(lunora${tn});
1251
+ onWrite = createVectorSyncHook({ ${en}schema: schema as unknown as VectorSchemaLike, vectors });
1252
+ } else {
1253
+ vectors = vectorsStub;
1254
+ onWrite = undefined;
1255
+ }
1256
+
1257
+ // Vectorize lives outside this shard's SQLite, so a query whose result
1258
+ // depends on a similarity search cannot be proven current on reconnect —
1259
+ // an unrelated upsert (or a re-index) moves the matches without touching
1260
+ // \`__cdc_log\`. Wrapped AFTER \`onWrite\` is built so the write-through
1261
+ // vector-sync hook keeps calling the bare facade.
1262
+ vectors = markUnvouchableReads(vectors, options.onRead, ["getByIds", "query"]);
1263
+ `:"",rn=`{
1264
+ ...this.ctxDbTuning(),
1265
+ auth: { identity: identity ?? null, userId: userId ?? null },
1266
+ broadcast: (delta) => {
1267
+ this.recordChangedTable(delta.table, delta.indexKeys);
1268
+ },
1269
+ cdc: config.cdc ?? false,
1270
+ // A dispatch with NO caller identity runs system-trusted: RLS scopes
1271
+ // rows to a user, and these have no user to scope to. This is the tier
1272
+ // migrations, imports and the external-source poll loop already run in
1273
+ // (see \`adminWriterPrelude\`). Only \`onShardInit\` and \`onQueryChange\`
1274
+ // reach it; \`onConnect\`/\`onDisconnect\` carry a verified identity and
1275
+ // stay guarded like any request.
1276
+ enforceRls: options.trusted !== true,
1277
+ headroom: options.headroom ?? this.transactionHeadroom(),
1278
+ // A live predicate, not a flag: the transaction opens AFTER this ctx
1279
+ // is built (a mutation dispatch wraps the handler), so only a call-time
1280
+ // read reports the truth. \`_commitSeq\` reuses one sequence across
1281
+ // writes only while they commit together — an action is not wrapped, so
1282
+ // each of its writes allocates its own.
1283
+ inTransaction: () => this.isInTransaction(),
1284
+ onIndexUse: this.getCtxDbIndexUseHook(),
1285
+ // Bound to THIS dispatch's reactive-cache read scope (\`handleRpc\`
1286
+ // threads it in), so two concurrent queries never stamp each
1287
+ // other's dep sets. \`executeSubscription\` overrides both with its
1288
+ // own \`ReadFootprint\` pair instead, and a dispatch with neither
1289
+ // gets an unbound hook that stamps no deps.
1290
+ onRead: options.onRead ?? this.getCtxDbReadHook(options.scope),
1291
+ // Left \`undefined\` when there is no scope so \`createShardCtxDb\`
1292
+ // keeps its own "degrade a provable slice to a whole-table dep"
1293
+ // fallback rather than reporting into a no-op.
1294
+ onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${z?`
1295
+ onWrite,`:""}
1296
+ scheduler,
1297
+ schema: schema as unknown as SchemaLike,
1298
+ sql: this.sql as SqlExec,
1299
+ storage,${we?`
1300
+ globalDb,`:""}
1301
+ }`,on=` /**
1302
+ * The bare writer every admin/maintenance entry point writes through.
1303
+ *
1304
+ * Admin and maintenance writes go through the SAME reactive-cache hooks as a
1305
+ * user mutation. Without this, a studio row edit, a TTL sweep, an admin
1306
+ * import, a CDC apply or a data-migration backfill writes without
1307
+ * invalidating, and the next query answers from the pre-write snapshot.
1308
+ *
1309
+ * \`headroom\` meters the transaction. An admin \`/rpc\` caller passes nothing
1310
+ * and falls back to \`this.transactionHeadroom()\`, which for an admin RPC is
1311
+ * \`undefined\` — \`handleAdminRpc\` answers before \`beginDispatch\`, so no
1312
+ * per-dispatch meter is in flight and a bulk loop is bounded by its per-call
1313
+ * row cap alone. The TTL sweep (an alarm work item, no dispatch) passes its
1314
+ * own by-value tracker explicitly instead.
1315
+ */
1316
+ private adminWriter(headroom?: TransactionHeadroomTracker): DatabaseWriterLike {
1317
+ const env = (this.env ?? {}) as Record<string, unknown>;
1318
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1319
+
1320
+ return createShardCtxDb({
1321
+ ...this.ctxDbTuning(),
1322
+ broadcast: (delta) => {
1323
+ this.recordChangedTable(delta.table, delta.indexKeys);
1324
+ },
1325
+ cdc: config.cdc ?? false,
1326
+ headroom,
1327
+ // Live predicate, same as the user-facing ctx — see \`databaseOptions\`.
1328
+ inTransaction: () => this.isInTransaction(),
1329
+ scheduler,
1330
+ schema: schema as unknown as SchemaLike,
1331
+ sql: this.sql as SqlExec,
1332
+ });
1333
+ }`,Y=(g="")=>` const writer = this.adminWriter(${g});`,an=z?`
1334
+ vectors,`:"",sn=Qe?`
1335
+ orm: bindOrm(facade),`:"",Ve=Ue?"config.hyperdriveGlobal":"config.d1",ln=we?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
1336
+ const globalDb: DatabaseWriterLike = ${Ve}?.(env, globalRequest) ?? globalDbStub;
1337
+ `:"",cn=L&&we?`
1338
+ protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1339
+ const env = this.env as Record<string, unknown>;
1340
+ // A shape read performs no writes, so the widened request only needs
1341
+ // the inbound bookmark (pin the membership drain to the caller's own
1342
+ // prior writes) — no \`onBookmark\` here.
1343
+ const globalRequest = { ...identity, ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
1344
+ const globalDb: DatabaseWriterLike = ${Ve}?.(env, globalRequest) ?? globalDbStub;
1345
+ const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
1346
+
1347
+ let cursor: null | string = null;
1348
+
1349
+ // Drain every page of the global membership so the seed/diff sees the
1350
+ // full rowset (D1 \`findMany\` is paginated). Stop one row past the cap:
1351
+ // a broad \`.global()\` shape would otherwise materialize an unbounded
1352
+ // array before the caller's \`withinGlobalShapeBound\` check rejects it,
1353
+ // so bail early and let the caller fail it closed.
1354
+ do {
1355
+ // eslint-disable-next-line no-await-in-loop -- sequential page drain to assemble the full membership
1356
+ const page = await globalDb.findMany(resolved.table, { cursor, where: resolved.effectiveWhere });
1357
+
1358
+ for (const doc of page.page) {
1359
+ rows.push({ doc, id: String((doc as { _id?: unknown })._id) });
1360
+
1361
+ if (rows.length > ShardDOBase.GLOBAL_SHAPE_MAX_ROWS) {
1362
+ return rows;
1363
+ }
1364
+ }
1365
+
1366
+ cursor = page.isDone ? null : page.continueCursor;
1367
+ } while (cursor !== null);
1368
+
1369
+ return rows;
1370
+ }
1371
+
1372
+ protected override async readGlobalChangedTables(sinceSeq: number, cursorOnly?: boolean): Promise<{ cursor: number; floor?: number; tables: string[] } | undefined> {
1373
+ const env = this.env as Record<string, unknown>;
1374
+ // Metadata-only: this asks the global changelog which TABLES moved,
1375
+ // never what changed in them, so it costs one small read per poll tick
1376
+ // for the whole shard — and a tick whose answer omits a shape's table
1377
+ // skips that shape's membership drain entirely.
1378
+ const globalDb: DatabaseWriterLike = ${Ve}?.(env, { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() }) ?? globalDbStub;
1379
+
1380
+ return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
1381
+ }
1382
+ `:"",dn=oe?`
1383
+ const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1384
+ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1385
+ `:"",un=`
1386
+ protected override async runShardInit(): Promise<void> {
1387
+ this.ensureMigrated();
1388
+ ${nt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1389
+ `:""}
1390
+ await this.dispatchShardInit();
1391
+ }
1392
+ `,pn=oe?`
1393
+ protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1394
+ const env = (this.env ?? {}) as Record<string, unknown>;
1395
+ const sourced = Object.entries((schema as unknown as SchemaLike).tables)
1396
+ .map(([table, definition]) => [table, (definition as { externalSource?: ExternalSourceLike }).externalSource] as const)
1397
+ .filter((entry): entry is [string, ExternalSourceLike] => entry[1] !== undefined);
1398
+
1399
+ if (sourced.length === 0) {
1400
+ return undefined;
1401
+ }
1402
+
1403
+ const shardKey = this.currentShardKey();
1404
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1405
+
1406
+ let clients = sourceClientCache.get(this);
1407
+
1408
+ if (clients === undefined) {
1409
+ clients = new Map();
1410
+ sourceClientCache.set(this, clients);
1411
+ }
1412
+
1413
+ let polledAt = sourcePollAtCache.get(this);
1414
+
1415
+ if (polledAt === undefined) {
1416
+ polledAt = new Map();
1417
+ sourcePollAtCache.set(this, polledAt);
1418
+ }
1419
+
1420
+ const now = Date.now();
1421
+ // \`nextDueAt\` tracks the EARLIEST next-due timestamp across every
1422
+ // non-manual source; the shared alarm re-arms there instead of the
1423
+ // fixed 2 s global-shape floor, so a large \`refresh.everyMs\` actually
1424
+ // sleeps until it's due. Stays \`undefined\` when every source is
1425
+ // \`refresh: "manual"\`, so the shared alarm goes idle for this tier.
1426
+ let nextDueAt: number | undefined;
1427
+
1428
+ for (const [table, source] of sourced) {
1429
+ if (source.refresh === "manual") {
1430
+ continue;
1431
+ }
1432
+
1433
+ if (isSourceDue(source.refresh, polledAt.get(table), now)) {
1434
+ try {
1435
+ let client = clients.get(source.binding);
1436
+
1437
+ if (client === undefined) {
1438
+ client = config.sourceClient?.(env, source.binding);
1439
+
1440
+ if (client !== undefined) {
1441
+ clients.set(source.binding, client);
1442
+ }
1443
+ }
1444
+
1445
+ if (client === undefined) {
1446
+ // No SqlClient resolved for this binding (host never wired
1447
+ // \`config.sourceClient\`, or wired it wrong). Surface it in the
1448
+ // Logs panel and stamp \`polledAt\` so a persistent misconfig backs
1449
+ // off to \`refresh.everyMs\` instead of retrying every alarm tick.
1450
+ this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`), trace);
1451
+ } else {
1452
+ // A FRESH tracker per TABLE, not one shared across the whole
1453
+ // loop: one table's runaway pull must not spend a budget a
1454
+ // sibling table needs, and a limit hit here must not block
1455
+ // that sibling from getting its own full budget this tick.
1456
+ const writer = createShardCtxDb({
1457
+ // Admin and maintenance writes go through the SAME reactive-cache hooks as
1458
+ // a user mutation. Without this, a studio row edit, a TTL sweep, an admin
1459
+ // import, a CDC apply or a data-migration backfill writes without
1460
+ // invalidating, and the next query answers from the pre-write snapshot.
1461
+ ...this.ctxDbTuning(),
1462
+ broadcast: (delta) => {
1463
+ this.recordChangedTable(delta.table, delta.indexKeys);
1464
+ },
1465
+ cdc: config.cdc ?? false,
1466
+ headroom: this.alarmHeadroom(),
1467
+ scheduler,
1468
+ schema: schema as unknown as SchemaLike,
1469
+ sql: this.sql as SqlExec,
1470
+ });
1471
+
1472
+ if (source.mode === "incremental") {
1473
+ // Incremental (plan 136): pull only rows past the durable
1474
+ // watermark (or a full-pull seed/reconcile), upsert-only.
1475
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
1476
+ await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
1477
+ } else {
1478
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; slices are independent but small and sequential keeps the writer transaction simple
1479
+ await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
1480
+ }
1481
+ }
1482
+
1483
+ // Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
1484
+ // poll that outruns \`everyMs\` must not make \`nextDueAt\` (below)
1485
+ // stale-immediate and re-arm the alarm in a hammering loop.
1486
+ polledAt.set(table, Date.now());
1487
+ } catch (error) {
1488
+ if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
1489
+ // Batch full, not a genuine failure. Incremental mode only
1490
+ // persists its watermark AFTER a full apply (see
1491
+ // \`pullExternalSourceIncrementalTick\`), so this throw left it
1492
+ // untouched — the next tick safely re-pulls/re-applies the
1493
+ // SAME slice (idempotent upsert). Full-pull mode (and an
1494
+ // incremental source's own occasional full-pull/reconcile
1495
+ // sweep) has no resumable cursor at all — deliberately not
1496
+ // inventing one here; a retry just redoes the whole pull,
1497
+ // safe if wasteful. Either way: warn instead of
1498
+ // \`recordExternalSourceError\`, and leave \`polledAt\`
1499
+ // UNCHANGED (skip the stamp below via \`continue\`) so this
1500
+ // table stays "due" and \`nextPollAlarmTarget\`'s existing
1501
+ // due-now floor re-arms the shared alarm promptly — not a
1502
+ // fresh \`setAlarm(now)\`.
1503
+ this.recordExternalSourceWarning(
1504
+ table,
1505
+ \`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
1506
+ trace,
1507
+ );
1508
+
1509
+ nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
1510
+
1511
+ continue;
1512
+ }
1513
+
1514
+ this.recordExternalSourceError(table, error, trace);
1515
+ // Stamp on failure too, so a persistently failing source throttles
1516
+ // to \`refresh.everyMs\` rather than being hammered every tick.
1517
+ polledAt.set(table, Date.now());
1518
+ }
1519
+ }
1520
+
1521
+ // This source's own next-due time, read AFTER the poll-or-skip above
1522
+ // so a just-polled source reports \`now + everyMs\` (its FRESH due
1523
+ // time), not the stale pre-poll one. An omitted \`refresh\` (poll
1524
+ // every tick) is due again immediately.
1525
+ const sourceNextDueAt = source.refresh === undefined ? now : (polledAt.get(table) ?? now) + source.refresh.everyMs;
1526
+
1527
+ nextDueAt = nextDueAt === undefined ? sourceNextDueAt : Math.min(nextDueAt, sourceNextDueAt);
1528
+ }
1529
+
1530
+ return nextDueAt;
1531
+ }
1532
+ `:"",hn=rt.length>0,mn=`
1533
+ public constructor(state: ShardDOState, env: unknown) {
1534
+ super(state, env, {
1535
+ // Every writer this file builds spreads the ctxDbTuning() slice —
1536
+ // the user-facing ctx and all three admin/maintenance writers — so
1537
+ // the base class can drop its coarse invalidation backstop. Only the
1538
+ // emitter can know that; a hand-written subclass leaves this unset
1539
+ // and keeps the backstop.
1540
+ ctxDbCacheWired: true,
1541
+ ...(config.maxRelationKeys === undefined ? {} : { maxRelationKeys: config.maxRelationKeys }),
1542
+ ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1543
+ ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1544
+ });
1545
+ ${oe?`
1546
+ const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1547
+ const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1548
+
1549
+ return source !== undefined && source.refresh !== "manual";
1550
+ });
1551
+
1552
+ if (autoSourced) {
1553
+ void this.scheduleSourcePoll();
1554
+ }
1555
+ `:""}${hn?`
1556
+ if (LUNORA_TTL_SWEEPS.length > 0) {
1557
+ void this.scheduleTtlSweep();
1558
+ }
1559
+ `:""} }
1560
+
1561
+ protected override isQueryFunction(functionPath: string): boolean {
1562
+ return LUNORA_FUNCTIONS[functionPath]?.kind === "query";
1563
+ }
1564
+ `,gn=Qe?`
1565
+ const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1566
+ ${f.tables.map(g=>` facade[${JSON.stringify(g.name)}] = bindTableFacade(db, ${JSON.stringify(g.name)});`).join(`
1567
+ `)}
1568
+ `:"",fn=`${pe.build}${V.build}${H.build}${J.build}${te.build}
1569
+ const secrets = createSecrets(env);
1570
+ `,bn=`${pe.contextField}${V.contextField}${H.contextField}${G.contextField}${J.contextField}${te.contextField}
1571
+ secrets,`,yn=G.build,st=w||m||d||x||R||k,wn=st?`
1572
+ // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1573
+ // and attached only for an \`action\` so query/mutation ctx never carry them.
1574
+ if (isAction) {
1575
+ ${ne.build}${U.build}${K.build}${Q.build}${B.build}${Ze}${[...w?[" ctx.images = images;"]:[],...m?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...x?[" ctx.r2sql = r2sql;"]:[],...R?[" ctx.pipelines = pipelines;"]:[],...k?[" ctx.x402 = x402;"]:[]].join(`
1576
+ `)}
1577
+ }
1578
+ `:"",kn=st?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1579
+ `:"";return`${S}${ke.join(`
1580
+ `)}
1581
+
1582
+ type FunctionKind = "action" | "mutation" | "query";
1583
+
1584
+ interface FunctionReference {
1585
+ __lunoraRef: string;
1586
+ }
1587
+
1588
+ /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1589
+ const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(Dt,void 0,4)};
1590
+
1591
+ /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1592
+ const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(Pt,void 0,4)};
1593
+
1594
+ /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1595
+ const LUNORA_TABLE_COLUMNS: Record<
1596
+ string,
1597
+ Array<{ bucket?: string; enumValues?: string[]; isStorage?: boolean; name: string; nullable?: boolean; optional: boolean; pk?: boolean; ref?: string; type: string }>
1598
+ > = ${JSON.stringify(Ft,void 0,4)};
1599
+
1600
+ /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1601
+ const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(Mt,void 0,4)};
1602
+
1603
+ /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1604
+ const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(rt,void 0,4)};
1605
+
1606
+ /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1607
+ const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(re,void 0,4)};
1608
+
1609
+ /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1610
+ const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(Nt,void 0,4)};
1611
+
1612
+ /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1613
+ const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(Tt,void 0,4)};
1614
+
1615
+ /** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
1616
+ const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(At,void 0,4)};
1617
+
1618
+ /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1619
+ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Ot,void 0,4)};
1620
+
1621
+ /** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
1622
+ const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(It,void 0,4)};
1623
+ ${Ae}${W.constant}${qt}${Ct}${_t}${Se}${$e}${Re}${fe}
1624
+ export interface ShardDOConfig {
1625
+ /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1626
+ cdc?: boolean;
1627
+ /** Ceiling on the join keys one relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
1628
+ maxRelationKeys?: number;
1629
+ /** Enable the per-shard reactive query cache: \`true\` for the defaults, or an options object to tune the caps. Query results are memoized by \`(functionPath, args, identity)\` and invalidated by the ctx-db write hooks before the subscription broadcast, so subscribers never observe a pre-write value. Omitted (or \`false\`) keeps every dispatch re-running its handler. */
1630
+ reactiveCache?: boolean | { maxBytes?: number; maxEntries?: number };
1631
+ /** Resolution policy for a relation-crossing \`where\` whose child is co-located in this shard: \`"auto"\` (cost-based, the engine default), \`"always"\` (inline correlated EXISTS) or \`"never"\` (universal semijoin). All three return identical rows. */
1632
+ relationExistsPushDown?: "always" | "auto" | "never";
1633
+ /** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
1634
+ observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1635
+ /** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
1636
+ scheduler?: (env: Record<string, unknown>) => unknown;
1637
+ storage?: (env: Record<string, unknown>) => unknown;${Ut}${ue}${V.configField}${H.configField}${J.configField}${ne.configField}${U.configField}${K.configField}${Q.configField}${B.configField}${je}${h}${Kt}${Qt}${Vt}
1638
+ }
1639
+ ${O("schedulerStub",Jt,["cancel","runAfter","runAt"])}${O("storageStub",zt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${Yt}${dn}${Xt}${Ie}${V.stub}${H.stub}${J.stub}${ne.stub}${U.stub}${K.stub}${Q.stub}${B.stub}${ye}${Ne}
1640
+ // Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
1641
+ // referencing call fails loudly with a clear error instead of overflowing the
1642
+ // stack. Tracked across the awaited handler chain (one DO invocation is
1643
+ // single-threaded), so the counter reflects true nesting depth.
1644
+ const MAX_RUN_DEPTH = 32;
1645
+ let runDepth = 0;
1646
+
1647
+ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: Record<string, unknown>, ctx: unknown): Promise<unknown> => {
1648
+ const registered = LUNORA_FUNCTIONS[functionPath];
1649
+
1650
+ if (!registered) {
1651
+ throw new Error(\`unknown function: \${functionPath}\`);
1652
+ }
1653
+
1654
+ if (registered.kind !== expected) {
1655
+ throw new Error(\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: "\${functionPath}" is registered as a \${registered.kind}, not a \${expected}\`);
1656
+ }
1657
+
1658
+ if (runDepth >= MAX_RUN_DEPTH) {
1659
+ throw new LunoraError("RUN_DEPTH_EXCEEDED", \`ctx.run*: composition depth limit (\${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation\`);
1660
+ }
1661
+
1662
+ runDepth += 1;
1663
+
1664
+ try {
1665
+ return await registered.handler(ctx, args);
1666
+ } finally {
1667
+ runDepth -= 1;
1668
+ }
1669
+ };
1670
+
1671
+ /**
1672
+ * Build the project's shard Durable Object. Export the result as \`ShardDO\`
1673
+ * from the worker entry so wrangler binds it by name.
1674
+ */
1675
+ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1676
+ class extends ShardDOBase {${mn}
1677
+ private migrated = false;
1678
+
1679
+ public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope): Promise<unknown> {
1680
+ const registered = LUNORA_FUNCTIONS[functionPath];
1681
+
1682
+ // Internal functions are reachable server-side only: via \`ctx.run*\`
1683
+ // composition, or a trusted system dispatch (scheduler/cron, marked by
1684
+ // \`isSystemDispatch()\`). A client RPC never carries that flag, so its
1685
+ // internals stay not-found and never leak across the external boundary.
1686
+ if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) {
1687
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
1688
+ }
1689
+
1690
+ this.ensureMigrated();
1691
+
1692
+ // \`headroom\`, when the caller supplied one, is threaded straight
1693
+ // through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
1694
+ // fallback (the racy shared-field read) entirely for THIS dispatch.
1695
+ // The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
1696
+ // \`handleRunAs\` don't mint their own and omit it, so they keep the
1697
+ // prior fallback behavior unchanged.
1698
+ //
1699
+ // \`scope\` is the reactive cache's per-dispatch read capture, threaded
1700
+ // the same way and for the same reason: the ctx-db read hooks resolve
1701
+ // their tracker at READ time, so binding them to the scope THIS
1702
+ // dispatch was handed is what keeps a concurrent query's reads out of
1703
+ // our dep set — and ours out of theirs. A dispatch with no scope (a
1704
+ // mutation, an action, a cache-less shard) builds unbound hooks that
1705
+ // stamp no deps.
1706
+ const ctx = this.buildCtx({ functionPath, headroom, scope, trusted: registered.lifecycle === "init" });
1707
+
1708
+ // A mutation's writes must commit all-or-nothing: wrap its dispatch in
1709
+ // the DO's BEGIN/COMMIT span so any throw (a validator, an RLS denial,
1710
+ // an OCC conflict, a failed row mid-\`insertMany\`/\`patchMany\`) rolls
1711
+ // back every write the mutation made. Queries are read-only and actions
1712
+ // do external I/O that can't be rolled back, so both dispatch directly.
1713
+ // \`ctx.run*\` composition runs inside this span (it never re-enters
1714
+ // handleRpc); runInTransaction's own guard rejects accidental nesting.
1715
+ //
1716
+ // The replay bookkeeping (idempotency dedup row + custom-mutator
1717
+ // watermark advance) commits INSIDE this span via
1718
+ // \`commitMutationBookkeeping\`, so the writes, the dedup row, and the
1719
+ // watermark are atomic — a crash can't leave the writes durable without
1720
+ // the replay guard.
1721
+ if (registered.kind === "mutation") {
1722
+ const result = await this.runInTransaction(async () => {
1723
+ const value = await registered.handler(ctx, args);
1724
+
1725
+ this.commitMutationBookkeeping(value);
1726
+
1727
+ return value;
1728
+ });
1729
+
1730
+ // The transaction committed, so the rows are durable and the objects
1731
+ // their deletion orphaned can go. Deliberately AFTER the span, never
1732
+ // inside it: an R2 delete cannot roll back, so a delete issued from
1733
+ // within a transaction that later aborts destroys data the surviving
1734
+ // row still points at. A throw above skips this entirely and the
1735
+ // queue dies with \`ctx\`.
1736
+ //
1737
+ // \`flushDeferredDeletes\` never rejects — the mutation has already
1738
+ // succeeded, so a failed cleanup must not turn into a failed response.
1739
+ // A leaked object is reported through \`ctx.log\` instead, with its key.
1740
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
1741
+
1742
+ return result;
1743
+ }
1744
+
1745
+ const result = await registered.handler(ctx, args);
1746
+
1747
+ // An action is not itself transactional, but \`ctx.runMutation\` runs its
1748
+ // submutations on THIS ctx, so their queued deletes land here — this is
1749
+ // the first point at which those writes are known to have committed. A
1750
+ // dispatch with nothing queued no-ops.
1751
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
1752
+
1753
+ return result;
1754
+ }
1755
+
1756
+ // Only a \`mutation\` may enter the base class's single-writer gate for
1757
+ // mutation-replay dedup — it is \`blockConcurrencyWhile\`, so gating an
1758
+ // action would stall every other dispatch on the shard for the length of
1759
+ // its outbound I/O, on nothing but a caller-supplied header. Unregistered
1760
+ // paths answer \`false\`; \`handleRpc\` above rejects them anyway.
1761
+ protected override isMutationFunction(functionPath: string): boolean {
1762
+ return LUNORA_FUNCTIONS[functionPath]?.kind === "mutation";
1763
+ }
1764
+ ${at.override}
1765
+ protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
1766
+ const registered = LUNORA_FUNCTIONS[functionPath];
1767
+
1768
+ if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
1769
+ return null;
1770
+ }
1771
+
1772
+ this.ensureMigrated();
1773
+
1774
+ const footprint = createReadFootprint();
1775
+ // Identity is threaded EXPLICITLY from the (deferred/interleaved)
1776
+ // subscription caller — never read from the shared per-request field
1777
+ // here — so a concurrent RPC can't leak its identity into this re-run.
1778
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange });
1779
+ const result = await registered.handler(ctx, args);
1780
+
1781
+ // Ranges come from THIS run's reads, never a shared field on the DO:
1782
+ // a deferred re-run interleaves with unrelated dispatches.
1783
+ return { ranges: footprint.ranges(), result, tables: footprint.tables };
1784
+ }
1785
+
1786
+ protected override executeStream(functionPath: string, args: Record<string, unknown>): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
1787
+ const registered = LUNORA_FUNCTIONS[functionPath];
1788
+
1789
+ if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
1790
+ return null;
1791
+ }
1792
+
1793
+ this.ensureMigrated();
1794
+
1795
+ return {
1796
+ ...(registered.durable ? { durable: registered.durable as { ttlMs?: number } } : {}),
1797
+ iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
1798
+ };
1799
+ }
1800
+ ${jt}${Bt}${cn}${pn}
1801
+ protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor"): readonly string[] {
1802
+ return LUNORA_LIFECYCLE_HOOKS[event];
1803
+ }
1804
+ ${un}
1805
+ // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1806
+ // socket-terminated half of the same reactivity — and differs only in who
1807
+ // consumes the result: the base's \`dispatchReactors\` stores the digest as
1808
+ // the new baseline and the footprint as the "should I even re-run this"
1809
+ // gate, instead of pushing a frame down a socket.
1810
+ //
1811
+ // Wrapped in \`runInTransaction\` because a reactor handler is a mutation
1812
+ // and its writes must commit all-or-nothing. Safe to open here: the refresh
1813
+ // drain runs OUTSIDE any dispatch transaction (it is post-flush background
1814
+ // work), so this never nests.
1815
+ //
1816
+ // NO identity is threaded, and the ctx is built \`trusted\`. A reactor fires
1817
+ // because data moved, not because anyone asked, so there is no user for RLS
1818
+ // to scope to — it runs in the same system tier as migrations and the
1819
+ // external-source poll loop. Inheriting the shared per-request identity
1820
+ // would instead run an app's reactor as whichever user happened to write
1821
+ // last, which is worse than running it as nobody.
1822
+ protected override async runReactor(functionPath: string, previousDigest?: string): Promise<{ digest: string; ran: boolean; tables: readonly string[] } | undefined> {
1823
+ const registered = LUNORA_FUNCTIONS[functionPath];
1824
+
1825
+ if (!registered || registered.kind !== "mutation") {
1826
+ return undefined;
1827
+ }
1828
+
1829
+ this.ensureMigrated();
1830
+
1831
+ const footprint = createReadFootprint();
1832
+ const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), onRead: footprint.onRead, onReadRange: footprint.onReadRange, trusted: true });
1833
+ const outcome = (await this.runInTransaction(async () => registered.handler(ctx, { previousDigest } as unknown as Record<string, unknown>))) as {
1834
+ digest: string;
1835
+ ran: boolean;
1836
+ };
1837
+
1838
+ // A reactor IS a mutation, so its ctx carries the deferred-delete queue
1839
+ // and its transaction has just committed. Without this the queue would
1840
+ // die with \`ctx\` and the objects would leak with nothing to find: no
1841
+ // error, no warning, no failed request — a reactor that reaps orphaned
1842
+ // rows is a textbook use of one.
1843
+ await this.deferPastResponse(flushDeferredDeletes(ctx));
1844
+
1845
+ return { digest: outcome.digest, ran: outcome.ran, tables: [...footprint.tables] };
1846
+ }
1847
+
1848
+
1849
+ protected override tableRefs(table: string): Record<string, string> | undefined {
1850
+ return LUNORA_TABLE_REFS[table];
1851
+ }
1852
+
1853
+ protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> {
1854
+ return LUNORA_TABLE_INDEXES[table] ?? [];
1855
+ }
1856
+
1857
+ protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> {
1858
+ return LUNORA_TTL_SWEEPS;
1859
+ }
1860
+
1861
+ protected override tableColumns(
1862
+ table: string,
1863
+ ): Array<{ bucket?: string; enumValues?: string[]; isStorage?: boolean; name: string; nullable?: boolean; optional: boolean; pk?: boolean; ref?: string; type: string }> {
1864
+ return LUNORA_TABLE_COLUMNS[table] ?? [];
1865
+ }
1866
+
1867
+ protected override storageColumns(): Record<string, string[]> {
1868
+ return LUNORA_STORAGE_COLUMNS;
1869
+ }
1870
+
1871
+ protected override rlsMetadata(): RlsPoliciesResult {
1872
+ return LUNORA_RLS_METADATA;
1873
+ }
1874
+
1875
+ protected override maskMetadata(): MaskPoliciesResult {
1876
+ return LUNORA_MASK_METADATA;
1877
+ }
1878
+
1879
+ protected override storageRulesMetadata(): StorageRulesResult {
1880
+ return LUNORA_STORAGE_RULES;
1881
+ }
1882
+
1883
+ protected override studioFeatures(): StudioFeaturesResult {
1884
+ return LUNORA_STUDIO_FEATURES;
1885
+ }
1886
+ ${W.evaluateOverride}${W.subscriptionOverride}${Lt}${Et}
1887
+ protected override advisories(): AdvisoryFinding[] {
1888
+ return LUNORA_ADVISORIES;
1889
+ }
1890
+
1891
+ protected override advisorProcedures(): AdvisorProcedure[] {
1892
+ return LUNORA_ADVISOR_PROCEDURES;
1893
+ }
1894
+
1895
+ ${on}
1896
+
1897
+ protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
1898
+ this.ensureMigrated();
1899
+
1900
+ // Falls back to the framework's reserved re-projection backfill
1901
+ // (\`__lunora_reproject__<table>\`), which rewrites rows whose
1902
+ // v.bigint()/v.bytes() columns are still stored in the pre-projection
1903
+ // tagged form. Built here rather than at module scope because it
1904
+ // needs this shard's \`sql\` handle to tell a legacy row from a
1905
+ // current one.
1906
+ const migration = LUNORA_MIGRATIONS[args.id] ?? buildReprojectionMigration(args.id, schema as unknown as SchemaLike, this.sql as SqlExec);
1907
+
1908
+ if (!migration) {
1909
+ throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
1910
+ }
1911
+
1912
+ ${Y()}
1913
+
1914
+ return runDataMigration({
1915
+ batchSize: args.batchSize,
1916
+ direction: args.direction,
1917
+ dryRun: args.dryRun,
1918
+ maxBatches: args.maxBatches,
1919
+ migration: migration as unknown as DataMigrationLike,
1920
+ // Flush after each batch so live migrationStatus subscribers see
1921
+ // progress mid-run (the base method records the reserved state
1922
+ // table the raw-SQL progress write is invisible to the tracker).
1923
+ onBatch: () => this.flushMigrationProgress(),
1924
+ sql: this.sql as SqlExec,
1925
+ writer,
1926
+ });
1927
+ }
1928
+
1929
+ protected override async runShardWrite(args: RunShardWriteArgs, headroom?: TransactionHeadroomTracker): Promise<RunShardWriteResult> {
1930
+ const definition = (schema as unknown as SchemaLike).tables[args.table];
1931
+
1932
+ if (!definition) {
1933
+ throw new LunoraError("UNKNOWN_TABLE", \`unknown table: \${args.table}\`, { status: 404 });
1934
+ }
1935
+
1936
+ // \`.global()\` tables live in D1, not this DO's SQLite — editing them
1937
+ // here would corrupt nothing but would fail confusingly, so reject up
1938
+ // front with a clear code the studio can surface.
1939
+ if (definition.shardMode?.kind === "global") {
1940
+ throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", \`table "\${args.table}" is global; edit it through D1, not the shard\`, { status: 400 });
1941
+ }
1942
+
1943
+ this.ensureMigrated();
1944
+
1945
+ ${Y("headroom ?? this.transactionHeadroom()")}
1946
+
1947
+ if (args.op === "insert") {
1948
+ const id = await writer.insert(args.table, args.doc ?? {});
1949
+
1950
+ return { id, op: "insert" };
1951
+ }
1952
+
1953
+ // Every by-id op PINS \`args.table\`. Unpinned, \`locateRowById\` probes
1954
+ // every non-global table for the id, so a request naming table A with an
1955
+ // id belonging to table B locates and mutates B's row — the by-id IDOR
1956
+ // the per-table \`ctx.db.<table>\` facade pins against. Pinning also stops
1957
+ // an absent row falling through to the \`.global()\` D1 twin, though that
1958
+ // branch is already unreachable here: \`adminWriter\` is built without a
1959
+ // \`globalDb\`, so a miss throws \`NOT_FOUND\` either way.
1960
+ if (args.op === "delete") {
1961
+ await writer.delete(args.id ?? "", args.table);
1962
+
1963
+ return { id: args.id ?? null, op: "delete" };
1964
+ }
1965
+
1966
+ if (args.op === "replace") {
1967
+ await writer.replace(args.id ?? "", args.doc ?? {}, args.table);
1968
+
1969
+ return { id: args.id ?? null, op: "replace" };
1970
+ }
1971
+
1972
+ await writer.patch(args.id ?? "", args.doc ?? {}, args.table);
1973
+
1974
+ return { id: args.id ?? null, op: "patch" };
1975
+ }
1976
+
1977
+ // The base \`ShardDO\` cannot build a schema-aware writer, so its
1978
+ // \`runShardExport\`/\`runShardImport\` return \`[]\` and \`{inserted:{}}\`.
1979
+ // Those are success-shaped: an empty export is what a correct export of
1980
+ // an empty shard looks like, so a backup of a populated sharded schema
1981
+ // reported success and wrote nothing, and an import reported success and
1982
+ // dropped every row. Overriding both here is what makes the two admin
1983
+ // RPCs real for a \`.shardBy()\` table.
1984
+ //
1985
+ // NOTE: the admin export RPC is not paginated — \`parseExportShardArgs\`
1986
+ // takes \`tables\`/\`batchSize\` but no cursor, and the coordinator issues
1987
+ // one call per shard — so the rows are collected into a single response.
1988
+ // \`batchSize\` bounds the SQLite scan page, not the reply. A shard holding
1989
+ // more rows than fit in the DO's memory budget will therefore fail the
1990
+ // export rather than stream it. That is a loud failure where the bug this
1991
+ // replaces was a silent empty one, but a cursor on the RPC is what makes
1992
+ // this a complete backup path for large shards.
1993
+ protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
1994
+ this.ensureMigrated();
1995
+
1996
+ ${Y()}
1997
+
1998
+ const rows: ExportRow[] = [];
1999
+
2000
+ // \`exportShardRows\` walks in keyset batches so a large table does not
2001
+ // materialize at once inside the generator; the admin RPC's response
2002
+ // is a single array, so it is collected here rather than streamed.
2003
+ for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, { batchSize: args.batchSize, tables: args.tables })) {
2004
+ rows.push(row);
2005
+ }
2006
+
2007
+ return rows;
2008
+ }
2009
+
2010
+ protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
2011
+ this.ensureMigrated();
2012
+
2013
+ ${Y()}
2014
+
2015
+ // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
2016
+ // database's \`_id\`s carry across verbatim and every foreign key
2017
+ // referencing them stays valid without a second remapping pass.
2018
+ return importShardRows(writer, schema as unknown as SchemaLike, { rows: args.rows, startLine: args.startLine });
2019
+ }
2020
+
2021
+ protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
2022
+ this.ensureMigrated();
2023
+
2024
+ ${Y()}
2025
+
2026
+ // \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2027
+ // but the shard writer from \`createShardCtxDb\` always defines it.
2028
+ if (!writer.rankBefore) {
2029
+ throw new LunoraError("NOT_IMPLEMENTED", "rankBefore is unavailable on the shard writer", { status: 500 });
2030
+ }
2031
+
2032
+ return writer.rankBefore(args.table, args.index, {
2033
+ partitionKey: args.partitionKey,
2034
+ rowId: args.rowId,
2035
+ sortValues: args.sortValues,
2036
+ });
2037
+ }
2038
+
2039
+ protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
2040
+ this.ensureMigrated();
2041
+
2042
+ ${Y()}
2043
+
2044
+ // \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
2045
+ // but the shard writer from \`createShardCtxDb\` always defines it. The sort
2046
+ // directions live in the schema's rankIndex, so the shard reads them itself;
2047
+ // \`args.directions\` is only the coordinator's comparator hint and isn't forwarded.
2048
+ if (!writer.rankPageRows) {
2049
+ throw new LunoraError("NOT_IMPLEMENTED", "rankPage is unavailable on the shard writer", { status: 500 });
2050
+ }
2051
+
2052
+ return writer.rankPageRows(args.table, args.index, {
2053
+ after: args.after,
2054
+ cursor: args.cursor,
2055
+ partitionKey: args.partitionKey,
2056
+ take: args.take,
2057
+ });
2058
+ }
2059
+
2060
+ protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
2061
+ this.ensureMigrated();
2062
+
2063
+ ${Y()}
2064
+
2065
+ await applyCdcChanges(writer, args.changes);
2066
+
2067
+ return { applied: args.changes.length };
2068
+ }
2069
+
2070
+ protected override ensureMigrated(): void {
2071
+ if (this.migrated) {
2072
+ return;
2073
+ }
2074
+
2075
+ runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${M} });
2076
+ this.migrated = true;
2077
+ }
2078
+ ${Ke?`
2079
+ protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
2080
+ // Migrations create the fts5 companions; without them every backfill
2081
+ // statement would raise "no such table" on a shard that has never
2082
+ // served a request.
2083
+ this.ensureMigrated();
2084
+
2085
+ return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
2086
+ }
2087
+ `:""}
2088
+ private buildCtx(options: { functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: { identity?: Record<string, unknown>; userId?: string }; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
2089
+ const env = (this.env ?? {}) as Record<string, unknown>;
2090
+ // When the caller threads an explicit identity (subscription seed /
2091
+ // refresh — both run in deferred/interleaved contexts), use it by
2092
+ // value and NEVER read the shared per-request identity field, which a
2093
+ // concurrent RPC may have re-set. Otherwise (the synchronous RPC
2094
+ // dispatch path) fall back to the per-request fields as before.
2095
+ const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
2096
+ const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
2097
+ ${nn}${de}${fn}${he}${me}${Ce}${Fe}
2098
+ // \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
2099
+ // reaches through, and pending jobs live in the SchedulerDO — nothing the
2100
+ // CDC changelog records — so reading them must forfeit a delta resume.
2101
+ // The scheduler's own \`runAfter\`/\`runAt\`/\`cancel\` are writes and stay unstamped.
2102
+ const scheduler = markUnvouchableReads((config.scheduler?.(env) ?? schedulerStub) as SchedulerLike, options.onRead, ["get", "list"]);
2103
+ // Build the storage adapter once and share it between \`ctx.storage\`
2104
+ // and \`ctx.db.system._storage\` so both read the same R2 binding. The
2105
+ // \`storageStub\` fallback satisfies SystemReaderStorageLike structurally
2106
+ // (its \`list\`/\`getMetadata\` throw the "no storage configured" error).
2107
+ //
2108
+ // Wrapped BEFORE the split so both consumers share one stamping facade.
2109
+ // Only the methods that actually reach R2 are stamped: \`getUrl\` and
2110
+ // \`getSignedUrl\` build a URL from the configured base (and an HMAC) and
2111
+ // read nothing, and they are what handlers overwhelmingly call — stamping
2112
+ // them would forfeit resumes for a dependency that cannot move the result.
2113
+ // \`bucket\` IS stamped: it hands back a sub-facade this wrapper does not
2114
+ // reach, so the selection is the last point at which the read can be seen.
2115
+ const storage = markUnvouchableReads(asBucketStorage(config.storage?.(env) ?? storageStub) as SystemReaderStorageLike, options.onRead, [
2116
+ "bucket",
2117
+ "download",
2118
+ "getMetadata",
2119
+ "list",
2120
+ ]);
2121
+ // \`ctx.storage.deleteAfterCommit(key)\`, on every dispatch that can host
2122
+ // a MUTATION handler — which is not only a mutation dispatch:
2123
+ // \`ctx.runMutation\` hands the CALLER's ctx to the callee, so a mutation
2124
+ // reached from an action runs on the action's ctx. Wrapping mutations
2125
+ // alone made that composition throw a bare TypeError on a method the
2126
+ // handler's own type promises. Queries stay unwrapped: they cannot host
2127
+ // one, and their ctx is built on the hot subscription path.
2128
+ //
2129
+ // Every dispatch wrapped here also flushes (see \`handleRpc\` and
2130
+ // \`runReactor\`) — a queue nothing drains leaks silently, which is worse
2131
+ // than not having the method at all.
2132
+ //
2133
+ // Wrapped OUTSIDE the read-stamping facade so \`bucket(name)\` still
2134
+ // resolves through it and stays stamped, and applied only to
2135
+ // \`ctx.storage\` so \`ctx.db.system._storage\` (which shares the adapter
2136
+ // above) is untouched.
2137
+ const contextKind = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind;
2138
+ const contextStorage = contextKind === "mutation" || contextKind === "action" ? withDeferredDeletes(storage) : storage;
2139
+ // \`ctx.log\`: the DO base builds the attributed logger (structured
2140
+ // fields + \`.with(...)\` child + trace correlation) and routes each call
2141
+ // to the optional \`observability\` sink. It also buffers the line (studio
2142
+ // Logs panel) and emits a structured console event the dev-server formats.
2143
+ //
2144
+ // Resolved BEFORE \`ctx.db\` below, because the database is wrapped in
2145
+ // auto-instrumentation that needs the sink, the trace anchor, and the
2146
+ // dispatch's wide-event handle.
2147
+ const observability = config.observability?.(env);
2148
+ const logFunctionPath = options.functionPath ?? "";
2149
+ const log = this.makeLogger(logFunctionPath, observability);
2150
+ const traceAnchor = this.resolveDispatchAnchor(Boolean(options.identity));
2151
+
2152
+ // \`ctx.span\`: the handle onto the DISPATCH's own span — the wide-event
2153
+ // surface. Attributes attached here accumulate for the whole request
2154
+ // and are folded into the one span it already emits, instead of
2155
+ // becoming N separate log lines. Shares \`traceAnchor\` with \`ctx.trace\`
2156
+ // so both write to the same trace.
2157
+ const span = this.makeDispatchSpan(traceAnchor, observability);
2158
+
2159
+ ${ln} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
2160
+ // adds aggregate counters (call count, total time, per-operation
2161
+ // breakdown) to the wide event rather than a span per call, so a
2162
+ // handler making hundreds of queries stays readable. See
2163
+ // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
2164
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${rn}), logFunctionPath, traceAnchor, observability);
2165
+ ${gn}${Be}
2166
+
2167
+ // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
2168
+ // The trace anchor is threaded explicitly for the same reason \`identity\`
2169
+ // is — a deferred caller (a subscription re-run) must not inherit the
2170
+ // writing mutation's trace from the shared per-request field.
2171
+ const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
2172
+ const metrics = this.makeMetrics(logFunctionPath, observability);
2173
+ ${yn}
2174
+ // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
2175
+ // captured ONCE so the whole handler body sees a single stable value.
2176
+ // Query/mutation handlers must be deterministic (they may be re-run on
2177
+ // OCC retry / subscription re-eval), so they must read time through
2178
+ // \`ctx.now\` instead of \`Date.now()\` — the \`nondeterministic_query_mutation\`
2179
+ // advisor flags the latter. Actions may still use ambient \`Date.now()\`.
2180
+ const now = Date.now();
2181
+
2182
+ const ctx: Record<string, unknown> = {
2183
+ auth: {
2184
+ getIdentity: async () => identity ?? null,
2185
+ userId: userId ?? null,
2186
+ },
2187
+ db,
2188
+ // Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
2189
+ // \`traceparent\` propagation, so time spent in a downstream service
2190
+ // is visible and its spans join this trace. Degrades to the bare
2191
+ // global when no sink is configured.
2192
+ fetch: this.makeFetch(logFunctionPath, traceAnchor, observability),
2193
+ ip: this.getCurrentIp(),
2194
+ log,
2195
+ metrics,
2196
+ now,${sn}
2197
+ scheduler,
2198
+ span,
2199
+ storage: contextStorage,
2200
+ trace,${an}${Oe}${bn}${qe}${_e}${De}${Le}${Me}
2201
+ };
2202
+ ${kn}${wn}
2203
+ ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
2204
+ ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
2205
+ // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
2206
+ // its OWN context, built without the subscription's read-footprint
2207
+ // hooks — so its reads never enter this subscription's footprint and a
2208
+ // write to the tables it touched does not re-run us. Everything else is
2209
+ // inherited: \`functionPath\` (log/metric attribution), \`headroom\` (the
2210
+ // sub-query must not escape this dispatch's resource ceiling),
2211
+ // \`scope\` (the reactive-cache capture — an untracked sub-query's reads
2212
+ // must still be deps of the entry the OUTER query is memoized as, or
2213
+ // the memo goes stale), and — load-bearing — the identity BY VALUE. Omitting identity would let \`buildCtx\` fall
2214
+ // back to the shared per-request fields, which a concurrent RPC may
2215
+ // have re-set, and an RLS-scoped sub-query would then read as the wrong
2216
+ // user. A tracked call keeps sharing \`ctx\` exactly as before.
2217
+ ctx.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>, runOptions?: { untracked?: boolean }) =>
2218
+ dispatchRun(
2219
+ "query",
2220
+ reference.__lunoraRef,
2221
+ fnArgs,
2222
+ runOptions?.untracked === true
2223
+ ? this.buildCtx({ functionPath: options.functionPath, headroom: options.headroom, identity: { identity, userId }, scope: options.scope })
2224
+ : ctx,
2225
+ );
2226
+
2227
+ return ctx;
2228
+ }
2229
+ };
2230
+ `},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:A(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:A(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Xe(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},$t=(e,t)=>{const n=se(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},jr=(e,t,n)=>{b(e,"drizzle column name");const r=Xe(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=$t(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},qr=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(b(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${X(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},Wr=(e,t)=>{b(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,s])=>` ${o}: ${jr(o,s,t)},`)].join(`
2231
+ `),r=e.indexes.length>0?`, (t) => ({
2232
+ ${e.indexes.map(o=>qr(o)).join(`
2233
+ `)}
2234
+ })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
2235
+ ${n}
2236
+ }${r});`},Ur=e=>e.typeAnnotation?.includes('Id<"')??!1,Kr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Xe(a);n.add(c.builder),s=s||Ur(c),o=o||$t(a,t)!==void 0}for(const a of i.indexes)r.add(a.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,a)=>i.localeCompare(a)),indexes:[...r].toSorted((i,a)=>i.localeCompare(a)),needsAnyColumn:o,needsId:s}},ct=(e,t=!1)=>{if(e.length===0)return`${S}export {};
2237
+ `;const n=ae(t),r=new Set(e.map(m=>m.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=Kr(e,r),c=[...s,...o].toSorted((m,w)=>m.localeCompare(w)),d=e.map(m=>Wr(m,r)).join(`
2238
+
2239
+ `),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
2240
+ `:"",a?`import type { Id } from "./dataModel.js";
2241
+ `:""].join("");return`${S}import { ${c.join(", ")} } from "${n.serverDrizzle}";
2242
+ ${p}
2243
+ ${d}
2244
+ `},ho=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:_(ct(n,t),Je),shard:_(ct(r,t),Je)}},mo=e=>{const t=new Map;for(const i of e){const a=t.get(i.cron);a?a.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
2245
+ `),r=n.length>0?`
2246
+ ${n}
2247
+ `:"",o=[...t.entries()].map(([i,a])=>{const c=a.map(d=>{const p=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${p}, args: ${JSON.stringify(d.args)} },`}).join(`
2248
+ `);return` ${JSON.stringify(i)}: [
2249
+ ${c}
2250
+ ],`}).join(`
2251
+ `),s=o.length>0?`
2252
+ ${o}
2253
+ `:"";return`${S}/**
2254
+ * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
2255
+ * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
2256
+ * shard; \`workflow\` is a \`WORKFLOW_*\` binding name whose durable workflow is
2257
+ * started fresh per fire. \`args\` are forwarded verbatim (a workflow's become
2258
+ * its \`params\`).
2259
+ */
2260
+ export interface LunoraCronJob {
2261
+ args: Record<string, unknown>;
2262
+ functionPath?: string;
2263
+ name: string;
2264
+ workflow?: string;
2265
+ }
2266
+
2267
+ /**
2268
+ * Deduplicated cron schedules — mirror of wrangler's \`triggers.crons\`. The
2269
+ * Lunora vite plugin keeps \`wrangler.jsonc\` in sync with this array.
2270
+ */
2271
+ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
2272
+
2273
+ /**
2274
+ * Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
2275
+ * looks up \`event.cron\` here and dispatches every job in the list.
2276
+ */
2277
+ export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
2278
+ `},go=e=>{const t=[...e].toSorted((r,o)=>r.name.localeCompare(o.name)).map(r=>{const o=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&o.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&o.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&o.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&o.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${o.join(", ")} },`}).join(`
2279
+ `),n=t.length>0?`
2280
+ ${t}
2281
+ `:"";return`${S}/**
2282
+ * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
2283
+ * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
2284
+ * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
2285
+ * mirrored into Vectorize for filtering.
2286
+ */
2287
+ export interface LunoraVectorIndex {
2288
+ dimensions?: number;
2289
+ field?: string;
2290
+ metadata?: ReadonlyArray<string>;
2291
+ metric?: "cosine" | "dot-product" | "euclidean";
2292
+ name: string;
2293
+ table: string;
2294
+ }
2295
+
2296
+ /**
2297
+ * Static registry of every vector index in the schema, sorted by name.
2298
+ * Vectorize cannot enumerate indexes at runtime, so the worker passes this to
2299
+ * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2300
+ */
2301
+ export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
2302
+ `},fo=e=>[...new Set(e.map(t=>t.cron))];export{eo as A,Rn as C,S as G,Hn as U,no as a,oo as b,io as c,mo as d,co as e,to as f,ho as g,so as h,ao as i,po as j,go as k,lo as l,fo as m,ur as n,uo as o,ro as p};