@lunora/codegen 1.0.0-alpha.81 → 1.0.0-alpha.83

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 (27) hide show
  1. package/dist/index.d.mts +1125 -1074
  2. package/dist/index.d.ts +1125 -1074
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/DEFAULT_TARGET-CH5disA3.mjs +1 -0
  5. package/dist/packem_shared/GENERATED_HEADER-oy7DTIDi.mjs +1 -0
  6. package/dist/packem_shared/{OPENRPC_VERSION-DfKtsdPS.mjs → OPENRPC_VERSION-K3RTK2CP.mjs} +1 -1
  7. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-ZIqaP_TZ.mjs +9 -0
  8. package/dist/packem_shared/SchemaSnapshotParseError-BJkhTEpi.mjs +16 -0
  9. package/dist/packem_shared/{buildOpenApiDocument-D46nZ7D_.mjs → buildOpenApiDocument-Blf3mpIz.mjs} +1 -1
  10. package/dist/packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs +1 -0
  11. package/dist/packem_shared/discover-queries-Bhu9SNsy.mjs +1 -0
  12. package/dist/packem_shared/discoverCrons-DLwFH_K5.mjs +1 -0
  13. package/dist/packem_shared/discoverMaskProcedures-ZewKJLXx.mjs +1 -0
  14. package/dist/packem_shared/{discoverQueries-2A0lbpxV.mjs → discoverQueries-g4qZzLpl.mjs} +1 -1
  15. package/dist/packem_shared/discoverSchema-4nJgoLaJ.mjs +1 -0
  16. package/dist/packem_shared/{emit-CCw5fiXq.mjs → emit-B7IUlWwi.mjs} +371 -248
  17. package/dist/packem_shared/{emitApp-DEHN578T.mjs → emitApp-jRD2D9kI.mjs} +112 -37
  18. package/dist/packem_shared/readPackageDependencies-CogJX1Ia.mjs +1 -0
  19. package/package.json +10 -10
  20. package/dist/packem_shared/DEFAULT_TARGET-BYPEwgZu.mjs +0 -1
  21. package/dist/packem_shared/GENERATED_HEADER-CR3xA8yO.mjs +0 -1
  22. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DjpfF4p7.mjs +0 -12
  23. package/dist/packem_shared/SchemaSnapshotParseError-0KRzSjo4.mjs +0 -14
  24. package/dist/packem_shared/discover-queries-Ctpk9SA-.mjs +0 -1
  25. package/dist/packem_shared/discoverCrons-CwtPaymU.mjs +0 -1
  26. package/dist/packem_shared/discoverMaskProcedures-DQ-4yUUK.mjs +0 -1
  27. package/dist/packem_shared/discoverSchema-DUl8rbP3.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{agentComponent as Ye}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as zt,hashSchemaSnapshot as Xt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{n as S}from"./paths-BmX5O1sG.mjs";const Ze=[{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:`
1
+ import{agentComponent as tt}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as on,hashSchemaSnapshot as sn}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{n as R}from"./paths-BmX5O1sG.mjs";const nt=[{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
2
  /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
3
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
4
  /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
@@ -15,57 +15,57 @@ import{agentComponent as Ye}from"@lunora/agent/component";import{LunoraError as
15
15
  /**
16
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
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"}],Yt=Ze,Zt=new Map(Yt.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),mr=Ze.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),et=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,en=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),tt=e=>e.column!==void 0,tn=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
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"}],ln=nt,dn=new Map(ln.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Or=nt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),rt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,cn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),at=e=>e.column!==void 0,un=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
19
19
  `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
20
20
  `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
21
21
  `;case"null":return`if (${t} !== null) return DEFER;
22
22
  `;default:return`if (typeof ${t} !== "string") return DEFER;
23
- `}},nn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!et.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
24
- `}},Fe=(e,t,n)=>{if(!tt(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(en.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:tn(e.kind,t)};switch(e.kind){case"array":return rn(e,t,n);case"literal":return nn(e,t);case"object":return on(e,t,n);default:return}}},rn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const a=n.next(),o=`__arr${String(a)}`,s=`__i${String(a)}`,i=`__e${String(a)}`,l=Fe(r,i,n);if(!l)return;const u=`if (!Array.isArray(${t})) return DEFER;
23
+ `}},pn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!rt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
24
+ `}},Me=(e,t,n)=>{if(!at(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(cn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:un(e.kind,t)};switch(e.kind){case"array":return hn(e,t,n);case"literal":return pn(e,t);case"object":return mn(e,t,n);default:return}}},hn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const a=n.next(),o=`__arr${String(a)}`,i=`__i${String(a)}`,s=`__e${String(a)}`,l=Me(r,s,n);if(!l)return;const u=`if (!Array.isArray(${t})) return DEFER;
25
25
  const ${o} = new Array(${t}.length);
26
- for (let ${s} = 0; ${s} < ${t}.length; ${s}++) {
27
- const ${i} = ${t}[${s}];
28
- ${l.pre}${o}[${s}] = ${l.out};
26
+ for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
27
+ const ${s} = ${t}[${i}];
28
+ ${l.pre}${o}[${i}] = ${l.out};
29
29
  }
30
- `;return{out:o,pre:u}},an=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||tt(t))return;const{inner:s}=t;if(!s)return;const i=Fe(s,n,r);if(!i)return;const l=r.next(),u=`__has${String(l)}`,p=`__val${String(l)}`,f=`let ${u} = false;
30
+ `;return{out:o,pre:u}},gn=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||at(t))return;const{inner:i}=t;if(!i)return;const s=Me(i,n,r);if(!s)return;const l=r.next(),u=`__has${String(l)}`,p=`__val${String(l)}`,f=`let ${u} = false;
31
31
  let ${p};
32
32
  if (${n} !== undefined) {
33
- ${i.pre}${p} = ${i.out};
33
+ ${s.pre}${p} = ${s.out};
34
34
  ${u} = true;
35
35
  }
36
- `;return{entry:`...(${u} ? { ${a}: ${p} } : {})`,pre:f}}const o=Fe(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},nt=(e,t,n)=>{let r="";const a=[];for(const o of Object.keys(e)){const s=e[o];if(!s)return;const i=an(o,s,t(o),n);if(!i)return;r+=i.pre,a.push(i.entry)}return{entries:a.join(", "),pre:r}},on=(e,t,n)=>{const r=e.shape??{},a=nt(r,l=>`${t}[${JSON.stringify(l)}]`,n);if(!a)return;const o=n.next(),s=`__obj${String(o)}`,i=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
37
- ${a.pre}const ${s} = { ${a.entries} };
38
- `;return{out:s,pre:i}},sn=e=>{let t=0;const n=nt(e,r=>`source[${JSON.stringify(r)}]`,{next:()=>(t+=1,t)});if(n)return`(source) => {
36
+ `;return{entry:`...(${u} ? { ${a}: ${p} } : {})`,pre:f}}const o=Me(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},ot=(e,t,n)=>{let r="";const a=[];for(const o of Object.keys(e)){const i=e[o];if(!i)return;const s=gn(o,i,t(o),n);if(!s)return;r+=s.pre,a.push(s.entry)}return{entries:a.join(", "),pre:r}},mn=(e,t,n)=>{const r=e.shape??{},a=ot(r,l=>`${t}[${JSON.stringify(l)}]`,n);if(!a)return;const o=n.next(),i=`__obj${String(o)}`,s=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
37
+ ${a.pre}const ${i} = { ${a.entries} };
38
+ `;return{out:i,pre:s}},fn=e=>{let t=0;const n=ot(e,r=>`source[${JSON.stringify(r)}]`,{next:()=>(t+=1,t)});if(n)return`(source) => {
39
39
  if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
40
40
  ${n.pre}return { ${n.entries} };
41
- }`},k=`// GENERATED by @lunora/codegen — do not edit.
41
+ }`},v=`// GENERATED by @lunora/codegen — do not edit.
42
42
  // Run \`lunora codegen\` to regenerate.
43
43
 
44
- `,H=(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"},rt=/^[A-Za-z_$][\w$]*$/u,ln=/^[\w./-]+$/u,m=(e,t)=>{if(!rt.test(e))throw new Z("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ee=e=>e.charAt(0).toUpperCase()+e.slice(1),D=e=>rt.test(e)?e:JSON.stringify(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"},cn=e=>{if(e===void 0)return"unknown";if(!et.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},O=e=>{const t=dn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?O(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return m(n,"v.id() table name"),`Id<"${n}">`}case"literal":return cn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([n,r])=>`${D(n)}: ${O(r)}`).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?O(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?O(e.keyType):"string",r=e.valueType?O(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>O(n)).join(" | "):"never";default:return"unknown"}},me=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>{const a=D(n);if(r.kind==="optional"){const o=r.inner?O(r.inner):"unknown";return`${a}?: ${o}`}return`${a}: ${O(r)}`}).join("; ")} }`},un=e=>e.kind==="optional"||!!e.column?.hasDefault,pn=e=>{m(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=a.kind==="optional"&&a.inner?a.inner:a,s=O(o),i=D(r);return un(a)?` ${i}?: ${s};`:` ${i}: ${s};`}).join(`
44
+ `,G=(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"},st=/^[A-Za-z_$][\w$]*$/u,bn=/^[\w./-]+$/u,m=(e,t)=>{if(!st.test(e))throw new Z("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Fe=e=>e.charAt(0).toUpperCase()+e.slice(1),D=e=>st.test(e)?e:JSON.stringify(e),yn={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"},wn=e=>{if(e===void 0)return"unknown";if(!rt.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},C=e=>{const t=yn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?C(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return m(n,"v.id() table name"),`Id<"${n}">`}case"literal":return wn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([n,r])=>it(n,r)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?C(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?C(e.keyType):"string",r=e.valueType?C(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>C(n)).join(" | "):"never";default:return"unknown"}},it=(e,t)=>{const n=D(e);if(t.kind==="optional"){const r=t.inner?C(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${C(t)}`},me=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>it(n,r)).join("; ")} }`},xn=e=>e.kind==="optional"||!!e.column?.hasDefault,kn=e=>{m(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=a.kind==="optional"&&a.inner?a.inner:a,i=C(o),s=D(r);return xn(a)?` ${s}?: ${i};`:` ${s}: ${i};`}).join(`
45
45
  `),n=t?`
46
46
  ${t}
47
47
  `:"";return`export interface Insert_${e.name} {
48
48
  _id?: Id<"${e.name}">;
49
- _creationTime?: number;${n}}`},fr=(e,t=!1)=>{const n=H(t);for(const c of e.tables)m(c.name,"table name");const r=e.tables.map(c=>`"${c.name}"`).join(" | ")||"never",a=e.tables.filter(c=>c.extensionKey===void 0).map(c=>`"${c.name}"`).join(" | ")||"never",o=e.tables.map(c=>{const g=Object.entries(c.shape).map(([x,v])=>{const T=D(x);if(v.kind==="optional"){const N=v.inner?O(v.inner):"unknown";return` ${T}?: ${N};`}return` ${T}: ${O(v)};`}).join(`
49
+ _creationTime?: number;${n}}`},Tr=(e,t=!1)=>{const n=G(t);for(const c of e.tables)m(c.name,"table name");const r=e.tables.map(c=>`"${c.name}"`).join(" | ")||"never",a=e.tables.filter(c=>c.extensionKey===void 0).map(c=>`"${c.name}"`).join(" | ")||"never",o=e.tables.map(c=>{const g=Object.entries(c.shape).map(([k,$])=>{const T=D(k);if($.kind==="optional"){const O=$.inner?C($.inner):"unknown";return` ${T}?: ${O};`}return` ${T}: ${C($)};`}).join(`
50
50
  `),b=g?`
51
51
  ${g}
52
52
  `:"";return`export interface Doc_${c.name} {
53
53
  _id: Id<"${c.name}">;
54
54
  _creationTime: number;${b}}`}).join(`
55
55
 
56
- `),s=e.tables.map(c=>` ${c.name}: Doc_${c.name};`).join(`
57
- `),i=e.tables.map(c=>{const g=c.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
56
+ `),i=e.tables.map(c=>` ${c.name}: Doc_${c.name};`).join(`
57
+ `),s=e.tables.map(c=>{const g=c.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
58
58
  `),l=e.tables.map(c=>{const g=c.searchIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
59
59
  `),u=e.tables.map(c=>{const g=c.rankIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
60
60
  `),p=e.tables.map(c=>{const g=c.shardMode==="global"?"":(c.geoIndexes??[]).map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
61
- `),f=e.vectorIndexes.map(c=>JSON.stringify(c.name)).join(" | ")||"never",y=e.tables.map(c=>pn(c)).join(`
61
+ `),f=e.vectorIndexes.map(c=>JSON.stringify(c.name)).join(" | ")||"never",y=e.tables.map(c=>kn(c)).join(`
62
62
 
63
- `),R=e.tables.map(c=>` ${c.name}: Insert_${c.name};`).join(`
63
+ `),N=e.tables.map(c=>` ${c.name}: Insert_${c.name};`).join(`
64
64
  `),d=e.tables.map(c=>{const g=c.relations.map(b=>(m(b.table,"relation target table"),` ${D(b.name)}: ${b.kind==="one"?"OneRelation":"ManyRelation"}<"${b.table}">;`)).join(`
65
65
  `);return g?` ${c.name}: {
66
66
  ${g}
67
67
  };`:` ${c.name}: {};`}).join(`
68
- `);return`${k}import type {
68
+ `);return`${v}import type {
69
69
  DatabaseReaderFacade as DatabaseReaderFacadeOf,
70
70
  DatabaseWriterFacade as DatabaseWriterFacadeOf,
71
71
  LoadWith as LoadWithOf,
@@ -121,7 +121,7 @@ export type Id<TName extends string> = string & { readonly __table: TName };
121
121
  ${o}
122
122
 
123
123
  export interface DataModel {
124
- ${s}
124
+ ${i}
125
125
  }
126
126
 
127
127
  export type Doc<T extends keyof DataModel> = DataModel[T];
@@ -131,7 +131,7 @@ export type Doc<T extends keyof DataModel> = DataModel[T];
131
131
  * Used by \`TableReader.withIndex()\` to constrain callers to declared names.
132
132
  */
133
133
  export interface IndexNamesByTable {
134
- ${i}
134
+ ${s}
135
135
  }
136
136
 
137
137
  export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
@@ -164,7 +164,7 @@ ${y}
164
164
 
165
165
  /** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
166
166
  export interface InsertModel {
167
- ${R}
167
+ ${N}
168
168
  }
169
169
 
170
170
  export type Insert<T extends keyof DataModel> = InsertModel[T];
@@ -234,11 +234,11 @@ export interface OrmWriter extends OrmReader {
234
234
  replace: <T extends keyof DataModel>(table: T, id: Id<T>) => OrmReplaceBuilder<T>;
235
235
  update: <T extends keyof DataModel>(table: T, id: Id<T>) => OrmUpdateBuilder<T>;
236
236
  }
237
- `},hn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,gn=/^(?:\.\.?\/)*_generated\//u,mn=/\.[A-Za-z]\w*$/u,Me=e=>e.replaceAll(hn,(t,n)=>{const r=n.replace(gn,"./");return`import("${mn.test(r)?r:`${r}.js`}")`}),fn=/import\("@lunora\/(?<pkg>client|do|runtime|server|values)(?<subpath>\/[^"]*)?"\)/gu,at=(e,t)=>t?e.replaceAll(fn,(n,r,a)=>`import("lunorash/${r}${a??""}")`):e,qe=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),bn=e=>e.output===void 0||e.output.kind==="any"?e.returnType:O(e.output),ze=e=>{const t=new Map;for(const r of e){const a=t.get(r.filePath)??[];a.push(r),t.set(r.filePath,a)}const n=([r,a])=>{const o=a.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=me(s.args),l=Me(bn(s));return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${l}>;`}).join(`
238
- `);return` ${D(S(r))}: {
237
+ `},vn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,lt=/^(?:\.\.?\/)*_generated\//u,dt=/\.[A-Za-z]\w*$/u,qe=e=>e.replaceAll(vn,(t,n)=>{const r=n.replace(lt,"./");return`import("${dt.test(r)?r:`${r}.js`}")`}),$n=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Sn=/^(?:\.\.?\/)+/u,Rn=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("/")},Be=(e,t)=>e.replaceAll($n,(n,r)=>{if(lt.test(r.replace(Sn,"")))return n;const a=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",o=`../${Rn(`${a}/${r}`)}`;return`import("${dt.test(o)?o:`${o}.js`}")`}),Nn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],On=new RegExp(String.raw`import\("@lunora/(?<pkg>${Nn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Tn={flags:new Set(["/web"]),platform:new Set},ct=(e,t)=>t?e.replaceAll(On,(n,r,a)=>{const o=Tn[r];return a&&o&&!o.has(a)?n:`import("lunorash/${r}${a??""}")`}):e,je=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),An=e=>e.output===void 0||e.output.kind==="any"?e.returnType:C(e.output),Ze=e=>{const t=new Map;for(const r of e){const a=t.get(r.filePath)??[];a.push(r),t.set(r.filePath,a)}const n=([r,a])=>{const o=a.toSorted((i,s)=>i.exportName.localeCompare(s.exportName)).map(i=>{const s=me(i.args),l=qe(Be(An(i),i.filePath));return` ${i.exportName}: FunctionReference<"${i.kind}", ${s}, ${l}>;`}).join(`
238
+ `);return` ${D(R(r))}: {
239
239
  ${o}
240
240
  };`};return[...t.entries()].toSorted(([r],[a])=>r.localeCompare(a)).map(r=>n(r)).join(`
241
- `)},yn=(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+=`
241
+ `)},Ln=(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+=`
242
242
  /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
243
243
  export interface WorkflowReference<Params = Record<string, unknown>> {
244
244
  readonly isLunoraWorkflow: true;
@@ -246,8 +246,8 @@ export interface WorkflowReference<Params = Record<string, unknown>> {
246
246
  readonly binding: string;
247
247
  readonly name: string;
248
248
  }
249
- `,e.length>0){const a=[...e].toSorted((i,l)=>i.exportName.localeCompare(l.exportName)),o=a.map(i=>` ${i.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${i.exportName}>>;`).join(`
250
- `),s=a.map(i=>` ${i.exportName}: { isLunoraWorkflow: true, binding: ${JSON.stringify(i.bindingName)}, name: ${JSON.stringify(i.exportName)} },`).join(`
249
+ `,e.length>0){const a=[...e].toSorted((s,l)=>s.exportName.localeCompare(l.exportName)),o=a.map(s=>` ${s.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${s.exportName}>>;`).join(`
250
+ `),i=a.map(s=>` ${s.exportName}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.exportName)} },`).join(`
251
251
  `);r+=`
252
252
  /** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
253
253
  export interface WorkflowsRef {
@@ -255,11 +255,11 @@ ${o}
255
255
  }
256
256
 
257
257
  export const workflows: WorkflowsRef = {
258
- ${s}
258
+ ${i}
259
259
  };
260
260
  `,n.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
261
- `)}if(t.length>0){const a=[...t].toSorted((i,l)=>i.exportName.localeCompare(l.exportName)),o=a.map(i=>` ${i.exportName}: WorkflowReference<AgentRunInput>;`).join(`
262
- `),s=a.map(i=>` ${i.exportName}: { isLunoraWorkflow: true, binding: ${JSON.stringify(i.bindingName)}, name: ${JSON.stringify(i.name)} },`).join(`
261
+ `)}if(t.length>0){const a=[...t].toSorted((s,l)=>s.exportName.localeCompare(l.exportName)),o=a.map(s=>` ${s.exportName}: WorkflowReference<AgentRunInput>;`).join(`
262
+ `),i=a.map(s=>` ${s.exportName}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.name)} },`).join(`
263
263
  `);r+=`
264
264
  /** 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 })\`). */
265
265
  export interface AgentsRef {
@@ -267,11 +267,11 @@ ${o}
267
267
  }
268
268
 
269
269
  export const agents: AgentsRef = {
270
- ${s}
270
+ ${i}
271
271
  };
272
272
  `,n.push(`import type { AgentRunInput } from "@lunora/agent";
273
- `)}return{block:r,importLine:n.join("")}},wn=()=>Object.keys(Ye().functions).toSorted((e,t)=>e.localeCompare(t)),ot=e=>new Set(e.filter(t=>S(t.filePath)==="agents").map(t=>t.exportName)),xn=()=>new Set(Object.entries(Ye().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),kn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=ot(t),a=xn(),o=t.find(i=>S(i.filePath)==="agents"&&a.has(i.exportName));if(o)throw new Z("INTERNAL",`@lunora/codegen: "agents:${o.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${o.exportName}" export in ${o.filePath}`);const s=wn().filter(i=>!r.has(i));return s.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
274
- `,lines:s.map(i=>` "agents:${i}": lunoraAgentRuntimeFunctions.${i} as unknown as RegisteredLunoraFunction,`).join(`
273
+ `)}return{block:r,importLine:n.join("")}},Cn=()=>Object.keys(tt().functions).toSorted((e,t)=>e.localeCompare(t)),ut=e=>new Set(e.filter(t=>R(t.filePath)==="agents").map(t=>t.exportName)),In=()=>new Set(Object.entries(tt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Dn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=ut(t),a=In(),o=t.find(s=>R(s.filePath)==="agents"&&a.has(s.exportName));if(o)throw new Z("INTERNAL",`@lunora/codegen: "agents:${o.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${o.exportName}" export in ${o.filePath}`);const i=Cn().filter(s=>!r.has(s));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
274
+ `,lines:i.map(s=>` "agents:${s}": lunoraAgentRuntimeFunctions.${s} as unknown as RegisteredLunoraFunction,`).join(`
275
275
  `),prelude:`
276
276
  /**
277
277
  * The \`@lunora/agent\` runtime component — auto-registered because \`lunora/agents.ts\`
@@ -279,13 +279,13 @@ ${s}
279
279
  * subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
280
280
  */
281
281
  const lunoraAgentRuntimeFunctions = agentComponent().functions;
282
- `}},vn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>S(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";
283
- `,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"}},$n=(e,t)=>{if(e.length===0)return[];const n=ot(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 a of e)a.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${a.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(a=>!n.has(a.exportName))},Sn=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>S(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}))},Rn=e=>{const t=e.filter(s=>s.stream);if(t.length===0)return{block:"",body:""};const n=new Map;for(const s of t){const i=n.get(s.filePath)??[];i.push(s),n.set(s.filePath,i)}const r=[...n.entries()].toSorted(([s],[i])=>s.localeCompare(i)),a=r.map(([s,i])=>{const l=i.map(u=>{const p=Me(u.chunkType??"unknown");return` ${D(u.exportName)}: HttpStreamRef<${p}, ${me(u.searchParams)}, ${me(u.params)}>;`}).join(`
284
- `);return` ${D(S(s))}: {
282
+ `}},_n=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>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";
283
+ `,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"}},En=(e,t)=>{if(e.length===0)return[];const n=ut(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 a of e)a.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${a.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(a=>!n.has(a.exportName))},Pn=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>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}))},Fn=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=new Map;for(const i of t){const s=n.get(i.filePath)??[];s.push(i),n.set(i.filePath,s)}const r=[...n.entries()].toSorted(([i],[s])=>i.localeCompare(s)),a=r.map(([i,s])=>{const l=s.map(u=>{const p=qe(Be(u.chunkType??"unknown",u.filePath));return` ${D(u.exportName)}: HttpStreamRef<${p}, ${me(u.searchParams)}, ${me(u.params)}>;`}).join(`
284
+ `);return` ${D(R(i))}: {
285
285
  ${l}
286
286
  };`}).join(`
287
- `),o=r.map(([s,i])=>{const l=i.map(u=>` ${D(u.exportName)}: { method: ${JSON.stringify(u.method)}, path: ${JSON.stringify(u.path)} },`).join(`
288
- `);return` ${D(S(s))}: {
287
+ `),o=r.map(([i,s])=>{const l=s.map(u=>` ${D(u.exportName)}: { method: ${JSON.stringify(u.method)}, path: ${JSON.stringify(u.path)} },`).join(`
288
+ `);return` ${D(R(i))}: {
289
289
  ${l}
290
290
  },`}).join(`
291
291
  `);return{block:`
@@ -297,15 +297,15 @@ ${a}
297
297
  export const httpStreams: HttpStreamsRef = {
298
298
  ${o}
299
299
  };
300
- `,body:a}},br=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:s=[]}=e,i=H(o),l=[...n.filter($=>$.visibility!=="internal"),...$n(t,n),...Sn(a,n)],u=n.filter($=>$.visibility==="internal"),p=ze(l),f=ze(u),y=Rn(r),R=`${p}
300
+ `,body:a}},Ar=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=G(o),l=[...n.filter(S=>S.visibility!=="internal"),...En(t,n),...Pn(a,n)],u=n.filter(S=>S.visibility==="internal"),p=Ze(l),f=Ze(u),y=Fn(r),N=`${p}
301
301
  ${f}
302
- ${y.body}`,d=qe(R),c=d.length>0?`
302
+ ${y.body}`,d=je(N),c=d.length>0?`
303
303
  import type { ${d.join(", ")} } from "./dataModel.js";
304
304
  `:"",g=p?`
305
305
  ${p}
306
306
  `:"",b=f?`
307
307
  ${f}
308
- `:"",x=yn(s,t),v=`export interface ApiTypes {${g}}
308
+ `:"",k=Ln(i,t),$=`export interface ApiTypes {${g}}
309
309
 
310
310
  export const api = anyApi as unknown as ApiTypes;
311
311
 
@@ -313,10 +313,10 @@ export const api = anyApi as unknown as ApiTypes;
313
313
  export interface InternalApiTypes {${b}}
314
314
 
315
315
  export const internal = anyApi as unknown as InternalApiTypes;
316
- ${x.block}${y.block}`,T=[...v.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],N=T.length>0?`import type { ${T.join(", ")} } from "${i.client}";
317
- `:"";return at(`${k}import { anyApi } from "${i.serverTypes}";
318
- ${N}${x.importLine}${c}
319
- ${v}`,o)},yr=e=>e?`${k}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
316
+ ${k.block}${y.block}`,T=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],O=T.length>0?`import type { ${T.join(", ")} } from "${s.client}";
317
+ `:"";return ct(`${v}import { anyApi } from "${s.client}";
318
+ ${O}${k.importLine}${c}
319
+ ${$}`,o)},Lr=e=>e?`${v}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
320
320
  import type { SeedClient, SeedClientOptions } from "@lunora/seed";
321
321
 
322
322
  import schema from "../schema.js";
@@ -333,8 +333,8 @@ import type { InsertModel } from "./dataModel.js";
333
333
  * const { posts } = await seed.posts((x) => x([10, 20]));
334
334
  */
335
335
  export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
336
- `:"",wr=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=H(n),a=l=>l.table===void 0?"Row":`Doc<${JSON.stringify(l.table)}> & Row`,o=e.map(l=>{m(l.exportName,"shape export name");const u=a(l),p=me(l.args),f=Object.keys(l.args).length>0,y=f?` args: ${p};`:` args?: ${p};`,R=f?`(args: ${p}) => void`:`(args?: ${p}) => void`,d=`${l.exportName}CollectionOptions`;return`/** Options for the \`${l.exportName}\` shape binding. */
337
- export interface ${Ee(d)} {
336
+ `:"",Cr=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=G(n),a=l=>l.table===void 0?"Row":`Doc<${JSON.stringify(l.table)}> & Row`,o=e.map(l=>{m(l.exportName,"shape export name");const u=a(l),p=me(l.args),f=Object.keys(l.args).length>0,y=f?` args: ${p};`:` args?: ${p};`,N=f?`(args: ${p}) => void`:`(args?: ${p}) => void`,d=`${l.exportName}CollectionOptions`;return`/** Options for the \`${l.exportName}\` shape binding. */
337
+ export interface ${Fe(d)} {
338
338
  ${y}
339
339
  /**
340
340
  * Share the optimistic-overlay gate with other collections + mutators on this
@@ -359,7 +359,7 @@ ${y}
359
359
  * \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
360
360
  * \`scope\` to re-point the subscription.
361
361
  */
362
- export const ${l.exportName}CollectionOptions = (options: ${Ee(d)}): LunoraCollectionOptions<${u}> =>
362
+ export const ${l.exportName}CollectionOptions = (options: ${Fe(d)}): LunoraCollectionOptions<${u}> =>
363
363
  lunoraCollectionOptions<${u}>({
364
364
  client: options.client,
365
365
  ...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
@@ -372,22 +372,22 @@ export const ${l.exportName}CollectionOptions = (options: ${Ee(d)}): LunoraColle
372
372
 
373
373
  /** Live collection for the \`${l.exportName}\` shape, with its sync controls. */
374
374
  export const ${l.exportName}Collection = (
375
- options: ${Ee(d)},
376
- ): { checkpoints: CheckpointRegistry; collection: Collection<${u}, string>; scope: ${R} } => {
375
+ options: ${Fe(d)},
376
+ ): { checkpoints: CheckpointRegistry; collection: Collection<${u}, string>; scope: ${N} } => {
377
377
  const { checkpoints, config, scope } = ${l.exportName}CollectionOptions(options);
378
378
 
379
379
  return { checkpoints, collection: createCollection(config), scope };
380
380
  };`}).join(`
381
381
 
382
- `),s=qe(o),i=s.length>0?`import type { ${s.join(", ")} } from "./dataModel.js";
383
- `:"";return`${k}import type { LunoraClient, SubscriptionError } from "${r.client}";
382
+ `),i=je(o),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
383
+ `:"";return`${v}import type { LunoraClient, SubscriptionError } from "${r.client}";
384
384
  import { lunoraCollectionOptions } from "@lunora/db/collections";
385
385
  import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
386
386
  import type { Collection } from "@tanstack/db";
387
387
  import { createCollection } from "@tanstack/db";
388
- ${i}
388
+ ${s}
389
389
  ${o}
390
- `},Nn=(e,t)=>`lunora_${S(e)}_${String(t)}`,On=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
390
+ `},Mn=(e,t)=>`lunora_${R(e)}_${String(t)}`,qn=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
391
391
  const registered = LUNORA_FUNCTIONS[functionPath];
392
392
 
393
393
  if (!registered) {
@@ -395,30 +395,30 @@ ${o}
395
395
  }
396
396
 
397
397
  return (await registered.handler(context, args ?? {})) as R;
398
- };`,Tn=(e,t,n=[],r=[])=>{const a=new Map,o=d=>{a.has(d)||a.set(d,Nn(d,a.size))};for(const d of e)o(d.filePath);for(const d of t)o(d.filePath);for(const d of n)o(d.filePath);for(const d of r)o(d.filePath);const s=[...a.entries()].map(([d,c])=>{if(!ln.test(d))throw new Z("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(d)}`);return`import * as ${c} from "../${d}.js";`}).join(`
399
- `),i=e.map(d=>` "${S(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
398
+ };`,Bn=(e,t,n=[],r=[])=>{const a=new Map,o=d=>{a.has(d)||a.set(d,Mn(d,a.size))};for(const d of e)o(d.filePath);for(const d of t)o(d.filePath);for(const d of n)o(d.filePath);for(const d of r)o(d.filePath);const i=[...a.entries()].map(([d,c])=>{if(!bn.test(d))throw new Z("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(d)}`);return`import * as ${c} from "../${d}.js";`}).join(`
399
+ `),s=e.map(d=>` "${R(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
400
400
  `),l=t.map(d=>` ${JSON.stringify(d.id)}: ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredDataMigration,`).join(`
401
- `),u=n.map(d=>` "${S(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
401
+ `),u=n.map(d=>` "${R(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
402
402
  `),p=r.map(d=>` "${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredShape,`).join(`
403
- `),f=n.map(d=>`${S(d.filePath)}:${d.exportName}`),y=[i,u].filter(d=>d.length>0).join(`
404
- `),R=e.map(d=>{if(d.lifecycle||Object.keys(d.args).length===0)return;const c=sn(d.args);return c===void 0?void 0:`installCompiledValidatorMap(${a.get(d.filePath)??""}.${d.exportName}.args, ${c});`}).filter(d=>d!==void 0).join(`
403
+ `),f=n.map(d=>`${R(d.filePath)}:${d.exportName}`),y=[s,u].filter(d=>d.length>0).join(`
404
+ `),N=e.map(d=>{if(d.lifecycle||Object.keys(d.args).length===0)return;const c=fn(d.args);return c===void 0?void 0:`installCompiledValidatorMap(${a.get(d.filePath)??""}.${d.exportName}.args, ${c});`}).filter(d=>d!==void 0).join(`
405
405
  `);return{dispatchBody:y.length>0?`
406
406
  ${y}
407
- `:"",importBlock:s.length>0?`${s}
407
+ `:"",importBlock:i.length>0?`${i}
408
408
 
409
- `:"",installBlock:R,migrationBody:l.length>0?`
409
+ `:"",installBlock:N,migrationBody:l.length>0?`
410
410
  ${l}
411
411
  `:"",mutatorPaths:f,shapeBody:p.length>0?`
412
412
  ${p}
413
- `:""}},An=e=>{const t=new Map;for(const a of e){const o=t.get(a.filePath)??[];o.push(a),t.set(a.filePath,o)}const n=[...t.entries()].toSorted(([a],[o])=>a.localeCompare(o)),r=n.map(([a,o])=>{const s=o.map(i=>{const l=me(i.args),u=l==="{}"?"?":"",p=Me(i.returnType);return i.kind==="stream"?` ${i.exportName}: (args${u}: ${l}) => Promise<AsyncIterable<${p}>>;`:` ${i.exportName}: (args${u}: ${l}) => Promise<${p}>;`}).join(`
414
- `);return` ${D(S(a))}: {
415
- ${s}
416
- };`}).join(`
417
- `);return{implementation:n.map(([a,o])=>{const s=S(a),i=o.map(l=>` ${l.exportName}: (args) => callRegistered(context, "${s}:${l.exportName}", args),`).join(`
418
- `);return` ${D(s)}: {
413
+ `:""}},jn=e=>{const t=new Map;for(const a of e){const o=t.get(a.filePath)??[];o.push(a),t.set(a.filePath,o)}const n=[...t.entries()].toSorted(([a],[o])=>a.localeCompare(o)),r=n.map(([a,o])=>{const i=o.map(s=>{const l=me(s.args),u=l==="{}"?"?":"",p=qe(Be(s.returnType,s.filePath));return s.kind==="stream"?` ${s.exportName}: (args${u}: ${l}) => Promise<AsyncIterable<${p}>>;`:` ${s.exportName}: (args${u}: ${l}) => Promise<${p}>;`}).join(`
414
+ `);return` ${D(R(a))}: {
419
415
  ${i}
416
+ };`}).join(`
417
+ `);return{implementation:n.map(([a,o])=>{const i=R(a),s=o.map(l=>` ${l.exportName}: (args) => callRegistered(context, "${i}:${l.exportName}", args),`).join(`
418
+ `);return` ${D(i)}: {
419
+ ${s}
420
420
  },`}).join(`
421
- `),types:r}},Ln=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=a.kind==="optional"&&a.inner?a.inner:a;o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},xr=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:s=!1,hasFlags:i=!1,hasHyperdrive:l=!1,hasImages:u=!1,hasKv:p=!1,hasNotify:f=!1,hasPayments:y=!1,hasPipelines:R=!1,hasR2sql:d=!1,hasX402:c=!1,identity:g,queues:b=[],schema:x,storageRuleBuckets:v=[],useUmbrella:T=!1,workflows:N=[]}={})=>{const $=H(T),w=Ln(x??{tables:[]},v).map(h=>JSON.stringify(h)).join(" | "),E=a?`import type { LunoraAi } from "@lunora/ai";
421
+ `),types:r}},Wn=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=a.kind==="optional"&&a.inner?a.inner:a;o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},Ir=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasFlags:s=!1,hasHyperdrive:l=!1,hasImages:u=!1,hasKv:p=!1,hasNotify:f=!1,hasPayments:y=!1,hasPipelines:N=!1,hasR2sql:d=!1,hasX402:c=!1,identity:g,queues:b=[],schema:k,storageRuleBuckets:$=[],useUmbrella:T=!1,workflows:O=[]}={})=>{const S=G(T),x=Wn(k??{tables:[]},$).map(h=>JSON.stringify(h)).join(" | "),P=a?`import type { LunoraAi } from "@lunora/ai";
422
422
  `:"",ee=a?`
423
423
  readonly ai: LunoraAi;`:"",F=y?`import type { LunoraPayment } from "@lunora/payment";
424
424
  `:"",te=y?`
@@ -429,11 +429,11 @@ ${i}
429
429
  readonly containers: {${t.map(h=>`
430
430
  readonly ${h.exportName}: ContainerAccessor;`).join("")}
431
431
  };`:"",L=[...a?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(h=>(m(h.bindingName,`container binding "${h.bindingName}"`),` /** Durable Object namespace for the \`${h.exportName}\` container. */
432
- readonly ${h.bindingName}?: unknown;`)),...N.map(h=>(m(h.bindingName,`workflow binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` workflow. */
432
+ readonly ${h.bindingName}?: unknown;`)),...O.map(h=>(m(h.bindingName,`workflow binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` workflow. */
433
433
  readonly ${h.bindingName}?: unknown;`)),...b.map(h=>(m(h.bindingName,`queue binding "${h.bindingName}"`),` /** Queue producer binding for the \`${h.exportName}\` queue. */
434
434
  readonly ${h.bindingName}?: unknown;`)),...e.map(h=>(m(h.bindingName,`agent binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` agent. */
435
435
  readonly ${h.bindingName}?: unknown;`))].join(`
436
- `),_=`
436
+ `),I=`
437
437
 
438
438
  /**
439
439
  * This project's Cloudflare bindings, as far as codegen can discover them from
@@ -451,21 +451,21 @@ ${L}`:""}
451
451
  }
452
452
 
453
453
  /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
454
- export type Env = CloudflareBindings;`,M=(h,_e)=>_e?Zt.get(h)?.field??"":"",re=M("kv",p),ae=M("analytics",o),xe=M("hyperdrive",l),ke=M("browser",s),ve=M("images",u),oe=M("pipelines",R),K=M("r2sql",d),P=(x?.vectorIndexes.length??0)>0,Q=P?' | "vectors"':"",X=P?`
455
- readonly vectors: VectorSearch<VectorIndexName>;`:"",ie=P?`
456
- readonly vectors: VectorSearchReader<VectorIndexName>;`:"",J=P?`import type { VectorSearch, VectorSearchReader } from "${$.server}";
454
+ export type Env = CloudflareBindings;`,M=(h,_e)=>_e?dn.get(h)?.field??"":"",re=M("kv",p),ae=M("analytics",o),ke=M("hyperdrive",l),ve=M("browser",i),$e=M("images",u),oe=M("pipelines",N),K=M("r2sql",d),E=(k?.vectorIndexes.length??0)>0,Q=E?' | "vectors"':"",X=E?`
455
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",se=E?`
456
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",H=E?`import type { VectorSearch, VectorSearchReader } from "${S.server}";
457
457
  import type { VectorIndexName } from "./dataModel.js";
458
458
  `:"",j=r?`
459
459
  /** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
460
- readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",W=i?`
460
+ readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",W=s?`
461
461
  /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
462
- readonly flags: import("${$.flags}").LunoraFlags;`:"",U=f?`
462
+ readonly flags: import("${S.flags}").LunoraFlags;`:"",U=f?`
463
463
  /** 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. */
464
464
  readonly notify: import("@lunora/notify").LunoraNotify;
465
465
  /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
466
- readonly push: import("@lunora/notify").LunoraPush;`:"",q=N.length>0,Y=q?`import type { WorkflowHandle } from "@lunora/workflow";
466
+ readonly push: import("@lunora/notify").LunoraPush;`:"",q=O.length>0,Y=q?`import type { WorkflowHandle } from "@lunora/workflow";
467
467
  import type * as lunoraWorkflowDefinitions from "../workflows.js";
468
- `:"",$e=q?`
468
+ `:"",Se=q?`
469
469
 
470
470
  /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
471
471
  type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
@@ -476,12 +476,12 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
476
476
 
477
477
  /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
478
478
  export interface LunoraWorkflows {
479
- ${N.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
479
+ ${O.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
480
480
  `)}
481
481
  }`:"",fe=q?' | "workflows"':"",be=q?`
482
- readonly workflows: LunoraWorkflows;`:"",se=b.length>0,Se=se?`import type { QueueProducer } from "@lunora/queue";
482
+ readonly workflows: LunoraWorkflows;`:"",ie=b.length>0,Re=ie?`import type { QueueProducer } from "@lunora/queue";
483
483
  import type * as lunoraQueueDefinitions from "../queues.js";
484
- `:"",Re=se?`
484
+ `:"",Ne=ie?`
485
485
 
486
486
  /** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
487
487
  type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
@@ -490,29 +490,29 @@ type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body }
490
490
  export interface LunoraQueues {
491
491
  ${b.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${h.exportName}>>;`).join(`
492
492
  `)}
493
- }`:"",ye=se?`
494
- readonly queues: LunoraQueues;`:"",le=e.length>0,Ne=le?`import type { AgentHandle } from "@lunora/agent";
495
- `:"",Oe=le?`
493
+ }`:"",ye=ie?`
494
+ readonly queues: LunoraQueues;`:"",le=e.length>0,Oe=le?`import type { AgentHandle } from "@lunora/agent";
495
+ `:"",Te=le?`
496
496
 
497
497
  /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
498
498
  export interface LunoraAgents {
499
499
  ${e.map(h=>(m(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
500
500
  `)}
501
501
  }`:"",we=le?`
502
- readonly agents: LunoraAgents;`:"",Te=g?`import type { InferIdentity } from "${$.server}";
502
+ readonly agents: LunoraAgents;`:"",Ae=g?`import type { InferIdentity } from "${S.server}";
503
503
  import type * as lunoraIdentityContract from "../identity.js";
504
- `:"",Ae=g?`
504
+ `:"",Le=g?`
505
505
 
506
506
  /** 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. */
507
507
  export type Identity = InferIdentity<typeof lunoraIdentityContract.${g.exportName}>;
508
508
 
509
509
  /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
510
510
  type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",de=g?' | "auth"':"",ce=g?`
511
- readonly auth: NarrowedAuth;`:"",Le=g?", Identity":"",Ce=n?`import type * as lunoraEnvContract from "../env.js";
511
+ readonly auth: NarrowedAuth;`:"",Ce=g?", Identity":"",Ie=n?`import type * as lunoraEnvContract from "../env.js";
512
512
  `:"",De=n?`
513
513
 
514
514
  /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
515
- export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",ue=n?' | "env"':"",pe=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`${k}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${$.server}";
515
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",ue=n?' | "env"':"",pe=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`${v}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${S.server}";
516
516
  import type {
517
517
  ActionBuilder,
518
518
  ActionCtx as ActionCtxBase,
@@ -533,14 +533,14 @@ import type {
533
533
  Storage as StorageBase,
534
534
  TableReader,
535
535
  Validator,
536
- } from "${$.server}";
536
+ } from "${S.server}";
537
537
 
538
- import type { DataModel, DatabaseReaderFacade, DatabaseWriterFacade, Doc, Id as IdOfTable, OrmReader, OrmWriter, Relations, TableName } from "./dataModel.js";
539
- ${J}${E}${F}${ne}${A}${Y}${Se}${Ne}${Te}${Ce}
538
+ import type { DataModel, DatabaseReaderFacade, DatabaseWriterFacade, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, OrmReader, OrmWriter, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
539
+ ${H}${P}${F}${ne}${A}${Y}${Re}${Oe}${Ae}${Ie}
540
540
  export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
541
541
 
542
542
  /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
543
- export type StorageBucketName = ${w};${_}${$e}${Re}${Oe}${Ae}${De}
543
+ export type StorageBucketName = ${x};${I}${Se}${Ne}${Te}${Le}${De}
544
544
 
545
545
  /**
546
546
  * Project-typed contexts. The base contexts from \`@lunora/server\` are
@@ -559,8 +559,17 @@ export type StorageBucketName = ${w};${_}${$e}${Re}${Oe}${Ae}${De}
559
559
  * Intersected with the wide \`(string) => TableReader\` signature so the bound
560
560
  * \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
561
561
  * call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
562
+ *
563
+ * The three index-name unions are what make \`.withIndex("by_TYPO")\` a compile
564
+ * error: each resolves to the table's declared names, or \`never\` when it
565
+ * declares none of that kind. Without them a renamed or dropped index left
566
+ * every call site typechecking, and the query either threw at runtime or
567
+ * degraded silently to a full table scan.
562
568
  */
563
- type TypedTableQuery = (<T extends TableName>(table: T) => TableReader<Doc<T>>) & ((table: string) => TableReader);
569
+ type TypedTableQuery = (<T extends TableName>(
570
+ table: T,
571
+ ) => TableReader<Doc<T>, IndexNamesByTable[T], SearchIndexNamesByTable[T], GeoIndexNamesByTable[T]>) &
572
+ ((table: string) => TableReader);
564
573
 
565
574
  /**
566
575
  * The point read \`ctx.db.get(id)\`, bound to this schema: an \`Id<"table">\`
@@ -597,7 +606,7 @@ type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOf
597
606
  export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${Q}${de}${ue}> {
598
607
  readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
599
608
  readonly orm: OrmReader;
600
- readonly storage: ReadOnlyStorage<StorageBucketName>;${ie}${j}${re}${W}${U}${ae}${pe}${ce}
609
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${se}${j}${re}${W}${U}${ae}${pe}${ce}
601
610
  }
602
611
 
603
612
  export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${Q}${fe}${de}${ue}> {
@@ -609,7 +618,7 @@ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${Q}$
609
618
  export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${Q}${fe}${de}${ue}> {
610
619
  readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
611
620
  readonly orm: OrmWriter;
612
- readonly storage: StorageBase<StorageBucketName>;${X}${j}${ee}${te}${B}${z}${re}${W}${U}${xe}${ke}${ve}${ae}${oe}${K}${pe}${be}${ye}${we}${ce}
621
+ readonly storage: StorageBase<StorageBucketName>;${X}${j}${ee}${te}${B}${z}${re}${W}${U}${ke}${ve}${$e}${ae}${oe}${K}${pe}${be}${ye}${we}${ce}
613
622
  }
614
623
 
615
624
  /**
@@ -642,7 +651,7 @@ export const internalAction = lunoraBuilders.internalAction as unknown as Intern
642
651
  /**
643
652
  * \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
644
653
  * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
645
- * \`${$.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
654
+ * \`${S.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
646
655
  * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
647
656
  * \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
648
657
  * no \`as unknown as\` cast. Runtime-identical to the package export; only the
@@ -667,7 +676,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
667
676
  * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
668
677
  * so the \`rls()\` chain discovers a policy authored either way the same.
669
678
  */
670
- export const definePolicy = createPolicyDsl<DataModel, Relations${Le}>();
679
+ export const definePolicy = createPolicyDsl<DataModel, Relations${Ce}>();
671
680
 
672
681
  /**
673
682
  * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
@@ -684,13 +693,13 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Le}>();
684
693
  export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
685
694
  id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
686
695
  };
687
- `},Cn=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${S(n.filePath)}:${n.exportName}`);return t},kr=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:s=!1,usesSandbox:i=!1}=e,l=n.length>0,u=H(s),{dispatchBody:p,importBlock:f,installBlock:y,migrationBody:R,mutatorPaths:d,shapeBody:c}=Tn(n,r,a,o),g=kn(t,n),b=vn(i,n),x=[g.lines,b.lines].filter(_=>_.length>0).join(`
688
- `);let v=p;x.length>0&&(v=p.length>0?`${p.trimEnd()}
689
- ${x}
696
+ `},Un=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${R(n.filePath)}:${n.exportName}`);return t},Dr=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,l=n.length>0,u=G(i),{dispatchBody:p,importBlock:f,installBlock:y,migrationBody:N,mutatorPaths:d,shapeBody:c}=Bn(n,r,a,o),g=Dn(t,n),b=_n(s,n),k=[g.lines,b.lines].filter(I=>I.length>0).join(`
697
+ `);let $=p;k.length>0&&($=p.length>0?`${p.trimEnd()}
698
+ ${k}
690
699
  `:`
691
- ${x}
692
- `);const T=Cn(n),N=o.length>0?`import type { RegisteredShape } from "${u.server}";
693
- `:"",$=o.length>0?`
700
+ ${k}
701
+ `);const T=Un(n),O=o.length>0?`import type { RegisteredShape } from "${u.server}";
702
+ `:"",S=o.length>0?`
694
703
  /**
695
704
  * Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
696
705
  * The generated ShardDO's \`resolveShape\` override looks a shape up by name and
@@ -698,14 +707,14 @@ ${x}
698
707
  * \`shape_subscribe\` (reads-as-permissions).
699
708
  */
700
709
  export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${c}};
701
- `:"",w=d.length>0?`
710
+ `:"",x=d.length>0?`
702
711
  /**
703
712
  * Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
704
713
  * ShardDO's \`isCustomMutator\` override routes through the client-watermark push
705
714
  * protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
706
715
  */
707
- export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(_=>JSON.stringify(_)).join(", ")}]);
708
- `:"",E=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
716
+ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(I=>JSON.stringify(I)).join(", ")}]);
717
+ `:"",P=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
709
718
  `:"",ee=y.length>0?`
710
719
  /**
711
720
  * AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
@@ -713,14 +722,14 @@ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(_=>JSO
713
722
  * parser as a zero-allocation fast path; anything it can't model is deferred.
714
723
  */
715
724
  ${y}
716
- `:"",F=An(n),te=F.types?`
725
+ `:"",F=jn(n),te=F.types?`
717
726
  ${F.types}
718
727
  `:"",ne=F.implementation?`
719
728
  ${F.implementation}
720
- `:"",B=qe(F.types),A=B.length>0?`import type { ${B.join(", ")} } from "./dataModel.js";
721
- `:"",z=l?"context":"_context",L=l?`${On}
729
+ `:"",B=je(F.types),A=B.length>0?`import type { ${B.join(", ")} } from "./dataModel.js";
730
+ `:"",z=l?"context":"_context",L=l?`${qn}
722
731
 
723
- `:"";return at(`${k}${f}${g.importLine}${b.importLine}${E}${N}import { LunoraError } from "${u.server}";
732
+ `:"";return ct(`${v}${f}${g.importLine}${b.importLine}${P}${O}import { LunoraError } from "${u.server}";
724
733
  import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
725
734
  ${A}
726
735
  /**
@@ -746,8 +755,8 @@ ${g.prelude}${b.prelude}
746
755
  * Static dispatch table. The key matches the \`__lunoraRef\` the client
747
756
  * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
748
757
  */
749
- export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${v}};
750
- ${ee}${$}${w}
758
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${$}};
759
+ ${ee}${S}${x}
751
760
  /**
752
761
  * Connection-lifecycle manifest: the function paths the generated ShardDO
753
762
  * dispatches when a client's WebSocket connects (\`connect\`) or disconnects
@@ -755,8 +764,8 @@ ${ee}${$}${w}
755
764
  * DO runs every hook under the socket's verified identity via system dispatch.
756
765
  */
757
766
  export const LUNORA_LIFECYCLE_HOOKS: { connect: readonly string[]; disconnect: readonly string[] } = {
758
- connect: [${T.connect.map(_=>JSON.stringify(_)).join(", ")}],
759
- disconnect: [${T.disconnect.map(_=>JSON.stringify(_)).join(", ")}],
767
+ connect: [${T.connect.map(I=>JSON.stringify(I)).join(", ")}],
768
+ disconnect: [${T.disconnect.map(I=>JSON.stringify(I)).join(", ")}],
760
769
  };
761
770
 
762
771
  /**
@@ -809,8 +818,8 @@ export interface RegisteredDataMigration {
809
818
  * Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
810
819
  * shard DO's admin RPC and the CLI resolve migrations to run through this map.
811
820
  */
812
- export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${R}};
813
- `,s)},Dn=e=>{const t={};for(const n of e.tables){const r={};for(const[a,o]of Object.entries(n.shape)){const s=o.kind==="optional"&&o.inner?o.inner:o;s.kind==="id"&&s.tableName!==void 0&&(r[a]=s.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},_n=e=>{const t={};for(const n of e.tables){const r=[];for(const[a,o]of Object.entries(n.shape))(o.kind==="optional"&&o.inner?o.inner:o).kind==="storage"&&r.push(a);r.length>0&&(t[n.name]=r)}return t},In=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(a=>({fields:[...a.fields],name:a.name,type:"index",...a.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(a=>({fields:[a.field,...a.filterFields??[]],name:a.name,type:"search"})),...(n.geoIndexes??[]).map(a=>({fields:[a.field],name:a.name,type:"geo"})),...n.rankIndexes.map(a=>({fields:a.sortBy.map(o=>o.field),name:a.name,type:"rank"})),...n.vectorIndexes.map(a=>({fields:a.field===void 0?[]:[a.field],name:a.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},Pn=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},En=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"}];for(const[a,o]of Object.entries(n.shape)){const s=o.kind==="optional"||!!o.column?.hasDefault,i=o.kind==="optional"&&o.inner?o.inner:o,l={name:a,optional:s,type:i.kind};i.kind==="id"&&i.tableName!==void 0&&(l.ref=i.tableName),i.kind==="storage"&&(l.isStorage=!0),r.push(l)}t[n.name]=r}return t},Fn=e=>e?{importFragment:"serveRelationFanout, ",override:`
821
+ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${N}};
822
+ `,i)},Kn=e=>{const t={};for(const n of e.tables){const r={};for(const[a,o]of Object.entries(n.shape)){const i=o.kind==="optional"&&o.inner?o.inner:o;i.kind==="id"&&i.tableName!==void 0&&(r[a]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},Qn=e=>{const t={};for(const n of e.tables){const r=[];for(const[a,o]of Object.entries(n.shape))(o.kind==="optional"&&o.inner?o.inner:o).kind==="storage"&&r.push(a);r.length>0&&(t[n.name]=r)}return t},Hn=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(a=>({fields:[...a.fields],name:a.name,type:"index",...a.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(a=>({fields:[a.field,...a.filterFields??[]],name:a.name,type:"search"})),...(n.geoIndexes??[]).map(a=>({fields:[a.field],name:a.name,type:"geo"})),...n.rankIndexes.map(a=>({fields:a.sortBy.map(o=>o.field),name:a.name,type:"rank"})),...n.vectorIndexes.map(a=>({fields:a.field===void 0?[]:[a.field],name:a.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},Jn=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},Vn=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"}];for(const[a,o]of Object.entries(n.shape)){const i=o.kind==="optional"||!!o.column?.hasDefault,s=o.kind==="optional"&&o.inner?o.inner:o,l={name:a,optional:i,type:s.kind};s.kind==="id"&&s.tableName!==void 0&&(l.ref=s.tableName),s.kind==="storage"&&(l.isStorage=!0),r.push(l)}t[n.name]=r}return t},Gn=e=>e?{importFragment:"serveRelationFanout, ",override:`
814
823
  protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
815
824
  this.ensureMigrated();
816
825
 
@@ -818,7 +827,7 @@ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${R}}
818
827
 
819
828
  return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
820
829
  }
821
- `}:{importFragment:"",override:""},Mn=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:`
830
+ `}:{importFragment:"",override:""},zn=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:`
822
831
  const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
823
832
  // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
824
833
  // function path + trace id into createAi, which folds them into the
@@ -849,7 +858,7 @@ const aiStub: LunoraAi = {
849
858
  ${t}
850
859
  }) as unknown as LunoraAi["workersai"],
851
860
  };
852
- `}},I={build:"",configField:"",contextField:"",importLines:[],stub:""},qn=e=>{if(!e)return I;const t='throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");';return{build:`
861
+ `}},_={build:"",configField:"",contextField:"",importLines:[],stub:""},Xn=e=>{if(!e)return _;const t='throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");';return{build:`
853
862
  const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
854
863
  const kv: Kv = kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub;
855
864
  `,configField:`
@@ -875,7 +884,7 @@ const kvStub: Kv = {
875
884
  ${t}
876
885
  },
877
886
  };
878
- `}},Bn=(e,t)=>e?{build:`
887
+ `}},Yn=(e,t)=>e?{build:`
879
888
  const flags: import("${t}").LunoraFlags = createFlags({
880
889
  hooks: flagsConfig.hooks,
881
890
  logger: flagsConfig.logger,
@@ -884,23 +893,23 @@ const kvStub: Kv = {
884
893
  });
885
894
  `,configField:`
886
895
  flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
887
- flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:I,jn=e=>e?{build:`
896
+ flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:_,Zn=e=>e?{build:`
888
897
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
889
898
  `,configField:"",contextField:`
890
899
  notify,
891
- push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:I,Wn=e=>e?{build:`
900
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:_,er=e=>e?{build:`
892
901
  const envConfig = lunoraEnvContract.${e.exportName}(env);
893
902
  `,configField:"",contextField:`
894
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:I,Un=e=>e?{build:`
903
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:_,tr=e=>e?{build:`
895
904
  const access = accessFacade(identity, userId);
896
905
  `,configField:"",contextField:`
897
- access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:I,Kn=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=i=>`
906
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:_,nr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
898
907
  const env = (this.env ?? {}) as Record<string, unknown>;
899
908
  const flags: import("${n}").LunoraFlags = createFlags({
900
909
  hooks: flagsConfig.hooks,
901
910
  logger: flagsConfig.logger,
902
911
  provider: () => config.flags?.(env) ?? flagsConfig.provider(env),
903
- targetingKey: ${i},
912
+ targetingKey: ${s},
904
913
  });`,a=`
905
914
  /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
906
915
  const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }> = ${JSON.stringify(e,void 0,4)};
@@ -925,7 +934,7 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
925
934
 
926
935
  return { configured: true, flags: evaluations };
927
936
  }
928
- `,s=`
937
+ `,i=`
929
938
  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 })")}
930
939
  const key = typeof args.key === "string" ? args.key : "";
931
940
 
@@ -958,7 +967,7 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
958
967
 
959
968
  return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
960
969
  }
961
- `;return{constant:a,evaluateOverride:o,subscriptionOverride:s}},Qn=e=>{if(!e)return I;const t='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().");';return{build:`
970
+ `;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},rr=e=>{if(!e)return _;const t='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().");';return{build:`
962
971
  const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
963
972
  const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
964
973
  `,configField:`
@@ -972,7 +981,7 @@ const analyticsStub: AnalyticsClient = {
972
981
  ${t}
973
982
  },
974
983
  };
975
- `}},Jn=e=>{if(!e)return I;const t='throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");';return{build:`
984
+ `}},ar=e=>{if(!e)return _;const t='throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");';return{build:`
976
985
  const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
977
986
  const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
978
987
  `,configField:`
@@ -986,7 +995,7 @@ const imagesStub: Images = {
986
995
  ${t}
987
996
  },
988
997
  };
989
- `}},Vn=e=>e?{build:`
998
+ `}},or=e=>e?{build:`
990
999
  const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
991
1000
  `,configField:`
992
1001
  sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
@@ -996,7 +1005,7 @@ const sqlStub: SqlClient = {
996
1005
  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))\\\`.");
997
1006
  },
998
1007
  };
999
- `}:I,Gn=e=>{if(!e)return I;const t="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.\");";return{build:`
1008
+ `}:_,sr=e=>{if(!e)return _;const t="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.\");";return{build:`
1000
1009
  const browser: Browser = config.browser ? config.browser(env) : browserStub;
1001
1010
  `,configField:`
1002
1011
  browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
@@ -1024,7 +1033,7 @@ const browserStub: Browser = {
1024
1033
  ${t}
1025
1034
  },
1026
1035
  };
1027
- `}},Hn=e=>{if(!e)return I;const t='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().");';return{build:`
1036
+ `}},ir=e=>{if(!e)return _;const t='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().");';return{build:`
1028
1037
  const r2sqlEnv = env as Record<string, unknown>;
1029
1038
  const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
1030
1039
  const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
@@ -1056,7 +1065,7 @@ const r2sqlStub: R2SqlClient = {
1056
1065
  ${t}
1057
1066
  },
1058
1067
  };
1059
- `}},zn=e=>e?{build:`
1068
+ `}},lr=e=>e?{build:`
1060
1069
  const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
1061
1070
  const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
1062
1071
  `,configField:`
@@ -1066,14 +1075,14 @@ const pipelinesStub: PipelineClient = {
1066
1075
  throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\\`pipelines\\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\\`pipelines\\\` to createShardDO().");
1067
1076
  },
1068
1077
  };
1069
- `}:I,vr=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(o=>(m(o.exportName,`container export "${o.exportName}"`),m(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
1078
+ `}:_,_r=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(o=>(m(o.exportName,`container export "${o.exportName}"`),m(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
1070
1079
  export class ${o.className} extends LunoraContainer {
1071
1080
  public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1072
1081
  super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
1073
1082
  }
1074
1083
  }
1075
1084
  `)).join(`
1076
- `),a=e.map(o=>o.exportName).join(", ");return`${k}/**
1085
+ `),a=e.map(o=>o.exportName).join(", ");return`${v}/**
1077
1086
  * Container-enabled Durable Object classes for the containers declared in
1078
1087
  * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
1079
1088
  * requires each \`containers[].class_name\` to be exported by the worker:
@@ -1091,7 +1100,7 @@ import { ${a} } from "../containers.js";
1091
1100
 
1092
1101
  export { ContainerProxy } from "@lunora/container/do";
1093
1102
 
1094
- ${r}`},Xn=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)m(r.exportName,`container export "${r.exportName}"`),m(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const a=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${a} },`}).join(`
1103
+ ${r}`},dr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)m(r.exportName,`container export "${r.exportName}"`),m(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const a=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${a} },`}).join(`
1095
1104
  `);return{build:`
1096
1105
  const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
1097
1106
  `,contextField:`
@@ -1100,14 +1109,14 @@ ${r}`},Xn=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
1100
1109
  const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
1101
1110
  ${n}
1102
1111
  ];
1103
- `}},$r=e=>{if(e.length===0)return"";const t=e.map(r=>(m(r.exportName,`workflow export "${r.exportName}"`),m(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
1112
+ `}},Er=e=>{if(e.length===0)return"";const t=e.map(r=>(m(r.exportName,`workflow export "${r.exportName}"`),m(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
1104
1113
  export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
1105
1114
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1106
1115
  super(ctx, env, ${r.exportName}, "${r.exportName}");
1107
1116
  }
1108
1117
  }
1109
1118
  `)).join(`
1110
- `),n=e.map(r=>r.exportName).join(", ");return`${k}/**
1119
+ `),n=e.map(r=>r.exportName).join(", ");return`${v}/**
1111
1120
  * WorkflowEntrypoint classes for the workflows declared in
1112
1121
  * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
1113
1122
  * requires each \`workflows[].class_name\` to be exported by the worker:
@@ -1128,21 +1137,21 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
1128
1137
  /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
1129
1138
  type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
1130
1139
 
1131
- ${t}`},Sr=e=>{if(e.length===0)return"";const t=e.filter(a=>a.voice).length>0,n=e.map(a=>{m(a.exportName,`agent export "${a.exportName}"`),m(a.className,`agent class "${a.className}"`);const o=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
1140
+ ${t}`},Pr=e=>{if(e.length===0)return"";const t=e.filter(a=>a.voice).length>0,n=e.map(a=>{m(a.exportName,`agent export "${a.exportName}"`),m(a.className,`agent class "${a.className}"`);const o=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
1132
1141
  export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1133
1142
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1134
1143
  super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
1135
1144
  }
1136
1145
  }
1137
- `;if(!a.voice)return o;const s=a.voiceClassName??"",i=a.voiceBindingName??"";m(s,`agent voice class "${s}"`);const l=`
1138
- /** Voice-session Durable Object for the \`${a.exportName}\` agent (binding \`${i}\`). */
1139
- export class ${s} extends VoiceSessionDO {
1146
+ `;if(!a.voice)return o;const i=a.voiceClassName??"",s=a.voiceBindingName??"";m(i,`agent voice class "${i}"`);const l=`
1147
+ /** Voice-session Durable Object for the \`${a.exportName}\` agent (binding \`${s}\`). */
1148
+ export class ${i} extends VoiceSessionDO {
1140
1149
  public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
1141
1150
  super(ctx, env, ${a.exportName}, "${a.exportName}");
1142
1151
  }
1143
1152
  }
1144
1153
  `;return`${o}${l}`}).join(`
1145
- `),r=e.map(a=>a.exportName).join(", ");return`${k}/**
1154
+ `),r=e.map(a=>a.exportName).join(", ");return`${v}/**
1146
1155
  * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
1147
1156
  * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
1148
1157
  * Workflow. Re-export them from your worker entry — wrangler requires each
@@ -1156,8 +1165,8 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
1156
1165
 
1157
1166
  import { ${r} } from "../agents.js";
1158
1167
 
1159
- ${n}`},Rr=e=>{const t=e.filter(a=>a.mode==="push");if(t.length===0)return"";for(const a of t)m(a.exportName,`queue export "${a.exportName}"`);const n=t.map(a=>a.exportName).join(", "),r=t.map(a=>` ${JSON.stringify(a.name)}: { definition: ${a.exportName}, exportName: ${JSON.stringify(a.exportName)} },`).join(`
1160
- `);return`${k}/**
1168
+ ${n}`},Fr=e=>{const t=e.filter(a=>a.mode==="push");if(t.length===0)return"";for(const a of t)m(a.exportName,`queue export "${a.exportName}"`);const n=t.map(a=>a.exportName).join(", "),r=t.map(a=>` ${JSON.stringify(a.name)}: { definition: ${a.exportName}, exportName: ${JSON.stringify(a.exportName)} },`).join(`
1169
+ `);return`${v}/**
1161
1170
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
1162
1171
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
1163
1172
  * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
@@ -1171,7 +1180,7 @@ import { ${n} } from "../queues.js";
1171
1180
  export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
1172
1181
  ${r}
1173
1182
  };
1174
- `},Yn=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`workflow export "${n.exportName}"`),m(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
1183
+ `},cr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`workflow export "${n.exportName}"`),m(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
1175
1184
  `);return{build:`
1176
1185
  const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
1177
1186
  `,contextField:`
@@ -1180,7 +1189,7 @@ ${r}
1180
1189
  const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
1181
1190
  ${t}
1182
1191
  ];
1183
- `}},Zn=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`queue export "${n.exportName}"`),m(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
1192
+ `}},ur=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`queue export "${n.exportName}"`),m(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
1184
1193
  `);return{build:`
1185
1194
  const queues = createQueueContext(env, LUNORA_QUEUES);
1186
1195
  `,contextField:`
@@ -1189,7 +1198,7 @@ ${t}
1189
1198
  const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
1190
1199
  ${t}
1191
1200
  ];
1192
- `}},er=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`agent export "${n.exportName}"`),m(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
1201
+ `}},pr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`agent export "${n.exportName}"`),m(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
1193
1202
  `);return{build:`
1194
1203
  const agents = createAgentContext(env, LUNORA_AGENTS);
1195
1204
  `,contextField:`
@@ -1198,21 +1207,21 @@ ${t}
1198
1207
  const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
1199
1208
  ${t}
1200
1209
  ];
1201
- `}},tr=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{constant:`
1210
+ `}},hr=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{constant:`
1202
1211
  /** Read-only declared-workflow metadata (discovered from \`lunora/workflows.ts\`) served via \`__lunora_admin__:listWorkflows\` for the studio's workflows view. */
1203
1212
  const LUNORA_WORKFLOWS_INFO: WorkflowsResult = ${JSON.stringify(t,void 0,4)};
1204
1213
  `,override:`
1205
1214
  protected override workflowsMetadata(): WorkflowsResult {
1206
1215
  return LUNORA_WORKFLOWS_INFO;
1207
1216
  }
1208
- `}},nr=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{constant:`
1217
+ `}},gr=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{constant:`
1209
1218
  /** Read-only declared-queue metadata (discovered from \`lunora/queues.ts\`) served via \`__lunora_admin__:listQueues\` for the studio's queues view. */
1210
1219
  const LUNORA_QUEUES_INFO: QueuesResult = ${JSON.stringify(t,void 0,4)};
1211
1220
  `,override:`
1212
1221
  protected override queuesMetadata(): QueuesResult {
1213
1222
  return LUNORA_QUEUES_INFO;
1214
1223
  }
1215
- `}},rr=e=>{if(!e)return{build:"",configField:"",contextField:"",imports:[],stub:""};const t='throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");';return{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
1224
+ `}},mr=e=>{if(!e)return{build:"",configField:"",contextField:"",imports:[],stub:""};const t='throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");';return{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
1216
1225
  const payments: LunoraPayment = config.payment
1217
1226
  ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
1218
1227
  : paymentStub;
@@ -1248,7 +1257,7 @@ const paymentStub: LunoraPayment = {
1248
1257
  ${t}
1249
1258
  },
1250
1259
  } as unknown as LunoraPayment;
1251
- `}},ar=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
1260
+ `}},fr=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
1252
1261
  const x402: X402Pay = config.x402
1253
1262
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1254
1263
  : x402Stub;
@@ -1260,10 +1269,10 @@ const x402Stub: X402Pay = {
1260
1269
  throw new Error("ctx.x402: no pay rail configured. Pass \\\`x402\\\` to createShardDO().");
1261
1270
  },
1262
1271
  } as unknown as X402Pay;
1263
- `}:{build:"",configField:"",contextField:"",imports:[],stub:""},or=(e,t,n,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike",...r?["FlagsResult"]:[],"KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],Nr=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:s=!1,hasAi:i=!1,hasAnalytics:l=!1,hasBrowser:u=!1,hasFlags:p=!1,hasHyperdrive:f=!1,hasImages:y=!1,hasKv:R=!1,hasNotify:d=!1,hasPayments:c=!1,hasPipelines:g=!1,hasR2sql:b=!1,hasX402:x=!1,maskMetadata:v,mutators:T=[],queues:N=[],rlsMetadata:$,schema:w,schemaSnapshot:E,shapes:ee=[],storageRules:F,studioFeatures:te,useUmbrella:ne=!1,workflows:B=[]})=>{const A=H(ne),z=T.length>0,L=ee.length>0,_=E===void 0?"":zt(E),M=E===void 0?"":`
1272
+ `}:{build:"",configField:"",contextField:"",imports:[],stub:""},br=(e,t,n,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],Mr=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:l=!1,hasBrowser:u=!1,hasFlags:p=!1,hasHyperdrive:f=!1,hasImages:y=!1,hasKv:N=!1,hasNotify:d=!1,hasPayments:c=!1,hasPipelines:g=!1,hasR2sql:b=!1,hasX402:k=!1,maskMetadata:$,mutators:T=[],queues:O=[],rlsMetadata:S,schema:x,schemaSnapshot:P,shapes:ee=[],storageRules:F,studioFeatures:te,useUmbrella:ne=!1,workflows:B=[]})=>{const A=G(ne),z=T.length>0,L=ee.length>0,I=P===void 0?"":on(P),M=P===void 0?"":`
1264
1273
  /** 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. */
1265
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Xt(E))}, json: ${JSON.stringify(_)} };
1266
- `,re=E===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:ae,configField:xe,contextField:ke,stub:ve}=Mn(i),oe=Un(s),K=qn(R),P=Bn(p,A.flags),Q=Kn(o,p,A.flags),X=jn(d),ie=Wn(a),J=Qn(l),j=Jn(y),W=Vn(f),U=Gn(u),q=Hn(b),Y=zn(g),{build:$e,contextField:fe,importLines:be,specs:se}=Zn(N),{build:Se,contextField:Re,importLines:ye,specs:le}=Xn(r,w.jurisdiction),{build:Ne,contextField:Oe,importLines:we,specs:Te}=Yn(B),{build:Ae,contextField:de,importLines:ce,specs:Le}=er(n),{build:Ce,configField:De,contextField:ue,imports:pe,stub:h}=rr(c),{build:_e,configField:st,imports:lt,stub:dt}=ar(x),ct=e,ut=t,pt=$??{policies:[],roles:[]},ht=v??{columns:[]},gt=F??{rules:[]},mt=te??{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:ft,override:bt}=tr(B),{constant:yt,override:wt}=nr(N),V=w.vectorIndexes.length>0,he=w.tables.some(C=>C.shardMode==="global"),Ie=w.tables.some(C=>C.shardMode==="global"&&C.globalBackend==="hyperdrive"),je=w.tables.some(C=>C.shardMode==="global"&&C.globalBackend!=="hyperdrive"),G=w.tables.some(C=>C.externalSource!==void 0);if(je&&Ie)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 Pe=w.tables.length>0,xt=Dn(w),kt=In(w),vt=En(w),$t=_n(w),We=Pn(w),Ue=or(V,B.length>0,N.length>0,p);L&&Ue.push("WhereInput");const Ke=Fn(he),St=L?`
1274
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(sn(P))}, json: ${JSON.stringify(I)} };
1275
+ `,re=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:ae,configField:ke,contextField:ve,stub:$e}=zn(s),oe=tr(i),K=Xn(N),E=Yn(p,A.flags),Q=nr(o,p,A.flags),X=Zn(d),se=er(a),H=rr(l),j=ar(y),W=or(f),U=sr(u),q=ir(b),Y=lr(g),{build:Se,contextField:fe,importLines:be,specs:ie}=ur(O),{build:Re,contextField:Ne,importLines:ye,specs:le}=dr(r,x.jurisdiction),{build:Oe,contextField:Te,importLines:we,specs:Ae}=cr(B),{build:Le,contextField:de,importLines:ce,specs:Ce}=pr(n),{build:Ie,configField:De,contextField:ue,imports:pe,stub:h}=mr(c),{build:_e,configField:ht,imports:gt,stub:mt}=fr(k),ft=e,bt=t,yt=S??{policies:[],roles:[]},wt=$??{columns:[]},xt=F??{rules:[]},kt=te??{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:vt,override:$t}=hr(B),{constant:St,override:Rt}=gr(O),J=x.vectorIndexes.length>0,Ue=new Set(x.tables.filter(w=>typeof w.shardMode=="object"&&w.shardMode.kind==="shardBy").map(w=>w.name)),xe=x.vectorIndexes.some(w=>Ue.has(w.table)),he=x.tables.some(w=>w.shardMode==="global"),Ee=x.tables.some(w=>w.shardMode==="global"&&w.globalBackend==="hyperdrive"),Ke=x.tables.some(w=>w.shardMode==="global"&&w.globalBackend!=="hyperdrive"),V=x.tables.some(w=>w.externalSource!==void 0);if(Ke&&Ee)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 Pe=x.tables.length>0,Nt=Kn(x),Ot=Hn(x),Tt=Vn(x),At=Qn(x),Qe=Jn(x),He=br(J,B.length>0,O.length>0,p);L&&He.push("WhereInput");const Je=Gn(he),Lt=L?`
1267
1276
  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 {
1268
1277
  const shape = LUNORA_SHAPES[name];
1269
1278
 
@@ -1316,15 +1325,15 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1316
1325
 
1317
1326
  return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
1318
1327
  }
1319
- `:"",Rt=z?`
1328
+ `:"",Ct=z?`
1320
1329
  protected override isCustomMutator(functionPath: string): boolean {
1321
1330
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1322
1331
  }
1323
- `:"",Nt=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":"",Ot=L?"assertShapeShardable, ":"",ge=[`import type { ${Ue.join(", ")} } from "${A.do}";`,`import { applyCdcChanges, ${Ot}createReadFootprint, createShardCtxDb, ${G?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}runDataMigration, runShardMigrations, ${Ke.importFragment}ShardDO as ShardDOBase } from "${A.do}";`,...G?[`import type { ExternalSourceLike, SourceClientLike } from "${A.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${A.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${A.server}";`];Pe&&ge.push(`import { bindOrm, bindTableFacade } from "${A.server}";`),V&&ge.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),i&&ge.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ge.push(...oe.importLines,...K.importLines,...P.importLines,...X.importLines,...ie.importLines,...J.importLines,...j.importLines,...W.importLines,...U.importLines,...q.importLines,...Y.importLines,...ye,...we,...be,...ce,...pe,...lt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...z?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Tt=V?`
1324
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",At=je?`
1325
- d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Lt=Ie?`
1326
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ct=G?`
1327
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Dt=he?'\nconst globalDbStub: DatabaseWriterLike = {\n aggregate: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n count: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n delete: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findFirst: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findFirstOrThrow: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findMany: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n get: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n groupBy: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n insert: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n normalizeId: () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n patch: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n query: () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n rank: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n rankPage: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n replace: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n};\n':"",_t=V?`
1332
+ `:"",It=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":"",Dt=L?"assertShapeShardable, ":"",ge=[`import type { ${He.join(", ")} } from "${A.do}";`,`import { applyCdcChanges, ${Dt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${V?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${xe?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Je.importFragment}ShardDO as ShardDOBase } from "${A.do}";`,...V?[`import type { ExternalSourceLike, SourceClientLike } from "${A.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${A.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${A.server}";`];Pe&&ge.push(`import { bindOrm, bindTableFacade } from "${A.server}";`),J&&ge.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&ge.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ge.push(...oe.importLines,...K.importLines,...E.importLines,...X.importLines,...se.importLines,...H.importLines,...j.importLines,...W.importLines,...U.importLines,...q.importLines,...Y.importLines,...ye,...we,...be,...ce,...pe,...gt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...z?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const _t=J?`
1333
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Et=Ke?`
1334
+ d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Pt=Ee?`
1335
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ft=V?`
1336
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Mt=he?'\nconst globalDbStub: DatabaseWriterLike = {\n aggregate: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n count: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n delete: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findFirst: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findFirstOrThrow: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findMany: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n get: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n groupBy: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n insert: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n normalizeId: () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n patch: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n query: () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n rank: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n rankPage: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n replace: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n};\n':"",qt=J?`
1328
1337
  const vectorsStub: VectorSearchLike = {
1329
1338
  deleteByIds: async () => {
1330
1339
  throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
@@ -1342,22 +1351,24 @@ const vectorsStub: VectorSearchLike = {
1342
1351
  throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
1343
1352
  },
1344
1353
  };
1345
- `:"",It=V?`
1354
+ `:"",Bt=xe?`
1355
+ const vectorShardKey = this.currentShardKey();
1356
+ `:"",jt=xe?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",Wt=xe?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${x.vectorIndexes.filter(w=>Ue.has(w.table)).map(w=>JSON.stringify(w.name)).join(", ")}] }`:"",Ut=J?`
1346
1357
  let vectors: VectorSearchLike;
1347
1358
  let onWrite: WriteHook | undefined;
1348
1359
 
1349
1360
  if (config.vectors) {
1350
1361
  const lunora = createVectors({ indexes: config.vectors(env) });
1351
-
1352
- vectors = createContextVectors(lunora);
1353
- onWrite = createVectorSyncHook({ schema: schema as unknown as VectorSchemaLike, vectors });
1362
+ ${Bt}
1363
+ vectors = createContextVectors(lunora${Wt});
1364
+ onWrite = createVectorSyncHook({ ${jt}schema: schema as unknown as VectorSchemaLike, vectors });
1354
1365
  } else {
1355
1366
  vectors = vectorsStub;
1356
1367
  onWrite = undefined;
1357
1368
  }
1358
- `:"",Qe=he?`
1359
- globalDb,`:"",Je=`
1360
- auth: { identity: identity ?? null, userId: userId ?? null },`,Pt=V?`{${Je}
1369
+ `:"",Ve=he?`
1370
+ globalDb,`:"",Ge=`
1371
+ auth: { identity: identity ?? null, userId: userId ?? null },`,Kt=J?`{${Ge}
1361
1372
  broadcast: (delta) => {
1362
1373
  this.recordChangedTable(delta.table, delta.indexKeys);
1363
1374
  },
@@ -1371,8 +1382,8 @@ const vectorsStub: VectorSearchLike = {
1371
1382
  scheduler,
1372
1383
  schema: schema as unknown as SchemaLike,
1373
1384
  sql: this.sql as SqlExec,
1374
- storage,${Qe}
1375
- }`:`{${Je}
1385
+ storage,${Ve}
1386
+ }`:`{${Ge}
1376
1387
  broadcast: (delta) => {
1377
1388
  this.recordChangedTable(delta.table, delta.indexKeys);
1378
1389
  },
@@ -1385,14 +1396,14 @@ const vectorsStub: VectorSearchLike = {
1385
1396
  scheduler,
1386
1397
  schema: schema as unknown as SchemaLike,
1387
1398
  sql: this.sql as SqlExec,
1388
- storage,${Qe}
1389
- }`,Et=V?`
1390
- vectors,`:"",Ft=Pe?`
1391
- orm: bindOrm(facade),`:"",Mt="",Ve=Ie?"config.hyperdriveGlobal":"config.d1",qt=he?` const globalDb: DatabaseWriterLike = ${Ve}?.(env, { identity, userId }) ?? globalDbStub;
1392
- `:"",Bt=L&&he?`
1399
+ storage,${Ve}
1400
+ }`,Qt=J?`
1401
+ vectors,`:"",Ht=Pe?`
1402
+ orm: bindOrm(facade),`:"",Jt="",ze=Ee?"config.hyperdriveGlobal":"config.d1",Vt=he?` const globalDb: DatabaseWriterLike = ${ze}?.(env, { identity, userId }) ?? globalDbStub;
1403
+ `:"",Gt=L&&he?`
1393
1404
  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 }>> {
1394
1405
  const env = this.env as Record<string, unknown>;
1395
- const globalDb: DatabaseWriterLike = ${Ve}?.(env, identity) ?? globalDbStub;
1406
+ const globalDb: DatabaseWriterLike = ${ze}?.(env, identity) ?? globalDbStub;
1396
1407
  const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
1397
1408
 
1398
1409
  let cursor: null | string = null;
@@ -1419,10 +1430,10 @@ const vectorsStub: VectorSearchLike = {
1419
1430
 
1420
1431
  return rows;
1421
1432
  }
1422
- `:"",jt=G?`
1433
+ `:"",zt=V?`
1423
1434
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1424
1435
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1425
- `:"",Wt=G?`
1436
+ `:"",Xt=V?`
1426
1437
  protected override async pollExternalSources(): Promise<number | undefined> {
1427
1438
  const env = (this.env ?? {}) as Record<string, unknown>;
1428
1439
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1435,15 +1446,6 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1435
1446
 
1436
1447
  const shardKey = this.currentShardKey();
1437
1448
  const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1438
- const writer = createShardCtxDb({
1439
- broadcast: (delta) => {
1440
- this.recordChangedTable(delta.table, delta.indexKeys);
1441
- },
1442
- cdc: config.cdc ?? false,
1443
- scheduler,
1444
- schema: schema as unknown as SchemaLike,
1445
- sql: this.sql as SqlExec,
1446
- });
1447
1449
 
1448
1450
  let clients = sourceClientCache.get(this);
1449
1451
 
@@ -1490,14 +1492,31 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1490
1492
  // Logs panel and stamp \`polledAt\` so a persistent misconfig backs
1491
1493
  // off to \`refresh.everyMs\` instead of retrying every alarm tick.
1492
1494
  this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`));
1493
- } else if (source.mode === "incremental") {
1494
- // Incremental (plan 136): pull only rows past the durable
1495
- // watermark (or a full-pull seed/reconcile), upsert-only.
1496
- // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
1497
- await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
1498
1495
  } else {
1499
- // 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
1500
- await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
1496
+ // A FRESH tracker per TABLE, not one shared across the whole
1497
+ // loop: one table's runaway pull must not spend a budget a
1498
+ // sibling table needs, and a limit hit here must not block
1499
+ // that sibling from getting its own full budget this tick.
1500
+ const writer = createShardCtxDb({
1501
+ broadcast: (delta) => {
1502
+ this.recordChangedTable(delta.table, delta.indexKeys);
1503
+ },
1504
+ cdc: config.cdc ?? false,
1505
+ headroom: this.alarmHeadroom(),
1506
+ scheduler,
1507
+ schema: schema as unknown as SchemaLike,
1508
+ sql: this.sql as SqlExec,
1509
+ });
1510
+
1511
+ if (source.mode === "incremental") {
1512
+ // Incremental (plan 136): pull only rows past the durable
1513
+ // watermark (or a full-pull seed/reconcile), upsert-only.
1514
+ // eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
1515
+ await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
1516
+ } else {
1517
+ // 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
1518
+ await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
1519
+ }
1501
1520
  }
1502
1521
 
1503
1522
  // Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
@@ -1505,6 +1524,33 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1505
1524
  // stale-immediate and re-arm the alarm in a hammering loop.
1506
1525
  polledAt.set(table, Date.now());
1507
1526
  } catch (error) {
1527
+ if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
1528
+ // Batch full, not a genuine failure. Incremental mode only
1529
+ // persists its watermark AFTER a full apply (see
1530
+ // \`pullExternalSourceIncrementalTick\`), so this throw left it
1531
+ // untouched — the next tick safely re-pulls/re-applies the
1532
+ // SAME slice (idempotent upsert). Full-pull mode (and an
1533
+ // incremental source's own occasional full-pull/reconcile
1534
+ // sweep) has no resumable cursor at all — deliberately not
1535
+ // inventing one here; a retry just redoes the whole pull,
1536
+ // safe if wasteful. Either way: warn instead of
1537
+ // \`recordExternalSourceError\`, and leave \`polledAt\`
1538
+ // UNCHANGED (skip the stamp below via \`continue\`) so this
1539
+ // table stays "due" and \`nextPollAlarmTarget\`'s existing
1540
+ // due-now floor re-arms the shared alarm promptly — not a
1541
+ // fresh \`setAlarm(now)\`.
1542
+ this.logs.push({
1543
+ functionPath: \`source:\${table}\`,
1544
+ level: "warn",
1545
+ message: \`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
1546
+ timestamp: Date.now(),
1547
+ });
1548
+
1549
+ nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
1550
+
1551
+ continue;
1552
+ }
1553
+
1508
1554
  this.recordExternalSourceError(table, error);
1509
1555
  // Stamp on failure too, so a persistently failing source throttles
1510
1556
  // to \`refresh.everyMs\` rather than being hammered every tick.
@@ -1523,10 +1569,10 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1523
1569
 
1524
1570
  return nextDueAt;
1525
1571
  }
1526
- `:"",Ge=We.length>0,Ut=G||Ge?`
1572
+ `:"",Xe=Qe.length>0,Yt=V||Xe?`
1527
1573
  public constructor(state: ShardDOState, env: unknown) {
1528
1574
  super(state, env);
1529
- ${G?`
1575
+ ${V?`
1530
1576
  const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1531
1577
  const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1532
1578
 
@@ -1536,27 +1582,27 @@ ${G?`
1536
1582
  if (autoSourced) {
1537
1583
  void this.scheduleSourcePoll();
1538
1584
  }
1539
- `:""}${Ge?`
1585
+ `:""}${Xe?`
1540
1586
  if (LUNORA_TTL_SWEEPS.length > 0) {
1541
1587
  void this.scheduleTtlSweep();
1542
1588
  }
1543
1589
  `:""} }
1544
- `:"",Kt=Pe?`
1590
+ `:"",Zt=Pe?`
1545
1591
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1546
- ${w.tables.map(C=>` facade[${JSON.stringify(C.name)}] = bindTableFacade(db, ${JSON.stringify(C.name)});`).join(`
1592
+ ${x.tables.map(w=>` facade[${JSON.stringify(w.name)}] = bindTableFacade(db, ${JSON.stringify(w.name)});`).join(`
1547
1593
  `)}
1548
- `:"",Qt=`${oe.build}${K.build}${P.build}${J.build}${ie.build}
1594
+ `:"",en=`${oe.build}${K.build}${E.build}${H.build}${se.build}
1549
1595
  const secrets = createSecrets(env);
1550
- `,Jt=`${oe.contextField}${K.contextField}${P.contextField}${X.contextField}${J.contextField}${ie.contextField}
1551
- secrets,`,Vt=X.build,He=y||f||u||b||g||x,Gt=He?`
1596
+ `,tn=`${oe.contextField}${K.contextField}${E.contextField}${X.contextField}${H.contextField}${se.contextField}
1597
+ secrets,`,nn=X.build,Ye=y||f||u||b||g||k,rn=Ye?`
1552
1598
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1553
1599
  // and attached only for an \`action\` so query/mutation ctx never carry them.
1554
1600
  if (isAction) {
1555
- ${j.build}${W.build}${U.build}${q.build}${Y.build}${_e}${[...y?[" ctx.images = images;"]:[],...f?[" ctx.sql = sql;"]:[],...u?[" ctx.browser = browser;"]:[],...b?[" ctx.r2sql = r2sql;"]:[],...g?[" ctx.pipelines = pipelines;"]:[],...x?[" ctx.x402 = x402;"]:[]].join(`
1601
+ ${j.build}${W.build}${U.build}${q.build}${Y.build}${_e}${[...y?[" ctx.images = images;"]:[],...f?[" ctx.sql = sql;"]:[],...u?[" ctx.browser = browser;"]:[],...b?[" ctx.r2sql = r2sql;"]:[],...g?[" ctx.pipelines = pipelines;"]:[],...k?[" ctx.x402 = x402;"]:[]].join(`
1556
1602
  `)}
1557
1603
  }
1558
- `:"",Ht=He?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1559
- `:"";return`${k}${ge.join(`
1604
+ `:"",an=Ye?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1605
+ `:"";return`${v}${ge.join(`
1560
1606
  `)}
1561
1607
 
1562
1608
  type FunctionKind = "action" | "mutation" | "query";
@@ -1566,45 +1612,45 @@ interface FunctionReference {
1566
1612
  }
1567
1613
 
1568
1614
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1569
- const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(xt,void 0,4)};
1615
+ const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(Nt,void 0,4)};
1570
1616
 
1571
1617
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1572
- const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(kt,void 0,4)};
1618
+ const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(Ot,void 0,4)};
1573
1619
 
1574
1620
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1575
- const LUNORA_TABLE_COLUMNS: Record<string, Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }>> = ${JSON.stringify(vt,void 0,4)};
1621
+ const LUNORA_TABLE_COLUMNS: Record<string, Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }>> = ${JSON.stringify(Tt,void 0,4)};
1576
1622
 
1577
1623
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1578
- const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify($t,void 0,4)};
1624
+ const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(At,void 0,4)};
1579
1625
 
1580
1626
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1581
- const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(We,void 0,4)};
1627
+ const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(Qe,void 0,4)};
1582
1628
 
1583
1629
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1584
- const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(ct,void 0,4)};
1630
+ const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(ft,void 0,4)};
1585
1631
 
1586
1632
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1587
- const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(ut,void 0,4)};
1633
+ const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(bt,void 0,4)};
1588
1634
 
1589
1635
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1590
- const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(pt,void 0,4)};
1636
+ const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(yt,void 0,4)};
1591
1637
 
1592
1638
  /** 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. */
1593
- const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(ht,void 0,4)};
1639
+ const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(wt,void 0,4)};
1594
1640
 
1595
1641
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1596
- const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(gt,void 0,4)};
1642
+ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(xt,void 0,4)};
1597
1643
 
1598
1644
  /** 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. */
1599
- const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(mt,void 0,4)};
1600
- ${M}${Q.constant}${Nt}${ft}${yt}${le}${Te}${se}${Le}
1645
+ const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(kt,void 0,4)};
1646
+ ${M}${Q.constant}${It}${vt}${St}${le}${Ae}${ie}${Ce}
1601
1647
  export interface ShardDOConfig {
1602
1648
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1603
1649
  cdc?: boolean;
1604
1650
  /** 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. */
1605
1651
  observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1606
1652
  scheduler?: (env: Record<string, unknown>) => unknown;
1607
- storage?: (env: Record<string, unknown>) => unknown;${Tt}${xe}${K.configField}${P.configField}${J.configField}${j.configField}${W.configField}${U.configField}${q.configField}${Y.configField}${De}${st}${At}${Lt}${Ct}
1653
+ storage?: (env: Record<string, unknown>) => unknown;${_t}${ke}${K.configField}${E.configField}${H.configField}${j.configField}${W.configField}${U.configField}${q.configField}${Y.configField}${De}${ht}${Et}${Pt}${Ft}
1608
1654
  }
1609
1655
 
1610
1656
  const schedulerStub = {
@@ -1642,7 +1688,7 @@ const storageStub = {
1642
1688
  throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
1643
1689
  },
1644
1690
  };
1645
- ${Dt}${jt}${_t}${ve}${K.stub}${P.stub}${J.stub}${j.stub}${W.stub}${U.stub}${q.stub}${Y.stub}${h}${dt}${Mt}
1691
+ ${Mt}${zt}${qt}${$e}${K.stub}${E.stub}${H.stub}${j.stub}${W.stub}${U.stub}${q.stub}${Y.stub}${h}${mt}${Jt}
1646
1692
  // Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
1647
1693
  // referencing call fails loudly with a clear error instead of overflowing the
1648
1694
  // stack. Tracked across the awaited handler chain (one DO invocation is
@@ -1679,10 +1725,10 @@ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: R
1679
1725
  * from the worker entry so wrangler binds it by name.
1680
1726
  */
1681
1727
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1682
- class extends ShardDOBase {${Ut}
1728
+ class extends ShardDOBase {${Yt}
1683
1729
  private migrated = false;
1684
1730
 
1685
- public override async handleRpc(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
1731
+ public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker): Promise<unknown> {
1686
1732
  const registered = LUNORA_FUNCTIONS[functionPath];
1687
1733
 
1688
1734
  // Internal functions are reachable server-side only: via \`ctx.run*\`
@@ -1695,7 +1741,13 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
1695
1741
 
1696
1742
  this.ensureMigrated();
1697
1743
 
1698
- const ctx = this.buildCtx({ functionPath });
1744
+ // \`headroom\`, when the caller supplied one, is threaded straight
1745
+ // through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
1746
+ // fallback (the racy shared-field read) entirely for THIS dispatch.
1747
+ // The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
1748
+ // \`handleRunAs\` don't mint their own and omit it, so they keep the
1749
+ // prior fallback behavior unchanged.
1750
+ const ctx = this.buildCtx({ functionPath, headroom });
1699
1751
 
1700
1752
  // A mutation's writes must commit all-or-nothing: wrap its dispatch in
1701
1753
  // the DO's BEGIN/COMMIT span so any throw (a validator, an RLS denial,
@@ -1722,7 +1774,7 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
1722
1774
 
1723
1775
  return registered.handler(ctx, args);
1724
1776
  }
1725
- ${Ke.override}
1777
+ ${Je.override}
1726
1778
  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> {
1727
1779
  const registered = LUNORA_FUNCTIONS[functionPath];
1728
1780
 
@@ -1757,7 +1809,7 @@ ${Ke.override}
1757
1809
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
1758
1810
  };
1759
1811
  }
1760
- ${Rt}${St}${Bt}${Wt}
1812
+ ${Ct}${Lt}${Gt}${Xt}
1761
1813
  protected override lifecycleHookPaths(event: "connect" | "disconnect"): readonly string[] {
1762
1814
  return LUNORA_LIFECYCLE_HOOKS[event];
1763
1815
  }
@@ -1797,7 +1849,7 @@ ${Rt}${St}${Bt}${Wt}
1797
1849
  protected override studioFeatures(): StudioFeaturesResult {
1798
1850
  return LUNORA_STUDIO_FEATURES;
1799
1851
  }
1800
- ${Q.evaluateOverride}${Q.subscriptionOverride}${bt}${wt}
1852
+ ${Q.evaluateOverride}${Q.subscriptionOverride}${$t}${Rt}
1801
1853
  protected override advisories(): AdvisoryFinding[] {
1802
1854
  return LUNORA_ADVISORIES;
1803
1855
  }
@@ -1893,7 +1945,71 @@ ${Q.evaluateOverride}${Q.subscriptionOverride}${bt}${wt}
1893
1945
  return { id: args.id ?? null, op: "patch" };
1894
1946
  }
1895
1947
 
1896
- protected override async deleteRowThroughWriter(table: string, id: string): Promise<void> {
1948
+ // The base \`ShardDO\` cannot build a schema-aware writer, so its
1949
+ // \`runShardExport\`/\`runShardImport\` return \`[]\` and \`{inserted:{}}\`.
1950
+ // Those are success-shaped: an empty export is what a correct export of
1951
+ // an empty shard looks like, so a backup of a populated sharded schema
1952
+ // reported success and wrote nothing, and an import reported success and
1953
+ // dropped every row. Overriding both here is what makes the two admin
1954
+ // RPCs real for a \`.shardBy()\` table.
1955
+ //
1956
+ // NOTE: the admin export RPC is not paginated — \`parseExportShardArgs\`
1957
+ // takes \`tables\`/\`batchSize\` but no cursor, and the coordinator issues
1958
+ // one call per shard — so the rows are collected into a single response.
1959
+ // \`batchSize\` bounds the SQLite scan page, not the reply. A shard holding
1960
+ // more rows than fit in the DO's memory budget will therefore fail the
1961
+ // export rather than stream it. That is a loud failure where the bug this
1962
+ // replaces was a silent empty one, but a cursor on the RPC is what makes
1963
+ // this a complete backup path for large shards.
1964
+ protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
1965
+ this.ensureMigrated();
1966
+
1967
+ const env = (this.env ?? {}) as Record<string, unknown>;
1968
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1969
+ const writer = createShardCtxDb({
1970
+ broadcast: (delta) => {
1971
+ this.recordChangedTable(delta.table, delta.indexKeys);
1972
+ },
1973
+ cdc: config.cdc ?? false,
1974
+ scheduler,
1975
+ schema: schema as unknown as SchemaLike,
1976
+ sql: this.sql as SqlExec,
1977
+ });
1978
+
1979
+ const rows: ExportRow[] = [];
1980
+
1981
+ // \`exportShardRows\` walks in keyset batches so a large table does not
1982
+ // materialize at once inside the generator; the admin RPC's response
1983
+ // is a single array, so it is collected here rather than streamed.
1984
+ for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, { batchSize: args.batchSize, tables: args.tables })) {
1985
+ rows.push(row);
1986
+ }
1987
+
1988
+ return rows;
1989
+ }
1990
+
1991
+ protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
1992
+ this.ensureMigrated();
1993
+
1994
+ const env = (this.env ?? {}) as Record<string, unknown>;
1995
+ const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1996
+ const writer = createShardCtxDb({
1997
+ broadcast: (delta) => {
1998
+ this.recordChangedTable(delta.table, delta.indexKeys);
1999
+ },
2000
+ cdc: config.cdc ?? false,
2001
+ scheduler,
2002
+ schema: schema as unknown as SchemaLike,
2003
+ sql: this.sql as SqlExec,
2004
+ });
2005
+
2006
+ // \`importShardRows\` inserts with \`allowExplicitId\`, so a source
2007
+ // database's \`_id\`s carry across verbatim and every foreign key
2008
+ // referencing them stays valid without a second remapping pass.
2009
+ return importShardRows(writer, schema as unknown as SchemaLike, { rows: args.rows, startLine: args.startLine });
2010
+ }
2011
+
2012
+ protected override async deleteRowThroughWriter(table: string, id: string, headroom?: TransactionHeadroomTracker): Promise<void> {
1897
2013
  const definition = (schema as unknown as SchemaLike).tables[table];
1898
2014
 
1899
2015
  if (!definition) {
@@ -1915,6 +2031,13 @@ ${Q.evaluateOverride}${Q.subscriptionOverride}${bt}${wt}
1915
2031
  this.recordChangedTable(delta.table, delta.indexKeys);
1916
2032
  },
1917
2033
  cdc: config.cdc ?? false,
2034
+ // \`runShardBulkDelete\` (a normal \`/rpc\` dispatch) calls this with no
2035
+ // explicit \`headroom\`, so it falls back to \`this.transactionHeadroom()\`
2036
+ // — the SAME per-dispatch meter every other write goes through, mirroring
2037
+ // \`buildCtx\`'s \`options.headroom ?? this.transactionHeadroom()\`. The TTL
2038
+ // sweep (an alarm work item, no dispatch in flight) passes its own
2039
+ // by-value tracker explicitly instead.
2040
+ headroom: headroom ?? this.transactionHeadroom(),
1918
2041
  scheduler,
1919
2042
  schema: schema as unknown as SchemaLike,
1920
2043
  sql: this.sql as SqlExec,
@@ -2023,7 +2146,7 @@ ${Q.evaluateOverride}${Q.subscriptionOverride}${bt}${wt}
2023
2146
  // dispatch path) fall back to the per-request fields as before.
2024
2147
  const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
2025
2148
  const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
2026
- ${It}${ae}${Qt}${Se}${Ne}${$e}${Ae}
2149
+ ${Ut}${ae}${en}${Re}${Oe}${Se}${Le}
2027
2150
  const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
2028
2151
  // Build the storage adapter once and share it between \`ctx.storage\`
2029
2152
  // and \`ctx.db.system._storage\` so both read the same R2 binding. The
@@ -2050,13 +2173,13 @@ ${It}${ae}${Qt}${Se}${Ne}${$e}${Ae}
2050
2173
  // so both write to the same trace.
2051
2174
  const span = this.makeDispatchSpan(traceAnchor, observability);
2052
2175
 
2053
- ${qt} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
2176
+ ${Vt} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
2054
2177
  // adds aggregate counters (call count, total time, per-operation
2055
2178
  // breakdown) to the wide event rather than a span per call, so a
2056
2179
  // handler making hundreds of queries stays readable. See
2057
2180
  // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
2058
- const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${Pt}), logFunctionPath, traceAnchor, observability);
2059
- ${Kt}${Ce}
2181
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${Kt}), logFunctionPath, traceAnchor, observability);
2182
+ ${Zt}${Ie}
2060
2183
 
2061
2184
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
2062
2185
  // The trace anchor is threaded explicitly for the same reason \`identity\`
@@ -2064,7 +2187,7 @@ ${Kt}${Ce}
2064
2187
  // writing mutation's trace from the shared per-request field.
2065
2188
  const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
2066
2189
  const metrics = this.makeMetrics(logFunctionPath, observability);
2067
- ${Vt}
2190
+ ${nn}
2068
2191
  // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
2069
2192
  // captured ONCE so the whole handler body sees a single stable value.
2070
2193
  // Query/mutation handlers must be deterministic (they may be re-run on
@@ -2087,13 +2210,13 @@ ${Vt}
2087
2210
  ip: this.getCurrentIp(),
2088
2211
  log,
2089
2212
  metrics,
2090
- now,${Ft}
2213
+ now,${Ht}
2091
2214
  scheduler,
2092
2215
  span,
2093
2216
  storage,
2094
- trace,${Et}${ke}${Jt}${ue}${Re}${Oe}${fe}${de}
2217
+ trace,${Qt}${ve}${tn}${ue}${Ne}${Te}${fe}${de}
2095
2218
  };
2096
- ${Ht}${Gt}
2219
+ ${an}${rn}
2097
2220
  ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
2098
2221
  ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
2099
2222
  ctx.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("query", reference.__lunoraRef, fnArgs, ctx);
@@ -2101,30 +2224,30 @@ ${Ht}${Gt}
2101
2224
  return ctx;
2102
2225
  }
2103
2226
  };
2104
- `},Be=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:O(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"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?Be(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},it=(e,t)=>{const n=e.kind==="optional"&&e.inner?e.inner:e;return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},ir=(e,t,n)=>{m(e,"drizzle column name");const r=Be(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const s=it(t,n);return s!==void 0&&(o+=`.references((): AnySQLiteColumn => ${s}._id)`),r.notNull&&(o+=".notNull()"),o},sr=e=>{m(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(m(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},lr=(e,t)=>{m(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([a,o])=>` ${a}: ${ir(a,o,t)},`)].join(`
2227
+ `},We=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:C(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"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?We(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},pt=(e,t)=>{const n=e.kind==="optional"&&e.inner?e.inner:e;return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},yr=(e,t,n)=>{m(e,"drizzle column name");const r=We(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const i=pt(t,n);return i!==void 0&&(o+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(o+=".notNull()"),o},wr=e=>{m(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(m(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},xr=(e,t)=>{m(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([a,o])=>` ${a}: ${yr(a,o,t)},`)].join(`
2105
2228
  `),r=e.indexes.length>0?`, (t) => ({
2106
- ${e.indexes.map(a=>sr(a)).join(`
2229
+ ${e.indexes.map(a=>wr(a)).join(`
2107
2230
  `)}
2108
2231
  })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
2109
2232
  ${n}
2110
- }${r});`},dr=e=>e.typeAnnotation?.includes('Id<"')??!1,cr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let a=!1,o=!1;for(const s of e){for(const i of Object.values(s.shape)){const l=Be(i);n.add(l.builder),o=o||dr(l),a=a||it(i,t)!==void 0}for(const i of s.indexes)r.add(i.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((s,i)=>s.localeCompare(i)),indexes:[...r].toSorted((s,i)=>s.localeCompare(i)),needsAnyColumn:a,needsId:o}},Xe=(e,t=!1)=>{if(e.length===0)return`${k}export {};
2111
- `;const n=H(t),r=new Set(e.map(f=>f.name)),{columns:a,indexes:o,needsAnyColumn:s,needsId:i}=cr(e,r),l=[...o,...a].toSorted((f,y)=>f.localeCompare(y)),u=e.map(f=>lr(f,r)).join(`
2233
+ }${r});`},kr=e=>e.typeAnnotation?.includes('Id<"')??!1,vr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let a=!1,o=!1;for(const i of e){for(const s of Object.values(i.shape)){const l=We(s);n.add(l.builder),o=o||kr(l),a=a||pt(s,t)!==void 0}for(const s of i.indexes)r.add(s.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,s)=>i.localeCompare(s)),indexes:[...r].toSorted((i,s)=>i.localeCompare(s)),needsAnyColumn:a,needsId:o}},et=(e,t=!1)=>{if(e.length===0)return`${v}export {};
2234
+ `;const n=G(t),r=new Set(e.map(f=>f.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=vr(e,r),l=[...o,...a].toSorted((f,y)=>f.localeCompare(y)),u=e.map(f=>xr(f,r)).join(`
2112
2235
 
2113
- `),p=[s?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
2114
- `:"",i?`import type { Id } from "./dataModel.js";
2115
- `:""].join("");return`${k}import { ${l.join(", ")} } from "${n.serverDrizzle}";
2236
+ `),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
2237
+ `:"",s?`import type { Id } from "./dataModel.js";
2238
+ `:""].join("");return`${v}import { ${l.join(", ")} } from "${n.serverDrizzle}";
2116
2239
  ${p}
2117
2240
  ${u}
2118
- `},Or=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:Xe(n,t),shard:Xe(r,t)}},Tr=e=>{const t=[],n=new Map;for(const i of e){const l=n.get(i.cron);l?l.push(i):(n.set(i.cron,[i]),t.push(i.cron))}const r=t.map(i=>` ${JSON.stringify(i)},`).join(`
2241
+ `},qr=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:et(n,t),shard:et(r,t)}},Br=e=>{const t=[],n=new Map;for(const s of e){const l=n.get(s.cron);l?l.push(s):(n.set(s.cron,[s]),t.push(s.cron))}const r=t.map(s=>` ${JSON.stringify(s)},`).join(`
2119
2242
  `),a=r.length>0?`
2120
2243
  ${r}
2121
- `:"",o=[...n.entries()].map(([i,l])=>{const u=l.map(p=>{const f=p.workflow?`workflow: ${JSON.stringify(p.workflow.binding)}`:`functionPath: ${JSON.stringify(p.functionPath)}`;return` { name: ${JSON.stringify(p.name)}, ${f}, args: ${JSON.stringify(p.args)} },`}).join(`
2122
- `);return` ${JSON.stringify(i)}: [
2244
+ `:"",o=[...n.entries()].map(([s,l])=>{const u=l.map(p=>{const f=p.workflow?`workflow: ${JSON.stringify(p.workflow.binding)}`:`functionPath: ${JSON.stringify(p.functionPath)}`;return` { name: ${JSON.stringify(p.name)}, ${f}, args: ${JSON.stringify(p.args)} },`}).join(`
2245
+ `);return` ${JSON.stringify(s)}: [
2123
2246
  ${u}
2124
2247
  ],`}).join(`
2125
- `),s=o.length>0?`
2248
+ `),i=o.length>0?`
2126
2249
  ${o}
2127
- `:"";return`${k}/**
2250
+ `:"";return`${v}/**
2128
2251
  * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
2129
2252
  * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
2130
2253
  * shard; \`workflow\` is a \`WORKFLOW_*\` binding name whose durable workflow is
@@ -2148,11 +2271,11 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${a}];
2148
2271
  * Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
2149
2272
  * looks up \`event.cron\` here and dispatches every job in the list.
2150
2273
  */
2151
- export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
2152
- `},Ar=e=>{const t=[...e].toSorted((r,a)=>r.name.localeCompare(a.name)).map(r=>{const a=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&a.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&a.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&a.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&a.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${a.join(", ")} },`}).join(`
2274
+ export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${i}};
2275
+ `},jr=e=>{const t=[...e].toSorted((r,a)=>r.name.localeCompare(a.name)).map(r=>{const a=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&a.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&a.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&a.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&a.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${a.join(", ")} },`}).join(`
2153
2276
  `),n=t.length>0?`
2154
2277
  ${t}
2155
- `:"";return`${k}/**
2278
+ `:"";return`${v}/**
2156
2279
  * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
2157
2280
  * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
2158
2281
  * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
@@ -2173,4 +2296,4 @@ export interface LunoraVectorIndex {
2173
2296
  * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2174
2297
  */
2175
2298
  export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
2176
- `},Lr=e=>{const t=new Set,n=[];for(const r of e)t.has(r.cron)||(t.add(r.cron),n.push(r.cron));return n};export{xr as $,$r as G,vr as H,Sr as J,kr as N,k as R,Nr as a,_n as b,yr as c,mr as d,Ar as g,Lr as m,fr as n,Tr as p,Yt as r,Or as u,wr as x,br as y,Rr as z};
2299
+ `},Wr=e=>{const t=new Set,n=[];for(const r of e)t.has(r.cron)||(t.add(r.cron),n.push(r.cron));return n};export{jr as $,Wr as A,Dr as B,Cr as C,Ar as I,Lr as O,Ir as P,v as R,Br as S,Nn as a,Mr as b,Qn as c,Tr as g,Pr as i,Fr as l,Or as n,_r as o,ln as r,Er as s,qr as v};