@lunora/codegen 1.0.0-alpha.173 → 1.0.0-alpha.175

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.
@@ -20,9 +20,9 @@ import{agentComponent as ht}from"@lunora/agent/component";import{LunoraError as
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
- `}},En=(e,t)=>e.stringMaxLength===void 0?"":`if (${t}.length > ${String(e.stringMaxLength)}) return DEFER;
24
- `,Dn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!gt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
25
- `}},Ge=(e,t,n)=>{if(!ft(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if(Cn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Ln(e.kind,t)+En(e,t)};switch(e.kind){case"array":return _n(e,t,n);case"literal":return Dn(e,t);case"object":return Fn(e,t,n);default:return}}},_n=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),s=`__arr${String(o)}`,i=`__i${String(o)}`,a=`__e${String(o)}`,c=Ge(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
23
+ `}},Dn=(e,t)=>e.stringMaxLength===void 0?"":`if (${t}.length > ${String(e.stringMaxLength)}) return DEFER;
24
+ `,En=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!gt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
25
+ `}},Ge=(e,t,n)=>{if(!ft(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if(Cn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Ln(e.kind,t)+Dn(e,t)};switch(e.kind){case"array":return _n(e,t,n);case"literal":return En(e,t);case"object":return Fn(e,t,n);default:return}}},_n=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),s=`__arr${String(o)}`,i=`__i${String(o)}`,a=`__e${String(o)}`,c=Ge(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
26
26
  const ${s} = new Array(${t}.length);
27
27
  for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
28
28
  const ${a} = ${t}[${i}];
@@ -41,7 +41,7 @@ ${yt(t)}${o.pre}const ${i} = { ${o.entries} };
41
41
  `;return{out:i,pre:a}},Bn=e=>{let t=0;const r=bt(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
42
42
  if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
43
43
  ${yt("source")}${r.pre}return { ${r.entries} };
44
- }`},$=`// GENERATED by @lunora/codegen — do not edit.
44
+ }`},R=`// GENERATED by @lunora/codegen — do not edit.
45
45
  // Run \`lunora codegen\` to regenerate.
46
46
 
47
47
  `,ae=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},wt=/^[A-Za-z_$][\w$]*$/u,qn=/^[\w./-]+$/u,f=(e,t)=>{if(!wt.test(e))throw new X("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},He=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>wt.test(e)?e:JSON.stringify(e),Y=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),jn={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(!gt.test(e))throw new X("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},O=e=>{const t=jn[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 f(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Wn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>kt(r,o)).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"}},kt=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?O(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${O(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>kt(n,r)).join("; ")} }`},xt=e=>e.kind==="optional"||!!e.column?.hasDefault,se=e=>e.kind==="optional"&&e.inner?e.inner:e,Un=e=>{f(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=se(o),i=O(s),a=q(r);return xt(o)?` ${a}?: ${i};`:` ${a}: ${i};`}).join(`
@@ -49,13 +49,13 @@ ${yt("source")}${r.pre}return { ${r.entries} };
49
49
  ${t}
50
50
  `:"";return`export interface Insert_${e.name} {
51
51
  _id?: Id<"${e.name}">;
52
- _creationTime?: number;${n}}`},Je="schema",lo=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const S=q(x);if(v.kind==="optional"){const N=v.inner?O(v.inner):"unknown";return` ${S}?: ${N};`}return` ${S}: ${O(v)};`}).join(`
52
+ _creationTime?: number;${n}}`},Je="schema",lo=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const $=q(x);if(v.kind==="optional"){const N=v.inner?O(v.inner):"unknown";return` ${$}?: ${N};`}return` ${$}: ${O(v)};`}).join(`
53
53
  `),b=l?`
54
54
  ${l}
55
- `:"",R=u.commitOrdered===!0?`
55
+ `:"",S=u.commitOrdered===!0?`
56
56
  _commitSeq: number;`:"";return`export interface Doc_${u.name} {
57
57
  _id: Id<"${u.name}">;
58
- _creationTime: number;${R}${b}}`}).join(`
58
+ _creationTime: number;${S}${b}}`}).join(`
59
59
 
60
60
  `),o=e.tables.map(u=>` ${u.name}: Doc_${u.name};`).join(`
61
61
  `),s=e.tables.map(u=>{const l=u.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
@@ -69,7 +69,7 @@ ${l}
69
69
  `);return l?` ${u.name}: {
70
70
  ${l}
71
71
  };`:` ${u.name}: {};`}).join(`
72
- `);return E(`${$}export type TableName = ${t};
72
+ `);return D(`${R}export type TableName = ${t};
73
73
 
74
74
  /**
75
75
  * The tables **this app declared** — every {@link TableName} except those an add-on
@@ -161,7 +161,7 @@ export interface Relations {
161
161
  ${y}
162
162
  }
163
163
 
164
- `,Je)},Kn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,vt=/^(?:\.\.?\/)*_generated\//u,Rt=/\.[A-Za-z]\w*$/u,Qn=e=>e.replaceAll(Kn,(t,n)=>{const r=n.replace(vt,"./");return`import("${Rt.test(r)?r:`${r}.js`}")`}),Vn=/import\("(?<spec>[^"]+)"\)/gu,dt="node_modules/",Hn=/^@types\//u,Gn=e=>e.replaceAll(Vn,(t,n)=>{const r=n.lastIndexOf(dt);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+dt.length);return o===""||Hn.test(o)?t:`import("${o}")`}),Jn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,zn=/^(?:\.\.?\/)+/u,Yn=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("/")},Xn=(e,t)=>e.replaceAll(Jn,(n,r)=>{if(vt.test(r.replace(zn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Yn(`${o}/${r}`)}`;return`import("${Rt.test(i)?i:`${i}.js`}")`}),E=(e,t)=>Qn(Xn(Gn(e),t)),Zn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],er=new RegExp(String.raw`import\("@lunora/(?<pkg>${Zn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),tr={flags:new Set(["/web"]),platform:new Set},St=(e,t)=>t?e.replaceAll(er,(n,r,o)=>{const s=tr[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),$t=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:O(e.output),Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},ut=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=E(xe(s.args),s.filePath),a=E($t(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
164
+ `,Je)},Kn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,vt=/^(?:\.\.?\/)*_generated\//u,Rt=/\.[A-Za-z]\w*$/u,Qn=e=>e.replaceAll(Kn,(t,n)=>{const r=n.replace(vt,"./");return`import("${Rt.test(r)?r:`${r}.js`}")`}),Vn=/import\("(?<spec>[^"]+)"\)/gu,dt="node_modules/",Hn=/^@types\//u,Gn=e=>e.replaceAll(Vn,(t,n)=>{const r=n.lastIndexOf(dt);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+dt.length);return o===""||Hn.test(o)?t:`import("${o}")`}),Jn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,zn=/^(?:\.\.?\/)+/u,Yn=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("/")},Xn=(e,t)=>e.replaceAll(Jn,(n,r)=>{if(vt.test(r.replace(zn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Yn(`${o}/${r}`)}`;return`import("${Rt.test(i)?i:`${i}.js`}")`}),D=(e,t)=>Qn(Xn(Gn(e),t)),Zn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],er=new RegExp(String.raw`import\("@lunora/(?<pkg>${Zn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),tr={flags:new Set(["/web"]),platform:new Set},St=(e,t)=>t?e.replaceAll(er,(n,r,o)=>{const s=tr[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),$t=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:O(e.output),Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},ut=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=D(xe(s.args),s.filePath),a=D($t(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
165
165
  `);return` ${q(T(n))}: {
166
166
  ${o}
167
167
  };`};return Ye(e).map(n=>t(n)).join(`
@@ -207,7 +207,7 @@ ${i}
207
207
  */
208
208
  const lunoraAgentRuntimeFunctions = agentComponent().functions;
209
209
  `}},sr=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>T(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new X("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
210
- `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},ir=(e,t)=>{if(e.length===0)return[];const n=Tt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},lr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>T(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}))},cr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=E(d.chunkType??"unknown",d.filePath),g=E(xe(d.searchParams),d.filePath),y=E(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${p}, ${g}, ${y}>;`}).join(`
210
+ `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},ir=(e,t)=>{if(e.length===0)return[];const n=Tt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},lr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>T(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}))},cr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=D(d.chunkType??"unknown",d.filePath),g=D(xe(d.searchParams),d.filePath),y=D(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${p}, ${g}, ${y}>;`}).join(`
211
211
  `);return` ${q(T(i))}: {
212
212
  ${c}
213
213
  };`}).join(`
@@ -228,11 +228,11 @@ ${o}
228
228
  ${g}
229
229
  ${y.body}`,l=ze(u),b=l.length>0?`
230
230
  import type { ${l.join(", ")} } from "./dataModel.js";
231
- `:"",R=p?`
231
+ `:"",S=p?`
232
232
  ${p}
233
233
  `:"",x=g?`
234
234
  ${g}
235
- `:"",v=nr(i,t),S=`export interface ApiTypes {${R}}
235
+ `:"",v=nr(i,t),$=`export interface ApiTypes {${S}}
236
236
 
237
237
  export const api = anyApi as unknown as ApiTypes;
238
238
 
@@ -240,10 +240,10 @@ export const api = anyApi as unknown as ApiTypes;
240
240
  export interface InternalApiTypes {${x}}
241
241
 
242
242
  export const internal = anyApi as unknown as InternalApiTypes;
243
- ${v.block}${y.block}`,N=[...S.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],Q=N.length>0?`import type { ${N.join(", ")} } from "${a.client}";
244
- `:"";return St(`${$}import { anyApi } from "${a.client}";
243
+ ${v.block}${y.block}`,N=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],Q=N.length>0?`import type { ${N.join(", ")} } from "${a.client}";
244
+ `:"";return St(`${R}import { anyApi } from "${a.client}";
245
245
  ${Q}${v.importLine}${b}
246
- ${S}`,s)},uo=e=>e?`${$}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
246
+ ${$}`,s)},uo=e=>e?`${R}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
247
247
  import type { SeedClient, SeedClientOptions } from "@lunora/seed";
248
248
 
249
249
  import schema from "../schema.js";
@@ -260,7 +260,7 @@ import type { InsertModel } from "./dataModel.js";
260
260
  * const { posts } = await seed.posts((x) => x([10, 20]));
261
261
  */
262
262
  export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
263
- `:"",po=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=ae(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,s=e.map(c=>{f(c.exportName,"shape export name");const d=o(c),p=E(xe(c.args),c.filePath),g=Object.keys(c.args).length>0,y=g?` args: ${p};`:` args?: ${p};`,u=g?`(args: ${p}) => void`:`(args?: ${p}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
263
+ `:"",po=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=ae(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,s=e.map(c=>{f(c.exportName,"shape export name");const d=o(c),p=D(xe(c.args),c.filePath),g=Object.keys(c.args).length>0,y=g?` args: ${p};`:` args?: ${p};`,u=g?`(args: ${p}) => void`:`(args?: ${p}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
264
264
  export interface ${He(l)} {
265
265
  ${y}
266
266
  /**
@@ -307,7 +307,7 @@ export const ${c.exportName}Collection = (
307
307
  };`}).join(`
308
308
 
309
309
  `),i=ze(s),a=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
310
- `:"";return`${$}import type { LunoraClient, SubscriptionError } from "${r.client}";
310
+ `:"";return`${R}import type { LunoraClient, SubscriptionError } from "${r.client}";
311
311
  import { lunoraCollectionOptions } from "@lunora/db/collections";
312
312
  import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
313
313
  import type { Collection } from "@tanstack/db";
@@ -358,7 +358,7 @@ ${y}
358
358
  ${c}
359
359
  `:"",mutatorPaths:g,shapeBody:p.length>0?`
360
360
  ${p}
361
- `:""}},hr=e=>{const t=Ye(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=E(xe(a.args),a.filePath),d=c==="{}"?"?":"",p=E($t(a),a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
361
+ `:""}},hr=e=>{const t=Ye(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=D(xe(a.args),a.filePath),d=c==="{}"?"?":"",p=D($t(a),a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
362
362
  `);return` ${q(T(o))}: {
363
363
  ${i}
364
364
  };`}).join(`
@@ -366,12 +366,12 @@ ${i}
366
366
  `);return` ${Y(i)}: {
367
367
  ${a}
368
368
  },`}).join(`
369
- `),types:n}},mr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=se(o);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&n.add(s.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},ho=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:o=!1,hasAnalytics:s=!1,hasBrowser:i=!1,hasVectors:a=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:p=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:R=!1,identity:x,queues:v=[],schema:S,storageRuleBuckets:N=[],useUmbrella:Q=!1,workflows:A=[]}={})=>{const C=ae(Q),w=mr(S??{tables:[]},N).map(h=>JSON.stringify(h)).join(" | "),P=o?`import type { LunoraAi } from "@lunora/ai";
369
+ `),types:n}},mr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const s=se(o);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&n.add(s.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},ho=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:o=!1,hasAnalytics:s=!1,hasBrowser:i=!1,hasVectors:a=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:p=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:S=!1,identity:x,queues:v=[],schema:$,storageRuleBuckets:N=[],useUmbrella:Q=!1,workflows:A=[]}={})=>{const C=ae(Q),w=mr($??{tables:[]},N).map(h=>JSON.stringify(h)).join(" | "),P=o?`import type { LunoraAi } from "@lunora/ai";
370
370
  `:"",M=o?`
371
371
  readonly ai: LunoraAi;`:"",ie=u?`import type { LunoraPayment } from "@lunora/payment";
372
372
  `:"",le=u?`
373
- readonly payments: LunoraPayment;`:"",Z=R?`import type { X402Pay } from "@lunora/x402/pay";
374
- `:"",V=R?`
373
+ readonly payments: LunoraPayment;`:"",Z=S?`import type { X402Pay } from "@lunora/x402/pay";
374
+ `:"",V=S?`
375
375
  readonly x402: X402Pay;`:"",L=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
376
376
  `:"",ee=t.length>0?`
377
377
  readonly containers: {${t.map(h=>`
@@ -399,7 +399,7 @@ ${k}`:""}
399
399
  }
400
400
 
401
401
  /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
402
- export type Env = CloudflareBindings;`,F=(h,We,Te)=>{const re=In.get(h);if(re!==void 0&&re.tier!==Te)throw new X("INTERNAL",`@lunora/codegen: capability "${h}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Te}" context — update whichever is wrong.`);return We?re?.field??"":""},ce=F("kv",g,"every"),de=F("analytics",s,"every"),Oe=F("hyperdrive",d,"action"),Ie=F("browser",i,"action"),Ce=F("images",p,"action"),ue=F("pipelines",l,"action"),H=F("r2sql",b,"action"),_=a&&(S?.vectorIndexes.length??0)>0,G=_?' | "vectors"':"",te=_?`
402
+ export type Env = CloudflareBindings;`,F=(h,We,Te)=>{const re=In.get(h);if(re!==void 0&&re.tier!==Te)throw new X("INTERNAL",`@lunora/codegen: capability "${h}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Te}" context — update whichever is wrong.`);return We?re?.field??"":""},ce=F("kv",g,"every"),de=F("analytics",s,"every"),Oe=F("hyperdrive",d,"action"),Ie=F("browser",i,"action"),Ce=F("images",p,"action"),ue=F("pipelines",l,"action"),H=F("r2sql",b,"action"),_=a&&($?.vectorIndexes.length??0)>0,G=_?' | "vectors"':"",te=_?`
403
403
  readonly vectors: VectorSearch<VectorIndexName>;`:"",pe=_?`
404
404
  readonly vectors: VectorSearchReader<VectorIndexName>;`:"",J=_?`import type { VectorSearch, VectorSearchReader } from "${C.server}";
405
405
  import type { VectorIndexName } from "./dataModel.js";
@@ -427,9 +427,9 @@ export interface LunoraWorkflows {
427
427
  ${A.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
428
428
  `)}
429
429
  }`:"",ve=B?' | "workflows"':"",Re=B?`
430
- readonly workflows: LunoraWorkflows;`:"",he=v.length>0,Ee=he?`import type { QueueProducer } from "@lunora/queue";
430
+ readonly workflows: LunoraWorkflows;`:"",he=v.length>0,De=he?`import type { QueueProducer } from "@lunora/queue";
431
431
  import type * as lunoraQueueDefinitions from "../queues.js";
432
- `:"",De=he?`
432
+ `:"",Ee=he?`
433
433
 
434
434
  /** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
435
435
  type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
@@ -460,7 +460,7 @@ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: (
460
460
  `:"",je=n?`
461
461
 
462
462
  /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
463
- export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",be=n?' | "env"':"",ye=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${$}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${C.server}";
463
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",be=n?' | "env"':"",ye=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${R}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${C.server}";
464
464
  import type {
465
465
  ActionBuilder,
466
466
  ActionCtx as ActionCtxBase,
@@ -517,7 +517,7 @@ export type {
517
517
  } from "${C.serverDataModel}";
518
518
 
519
519
  import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
520
- ${J}${P}${ie}${Z}${L}${ne}${Ee}${_e}${Me}${qe}
520
+ ${J}${P}${ie}${Z}${L}${ne}${De}${_e}${Me}${qe}
521
521
  export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
522
522
 
523
523
  /**
@@ -577,7 +577,7 @@ export interface OrmWriter extends OrmReader {
577
577
  }
578
578
 
579
579
  /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
580
- export type StorageBucketName = ${w};${Ae}${Le}${De}${Pe}${Fe}${je}
580
+ export type StorageBucketName = ${w};${Ae}${Le}${Ee}${Pe}${Fe}${je}
581
581
 
582
582
  /**
583
583
  * Project-typed contexts. The base contexts from \`@lunora/server\` are
@@ -730,8 +730,8 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Be}>();
730
730
  export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
731
731
  id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
732
732
  };
733
- `},gr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${T(n.filePath)}:${n.exportName}`);return t},mo=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=ae(i),{dispatchBody:p,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=pr(n,r,o,s),R=ar(t,n),x=sr(a,n),v=[R.lines,x.lines].filter(k=>k.length>0).join(`
734
- `);let S=p;v.length>0&&(S=p.length>0?`${p.trimEnd()}
733
+ `},gr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${T(n.filePath)}:${n.exportName}`);return t},mo=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:a=!1}=e,c=n.length>0,d=ae(i),{dispatchBody:p,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=pr(n,r,o,s),S=ar(t,n),x=sr(a,n),v=[S.lines,x.lines].filter(k=>k.length>0).join(`
734
+ `);let $=p;v.length>0&&($=p.length>0?`${p.trimEnd()}
735
735
  ${v}
736
736
  `:`
737
737
  ${v}
@@ -766,7 +766,7 @@ ${M.implementation}
766
766
  `:"",Z=ze(M.types),V=Z.length>0?`import type { ${Z.join(", ")} } from "./dataModel.js";
767
767
  `:"",L=c?"context":"_context",ee=c?`${ur}
768
768
 
769
- `:"";return St(`${$}${g}${R.importLine}${x.importLine}${w}${Q}import { LunoraError } from "${d.server}";
769
+ `:"";return St(`${R}${g}${S.importLine}${x.importLine}${w}${Q}import { LunoraError } from "${d.server}";
770
770
  import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
771
771
  ${V}
772
772
  /**
@@ -805,12 +805,12 @@ export interface RegisteredLunoraFunction {
805
805
  */
806
806
  x402?: { readonly price: number | string };
807
807
  }
808
- ${R.prelude}${x.prelude}
808
+ ${S.prelude}${x.prelude}
809
809
  /**
810
810
  * Static dispatch table. The key matches the \`__lunoraRef\` the client
811
811
  * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
812
812
  */
813
- export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${S}};
813
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${$}};
814
814
  ${P}${A}${C}
815
815
  /**
816
816
  * Lifecycle manifest: the function paths the generated ShardDO dispatches when a
@@ -925,7 +925,7 @@ const aiStub: LunoraAi = {
925
925
  const ${e} = {
926
926
  ${s}
927
927
  }${r};
928
- `},D={build:"",configField:"",contextField:"",importLines:[],stub:""},$r=e=>e?{build:`
928
+ `},E={build:"",configField:"",contextField:"",importLines:[],stub:""},$r=e=>e?{build:`
929
929
  const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
930
930
  // KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
931
931
  // when a value changes — a subscription that read one can never be proven
@@ -939,24 +939,24 @@ ${s}
939
939
  ]);
940
940
  `,configField:`
941
941
  kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
942
- kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:I("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:D,Tr=(e,t)=>e?{build:`
942
+ kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:I("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:E,Tr=(e,t)=>e?{build:`
943
943
  const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
944
944
  provider: () => config.flags?.(env),
945
945
  targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
946
946
  });
947
947
  `,configField:`
948
948
  flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
949
- flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:D,Nr=e=>e?{build:`
949
+ flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:E,Nr=e=>e?{build:`
950
950
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
951
951
  `,configField:"",contextField:`
952
952
  notify,
953
- push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,Ar=e=>e?{build:`
953
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:E,Ar=e=>e?{build:`
954
954
  const envConfig = lunoraEnvContract.${e.exportName}(env);
955
955
  `,configField:"",contextField:`
956
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,Or=e=>e?{build:`
956
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:E,Or=e=>e?{build:`
957
957
  const access = accessFacade(identity, userId);
958
958
  `,configField:"",contextField:`
959
- access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,Ir=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=a=>`
959
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:E,Ir=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=a=>`
960
960
  const env = (this.env ?? {}) as Record<string, unknown>;
961
961
  const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
962
962
  provider: () => config.flags?.(env),
@@ -1023,20 +1023,20 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
1023
1023
  const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
1024
1024
  `,configField:`
1025
1025
  analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
1026
- analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:I("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:D,Lr=e=>e?{build:`
1026
+ analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:I("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:E,Lr=e=>e?{build:`
1027
1027
  const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
1028
1028
  const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
1029
1029
  `,configField:`
1030
1030
  images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
1031
- images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:I("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:D,Er=e=>e?{build:`
1031
+ images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:I("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:E,Dr=e=>e?{build:`
1032
1032
  const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
1033
1033
  `,configField:`
1034
1034
  sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
1035
- sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:I("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:D,Dr=e=>e?{build:`
1035
+ sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:I("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:E,Er=e=>e?{build:`
1036
1036
  const browser: Browser = config.browser ? config.browser(env) : browserStub;
1037
1037
  `,configField:`
1038
1038
  browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
1039
- browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:I("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:D,_r=e=>e?{build:`
1039
+ browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:I("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["connect","content","launch","pdf","scrape","screenshot","sessions"])}:E,_r=e=>e?{build:`
1040
1040
  const r2sqlEnv = env as Record<string, unknown>;
1041
1041
  const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
1042
1042
  const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
@@ -1047,18 +1047,18 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
1047
1047
  ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
1048
1048
  : r2sqlStub;
1049
1049
  `,configField:`
1050
- r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:I("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:D,Pr=e=>e?{build:`
1050
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:I("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:E,Pr=e=>e?{build:`
1051
1051
  const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
1052
1052
  const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
1053
1053
  `,configField:`
1054
- pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:D,go=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(f(s.exportName,`container export "${s.exportName}"`),f(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
1054
+ pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,go=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(s=>(f(s.exportName,`container export "${s.exportName}"`),f(s.className,`container class "${s.className}"`),`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
1055
1055
  export class ${s.className} extends LunoraContainer {
1056
1056
  public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1057
1057
  super(ctx, env, ${s.exportName}, "${s.exportName}"${n});
1058
1058
  }
1059
1059
  }
1060
1060
  `)).join(`
1061
- `),o=e.map(s=>s.exportName).join(", ");return`${$}/**
1061
+ `),o=e.map(s=>s.exportName).join(", ");return`${R}/**
1062
1062
  * Container-enabled Durable Object classes for the containers declared in
1063
1063
  * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
1064
1064
  * requires each \`containers[].class_name\` to be exported by the worker:
@@ -1092,7 +1092,7 @@ export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.e
1092
1092
  }
1093
1093
  }
1094
1094
  `)).join(`
1095
- `),n=e.map(r=>r.exportName).join(", ");return`${$}/**
1095
+ `),n=e.map(r=>r.exportName).join(", ");return`${R}/**
1096
1096
  * WorkflowEntrypoint classes for the workflows declared in
1097
1097
  * \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
1098
1098
  * requires each \`workflows[].class_name\` to be exported by the worker:
@@ -1127,7 +1127,7 @@ export class ${d} extends VoiceSessionDO {
1127
1127
  }
1128
1128
  }
1129
1129
  `;return`${c}${g}`}).join(`
1130
- `),o=e.map(a=>a.exportName).join(", ");return`${$}/**
1130
+ `),o=e.map(a=>a.exportName).join(", ");return`${R}/**
1131
1131
  * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
1132
1132
  * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
1133
1133
  * Workflow. Re-export them from your worker entry — wrangler requires each
@@ -1142,7 +1142,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
1142
1142
  import { ${o} } from "../agents.js";
1143
1143
 
1144
1144
  ${r}`},yo=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)f(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
1145
- `);return`${$}/**
1145
+ `);return`${R}/**
1146
1146
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
1147
1147
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
1148
1148
  * by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
@@ -1201,10 +1201,10 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1201
1201
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1202
1202
  : x402Stub;
1203
1203
  `,configField:`
1204
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Qr=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],wo=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:S=!1,maskMetadata:N,mutators:Q=[],queues:A=[],rlsMetadata:C,schema:w,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const L=ae(Z),ee=Q.length>0,k=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
1204
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Qr=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],wo=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:S=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:$=!1,maskMetadata:N,mutators:Q=[],queues:A=[],rlsMetadata:C,schema:w,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const L=ae(Z),ee=Q.length>0,k=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
1205
1205
  /** 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. */
1206
1206
  const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Tn(P))}, json: ${JSON.stringify(Ae)} };
1207
- `,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=Sr(a),ue=Or(i),H=$r(u),_=Tr(p,L.flags),G=Ir(s,p,L.flags),te=Nr(l),pe=Ar(o),J=Cr(c),j=Lr(y),W=Er(g),U=Dr(d),B=_r(x),ne=Pr(R),{build:Le,contextField:ve,importLines:Re,specs:he}=Br(A),{build:Ee,contextField:De,importLines:Se,specs:me}=Mr(r,w.jurisdiction),{build:_e,contextField:Pe,importLines:$e,specs:Me}=Fr(V),{build:Fe,contextField:ge,importLines:fe,specs:Be}=qr(n),{build:qe,configField:je,contextField:be,imports:ye,stub:Ze}=Ur(b),{build:h,configField:We,imports:Te,stub:re}=Kr(S),Ot=e,It=t,et=C??{policies:[],roles:[]},Ct=N??{columns:[]},Lt=ie??{rules:[]},Et=le??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Dt,override:_t}=jr(V),{constant:Pt,override:Mt}=Wr(A),K=v&&w.vectorIndexes.length>0,tt=new Set(w.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&w.vectorIndexes.some(m=>tt.has(m.table)),we=w.tables.some(m=>m.shardMode==="global"),Ue=w.tables.some(m=>Nn(m)),nt=w.tables.some(m=>An(m)),oe=w.tables.some(m=>m.externalSource!==void 0),rt=w.tables.some(m=>m.memory===!0),Ke=w.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(nt&&Ue)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=w.tables.length>0,Ft=fr(w),Bt=yr(w),qt=vr(w),jt=br(w),ot=wr(w),at=Qr(K,V.length>0,A.length>0,p,Ke);k&&at.push("WhereInput");const st=Rr(we),Wt=k?`
1207
+ `,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=Sr(a),ue=Or(i),H=$r(u),_=Tr(p,L.flags),G=Ir(s,p,L.flags),te=Nr(l),pe=Ar(o),J=Cr(c),j=Lr(y),W=Dr(g),U=Er(d),B=_r(x),ne=Pr(S),{build:Le,contextField:ve,importLines:Re,specs:he}=Br(A),{build:De,contextField:Ee,importLines:Se,specs:me}=Mr(r,w.jurisdiction),{build:_e,contextField:Pe,importLines:$e,specs:Me}=Fr(V),{build:Fe,contextField:ge,importLines:fe,specs:Be}=qr(n),{build:qe,configField:je,contextField:be,imports:ye,stub:Ze}=Ur(b),{build:h,configField:We,imports:Te,stub:re}=Kr($),Ot=e,It=t,et=C??{policies:[],roles:[]},Ct=N??{columns:[]},Lt=ie??{rules:[]},Dt=le??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Et,override:_t}=jr(V),{constant:Pt,override:Mt}=Wr(A),K=v&&w.vectorIndexes.length>0,tt=new Set(w.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&w.vectorIndexes.some(m=>tt.has(m.table)),we=w.tables.some(m=>m.shardMode==="global"),Ue=w.tables.some(m=>Nn(m)),nt=w.tables.some(m=>An(m)),oe=w.tables.some(m=>m.externalSource!==void 0),rt=w.tables.some(m=>m.memory===!0),Ke=w.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(nt&&Ue)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=w.tables.length>0,Ft=fr(w),Bt=yr(w),qt=vr(w),jt=br(w),ot=wr(w),at=Qr(K,V.length>0,A.length>0,p,Ke);k&&at.push("WhereInput");const st=Rr(we),Wt=k?`
1208
1208
  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 {
1209
1209
  const shape = LUNORA_SHAPES[name];
1210
1210
 
@@ -1613,15 +1613,15 @@ ${w.tables.map(m=>` facade[${JSON.stringify(m.name)}] = bindTableFaca
1613
1613
  `:"",wn=`${ue.build}${H.build}${_.build}${J.build}${pe.build}
1614
1614
  const secrets = createSecrets(env);
1615
1615
  `,kn=`${ue.contextField}${H.contextField}${_.contextField}${te.contextField}${J.contextField}${pe.contextField}
1616
- secrets,`,xn=te.build,ct=y||g||d||x||R||S,vn=ct?`
1616
+ secrets,`,xn=te.build,ct=y||g||d||x||S||$,vn=ct?`
1617
1617
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1618
1618
  // and attached only for an \`action\` so query/mutation ctx never carry them.
1619
1619
  if (isAction) {
1620
- ${j.build}${W.build}${U.build}${B.build}${ne.build}${h}${[...y?[" ctx.images = images;"]:[],...g?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...x?[" ctx.r2sql = r2sql;"]:[],...R?[" ctx.pipelines = pipelines;"]:[],...S?[" ctx.x402 = x402;"]:[]].join(`
1620
+ ${j.build}${W.build}${U.build}${B.build}${ne.build}${h}${[...y?[" ctx.images = images;"]:[],...g?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...x?[" ctx.r2sql = r2sql;"]:[],...S?[" ctx.pipelines = pipelines;"]:[],...$?[" ctx.x402 = x402;"]:[]].join(`
1621
1621
  `)}
1622
1622
  }
1623
1623
  `:"",Rn=ct?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1624
- `:"";return`${$}${ke.join(`
1624
+ `:"";return`${R}${ke.join(`
1625
1625
  `)}
1626
1626
 
1627
1627
  type FunctionKind = "action" | "mutation" | "query";
@@ -1664,8 +1664,8 @@ const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(Ct,void 0,4)};
1664
1664
  const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Lt,void 0,4)};
1665
1665
 
1666
1666
  /** 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. */
1667
- const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(Et,void 0,4)};
1668
- ${F}${G.constant}${Dt}${Pt}${me}${Me}${he}${Be}
1667
+ const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(Dt,void 0,4)};
1668
+ ${F}${G.constant}${Et}${Pt}${me}${Me}${he}${Be}
1669
1669
  export interface ShardDOConfig {
1670
1670
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1671
1671
  cdc?: boolean;
@@ -2241,7 +2241,7 @@ ${Ke?`
2241
2241
  // dispatch path) fall back to the per-request fields as before.
2242
2242
  const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
2243
2243
  const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
2244
- ${an}${de}${wn}${Ee}${_e}${Le}${Fe}
2244
+ ${an}${de}${wn}${De}${_e}${Le}${Fe}
2245
2245
  // Which dispatch this ctx belongs to. Drives the two deferral facades
2246
2246
  // below and the \`ctx.run*\` caller guard; a ctx built for an
2247
2247
  // admin/lifecycle path has no registered function, and so no kind.
@@ -2369,7 +2369,7 @@ ${xn}
2369
2369
  scheduler,
2370
2370
  span,
2371
2371
  storage: contextStorage,
2372
- trace,${cn}${Ie}${kn}${be}${De}${Pe}${ve}${ge}
2372
+ trace,${cn}${Ie}${kn}${be}${Ee}${Pe}${ve}${ge}
2373
2373
  };
2374
2374
  ${Rn}${vn}
2375
2375
  ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx, contextKind);
@@ -2410,15 +2410,25 @@ ${e.indexes.map(o=>Hr(o)).join(`
2410
2410
  `)}
2411
2411
  })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
2412
2412
  ${n}
2413
- }${r});`},Jr=e=>e.typeAnnotation?.includes('Id<"')??!1,zr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Xe(a);n.add(c.builder),s=s||Jr(c),o=o||At(a,t)!==void 0}for(const a of i.indexes)r.add(a.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,a)=>i.localeCompare(a)),indexes:[...r].toSorted((i,a)=>i.localeCompare(a)),needsAnyColumn:o,needsId:s}},pt=(e,t=!1)=>{if(e.length===0)return`${$}export {};
2413
+ }${r});`},Jr=e=>e.typeAnnotation?.includes('Id<"')??!1,zr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Xe(a);n.add(c.builder),s=s||Jr(c),o=o||At(a,t)!==void 0}for(const a of i.indexes)r.add(a.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,a)=>i.localeCompare(a)),indexes:[...r].toSorted((i,a)=>i.localeCompare(a)),needsAnyColumn:o,needsId:s}},pt=(e,t=!1)=>{if(e.length===0)return`${R}export {};
2414
2414
  `;const n=ae(t),r=new Set(e.map(g=>g.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=zr(e,r),c=[...s,...o].toSorted((g,y)=>g.localeCompare(y)),d=e.map(g=>Gr(g,r)).join(`
2415
2415
 
2416
2416
  `),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
2417
2417
  `:"",a?`import type { Id } from "./dataModel.js";
2418
- `:""].join("");return`${$}import { ${c.join(", ")} } from "${n.serverDrizzle}";
2418
+ `:""].join("");return`${R}import { ${c.join(", ")} } from "${n.serverDrizzle}";
2419
2419
  ${p}
2420
2420
  ${d}
2421
- `},ko=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:E(pt(n,t),Je),shard:E(pt(r,t),Je)}},xo=e=>{const t=new Map;for(const i of e){const a=t.get(i.cron);a?a.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
2421
+ `},ko=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:D(pt(n,t),Je),shard:D(pt(r,t),Je)}},xo=e=>e?`${R}/**
2422
+ * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
2423
+ * forward it — wrangler binds only what the entry exports:
2424
+ *
2425
+ * \`export * from "./lunora/_generated/scheduler.js";\`
2426
+ *
2427
+ * A Vite-first (class-A) app needs no such line: the generated worker entry
2428
+ * forwards this module for you whenever it exists.
2429
+ */
2430
+ export { SchedulerDO } from "@lunora/scheduler";
2431
+ `:"",vo=e=>{const t=new Map;for(const i of e){const a=t.get(i.cron);a?a.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
2422
2432
  `),r=n.length>0?`
2423
2433
  ${n}
2424
2434
  `:"",o=[...t.entries()].map(([i,a])=>{const c=a.map(d=>{const p=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${p}, args: ${JSON.stringify(d.args)} },`}).join(`
@@ -2427,7 +2437,7 @@ ${c}
2427
2437
  ],`}).join(`
2428
2438
  `),s=o.length>0?`
2429
2439
  ${o}
2430
- `:"";return`${$}/**
2440
+ `:"";return`${R}/**
2431
2441
  * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
2432
2442
  * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
2433
2443
  * shard; \`workflow\` is a \`WORKFLOW_*\` binding name whose durable workflow is
@@ -2452,10 +2462,10 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
2452
2462
  * looks up \`event.cron\` here and dispatches every job in the list.
2453
2463
  */
2454
2464
  export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${s}};
2455
- `},vo=e=>{const t=[...e].toSorted((r,o)=>r.name.localeCompare(o.name)).map(r=>{const o=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&o.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&o.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&o.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&o.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${o.join(", ")} },`}).join(`
2465
+ `},Ro=e=>{const t=[...e].toSorted((r,o)=>r.name.localeCompare(o.name)).map(r=>{const o=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&o.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&o.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&o.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&o.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${o.join(", ")} },`}).join(`
2456
2466
  `),n=t.length>0?`
2457
2467
  ${t}
2458
- `:"";return`${$}/**
2468
+ `:"";return`${R}/**
2459
2469
  * One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
2460
2470
  * or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
2461
2471
  * for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
@@ -2476,4 +2486,4 @@ export interface LunoraVectorIndex {
2476
2486
  * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2477
2487
  */
2478
2488
  export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
2479
- `},Ro=e=>[...new Set(e.map(t=>t.cron))];export{io as A,On as C,$ as G,Zn as U,co as a,po as b,go as c,xo as d,bo as e,lo as f,ko as g,mo as h,ho as i,wo as j,vo as k,fo as l,Ro as m,br as n,yo as o,uo as p};
2489
+ `},So=e=>[...new Set(e.map(t=>t.cron))];export{io as A,On as C,R as G,Zn as U,co as a,po as b,go as c,vo as d,bo as e,lo as f,ko as g,mo as h,xo as i,ho as j,wo as k,Ro as l,fo as m,So as n,br as o,yo as p,uo as q};