@lunora/codegen 1.0.0-alpha.70 → 1.0.0-alpha.71
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.
- package/dist/index.d.mts +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/GENERATED_HEADER-DV-sQj-R.mjs +1 -0
- package/dist/packem_shared/{OPENRPC_VERSION-BcivFYIX.mjs → OPENRPC_VERSION-CvVFqUlq.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-DVjBK4ud.mjs → SCHEMA_SNAPSHOT_FILENAME-CDCj-7wp.mjs} +3 -3
- package/dist/packem_shared/{buildOpenApiDocument-BJudKDP_.mjs → buildOpenApiDocument-CXFC-wzM.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-Cy4OQ0Cu.mjs +1 -0
- package/dist/packem_shared/{emit-Bp0nOR_O.mjs → emit-D7VIjvlm.mjs} +141 -137
- package/dist/packem_shared/{emitApp-Cm9yVOpP.mjs → emitApp-CAeIj6e_.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/GENERATED_HEADER-Sl8NoQFl.mjs +0 -1
- package/dist/packem_shared/discoverSchema-m2voTncu.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as
|
|
1
|
+
import{agentComponent as Ye}from"@lunora/agent/component";import{LunoraError as Y}from"@lunora/errors";import{n as v}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:`
|
|
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,38 +15,38 @@ import{agentComponent as Ge}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"}],Ut=
|
|
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"}],Ut=Ze,Kt=new Map(Ut.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),rr=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,Qt=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),tt=e=>e.column!==void 0,Jt=(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
|
-
`}},
|
|
24
|
-
`}},
|
|
23
|
+
`}},Vt=(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(Qt.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Jt(e.kind,t)};switch(e.kind){case"array":return Gt(e,t,n);case"literal":return Vt(e,t);case"object":return zt(e,t,n);default:return}}},Gt=(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;
|
|
25
25
|
const ${o} = new Array(${t}.length);
|
|
26
26
|
for (let ${s} = 0; ${s} < ${t}.length; ${s}++) {
|
|
27
27
|
const ${i} = ${t}[${s}];
|
|
28
28
|
${l.pre}${o}[${s}] = ${l.out};
|
|
29
29
|
}
|
|
30
|
-
`;return{out:o,pre:u}},Ht=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||
|
|
30
|
+
`;return{out:o,pre:u}},Ht=(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)}`,b=`let ${u} = false;
|
|
31
31
|
let ${p};
|
|
32
32
|
if (${n} !== undefined) {
|
|
33
33
|
${i.pre}${p} = ${i.out};
|
|
34
34
|
${u} = true;
|
|
35
35
|
}
|
|
36
|
-
`;return{entry:`...(${u} ? { ${a}: ${p} } : {})`,pre:b}}const o=
|
|
36
|
+
`;return{entry:`...(${u} ? { ${a}: ${p} } : {})`,pre:b}}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=Ht(o,s,t(o),n);if(!i)return;r+=i.pre,a.push(i.entry)}return{entries:a.join(", "),pre:r}},zt=(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
37
|
${a.pre}const ${s} = { ${a.entries} };
|
|
38
|
-
`;return{out:s,pre:i}},Xt=e=>{let t=0;const n=
|
|
38
|
+
`;return{out:s,pre:i}},Xt=e=>{let t=0;const n=nt(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
41
|
}`},k=`// GENERATED by @lunora/codegen — do not edit.
|
|
42
42
|
// Run \`lunora codegen\` to regenerate.
|
|
43
43
|
|
|
44
|
-
`,V=(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"},
|
|
44
|
+
`,V=(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,Yt=/^[\w./-]+$/u,m=(e,t)=>{if(!rt.test(e))throw new Y("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ee=e=>e.charAt(0).toUpperCase()+e.slice(1),A=e=>rt.test(e)?e:JSON.stringify(e),Zt={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",from:"unknown",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},en=e=>{if(e===void 0)return"unknown";if(!et.test(e))throw new Y("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},T=e=>{const t=Zt[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?T(e.inner):"unknown"}>`;case"id":{const n=e.tableName??"_unknown_";return m(n,"v.id() table name"),`Id<"${n}">`}case"literal":return en(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([n,r])=>`${A(n)}: ${T(r)}`).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?T(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?T(e.keyType):"string",r=e.valueType?T(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>T(n)).join(" | "):"never";default:return"unknown"}},be=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>{const a=A(n);if(r.kind==="optional"){const o=r.inner?T(r.inner):"unknown";return`${a}?: ${o}`}return`${a}: ${T(r)}`}).join("; ")} }`},tn=e=>e.kind==="optional"||!!e.column?.hasDefault,nn=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=T(o),i=A(r);return tn(a)?` ${i}?: ${s};`:` ${i}: ${s};`}).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}}`},ar=(e,t=!1)=>{const n=V(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(([R
|
|
49
|
+
_creationTime?: number;${n}}`},ar=(e,t=!1)=>{const n=V(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(([S,R])=>{const x=A(S);if(R.kind==="optional"){const I=R.inner?T(R.inner):"unknown";return` ${x}?: ${I};`}return` ${x}: ${T(R)};`}).join(`
|
|
50
50
|
`),f=g?`
|
|
51
51
|
${g}
|
|
52
52
|
`:"";return`export interface Doc_${c.name} {
|
|
@@ -55,7 +55,7 @@ ${g}
|
|
|
55
55
|
|
|
56
56
|
`),s=e.tables.map(c=>` ${c.name}: Doc_${c.name};`).join(`
|
|
57
57
|
`),i=e.tables.map(c=>{const g=c.indexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
58
|
-
`),l=e.tables.map(c=>{const g=c.
|
|
58
|
+
`),l=e.tables.map(c=>{const g=c.searchIndexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
59
59
|
`),u=e.tables.map(c=>{const g=c.rankIndexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
60
60
|
`),p=e.tables.map(c=>{const g=c.shardMode==="global"?"":(c.geoIndexes??[]).map(f=>JSON.stringify(f.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
61
61
|
`),b=e.vectorIndexes.map(c=>JSON.stringify(c.name)).join(" | ")||"never",w=e.tables.map(c=>nn(c)).join(`
|
|
@@ -234,7 +234,7 @@ 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
|
-
`},rn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,an=/^(?:\.\.?\/)*_generated\//u,on=/\.[A-Za-z]\w*$/u,
|
|
237
|
+
`},rn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,an=/^(?:\.\.?\/)*_generated\//u,on=/\.[A-Za-z]\w*$/u,Me=e=>e.replaceAll(rn,(t,n)=>{const r=n.replace(an,"./");return`import("${on.test(r)?r:`${r}.js`}")`}),sn=/import\("@lunora\/(?<pkg>client|do|runtime|server|values)(?<subpath>\/[^"]*)?"\)/gu,at=(e,t)=>t?e.replaceAll(sn,(n,r,a)=>`import("lunorash/${r}${a??""}")`):e,qe=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),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=be(s.args),l=Me(s.returnType);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${l}>;`}).join(`
|
|
238
238
|
`);return` ${A(v(r))}: {
|
|
239
239
|
${o}
|
|
240
240
|
};`};return[...t.entries()].toSorted(([r],[a])=>r.localeCompare(a)).map(r=>n(r)).join(`
|
|
@@ -270,7 +270,7 @@ export const agents: AgentsRef = {
|
|
|
270
270
|
${s}
|
|
271
271
|
};
|
|
272
272
|
`,n.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
273
|
-
`)}return{block:r,importLine:n.join("")}},dn=()=>Object.keys(
|
|
273
|
+
`)}return{block:r,importLine:n.join("")}},dn=()=>Object.keys(Ye().functions).toSorted((e,t)=>e.localeCompare(t)),ot=e=>new Set(e.filter(t=>v(t.filePath)==="agents").map(t=>t.exportName)),cn=()=>new Set(Object.entries(Ye().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),un=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=ot(t),a=cn(),o=t.find(i=>v(i.filePath)==="agents"&&a.has(i.exportName));if(o)throw new Y("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=dn().filter(i=>!r.has(i));return s.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
274
274
|
`,lines:s.map(i=>` "agents:${i}": lunoraAgentRuntimeFunctions.${i} as unknown as RegisteredLunoraFunction,`).join(`
|
|
275
275
|
`),prelude:`
|
|
276
276
|
/**
|
|
@@ -279,8 +279,8 @@ ${s}
|
|
|
279
279
|
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
280
280
|
*/
|
|
281
281
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
282
|
-
`}},pn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>v(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new
|
|
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"}},hn=(e,t)=>{if(e.length===0)return[];const n=
|
|
282
|
+
`}},pn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>v(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new Y("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"}},hn=(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))},gn=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>v(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}))},mn=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` ${A(u.exportName)}: HttpStreamRef<${p}, ${be(u.searchParams)}, ${be(u.params)}>;`}).join(`
|
|
284
284
|
`);return` ${A(v(s))}: {
|
|
285
285
|
${l}
|
|
286
286
|
};`}).join(`
|
|
@@ -297,17 +297,17 @@ ${a}
|
|
|
297
297
|
export const httpStreams: HttpStreamsRef = {
|
|
298
298
|
${o}
|
|
299
299
|
};
|
|
300
|
-
`,body:a}},or=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:s=[]}=e,i=V(o),l=[...n.filter(x=>x.visibility!=="internal"),...hn(t,n),...gn(a,n)],u=n.filter(x=>x.visibility==="internal"),p=
|
|
300
|
+
`,body:a}},or=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:s=[]}=e,i=V(o),l=[...n.filter(x=>x.visibility!=="internal"),...hn(t,n),...gn(a,n)],u=n.filter(x=>x.visibility==="internal"),p=ze(l),b=ze(u),w=mn(r),$=`${p}
|
|
301
301
|
${b}
|
|
302
|
-
${w.body}`,d=
|
|
302
|
+
${w.body}`,d=qe($),c=d.length>0?`
|
|
303
303
|
import type { ${d.join(", ")} } from "./dataModel.js";
|
|
304
304
|
`:"",g=p?`
|
|
305
305
|
${p}
|
|
306
306
|
`:"",f=b?`
|
|
307
307
|
${b}
|
|
308
|
-
`:"",
|
|
309
|
-
import type { ${
|
|
310
|
-
${
|
|
308
|
+
`:"",S=ln(s,t),R=w.block===""?"FunctionReference":"FunctionReference, HttpStreamRef";return at(`${k}import { anyApi } from "${i.serverTypes}";
|
|
309
|
+
import type { ${R} } from "${i.client}";
|
|
310
|
+
${S.importLine}${c}
|
|
311
311
|
export interface ApiTypes {${g}}
|
|
312
312
|
|
|
313
313
|
export const api = anyApi as unknown as ApiTypes;
|
|
@@ -316,7 +316,7 @@ export const api = anyApi as unknown as ApiTypes;
|
|
|
316
316
|
export interface InternalApiTypes {${f}}
|
|
317
317
|
|
|
318
318
|
export const internal = anyApi as unknown as InternalApiTypes;
|
|
319
|
-
${
|
|
319
|
+
${S.block}${w.block}`,o)},ir=e=>e?`${k}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
|
-
`:"",sr=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=V(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=
|
|
337
|
-
export interface ${
|
|
336
|
+
`:"",sr=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=V(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=be(l.args),b=Object.keys(l.args).length>0,w=b?` args: ${p};`:` args?: ${p};`,$=b?`(args: ${p}) => void`:`(args?: ${p}) => void`,d=`${l.exportName}CollectionOptions`;return`/** Options for the \`${l.exportName}\` shape binding. */
|
|
337
|
+
export interface ${Ee(d)} {
|
|
338
338
|
${w}
|
|
339
339
|
/**
|
|
340
340
|
* Share the optimistic-overlay gate with other collections + mutators on this
|
|
@@ -359,7 +359,7 @@ ${w}
|
|
|
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: ${
|
|
362
|
+
export const ${l.exportName}CollectionOptions = (options: ${Ee(d)}): LunoraCollectionOptions<${u}> =>
|
|
363
363
|
lunoraCollectionOptions<${u}>({
|
|
364
364
|
client: options.client,
|
|
365
365
|
...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
|
|
@@ -372,14 +372,14 @@ export const ${l.exportName}CollectionOptions = (options: ${Ce(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: ${
|
|
375
|
+
options: ${Ee(d)},
|
|
376
376
|
): { checkpoints: CheckpointRegistry; collection: Collection<${u}, string>; scope: ${$} } => {
|
|
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=
|
|
382
|
+
`),s=qe(o),i=s.length>0?`import type { ${s.join(", ")} } from "./dataModel.js";
|
|
383
383
|
`:"";return`${k}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";
|
|
@@ -395,7 +395,7 @@ ${o}
|
|
|
395
395
|
}
|
|
396
396
|
|
|
397
397
|
return (await registered.handler(context, args ?? {})) as R;
|
|
398
|
-
};`,yn=(e,t,n=[],r=[])=>{const a=new Map,o=d=>{a.has(d)||a.set(d,fn(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(!Yt.test(d))throw new
|
|
398
|
+
};`,yn=(e,t,n=[],r=[])=>{const a=new Map,o=d=>{a.has(d)||a.set(d,fn(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(!Yt.test(d))throw new Y("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(d)}`);return`import * as ${c} from "../${d}.js";`}).join(`
|
|
399
399
|
`),i=e.map(d=>` "${v(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
401
|
`),u=n.map(d=>` "${v(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
@@ -410,7 +410,7 @@ ${w}
|
|
|
410
410
|
${l}
|
|
411
411
|
`:"",mutatorPaths:b,shapeBody:p.length>0?`
|
|
412
412
|
${p}
|
|
413
|
-
`:""}},wn=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=
|
|
413
|
+
`:""}},wn=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=be(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
414
|
`);return` ${A(v(a))}: {
|
|
415
415
|
${s}
|
|
416
416
|
};`}).join(`
|
|
@@ -418,18 +418,18 @@ ${s}
|
|
|
418
418
|
`);return` ${A(s)}: {
|
|
419
419
|
${i}
|
|
420
420
|
},`}).join(`
|
|
421
|
-
`),types:r}},xn=(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))]},lr=({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:b=!1,hasPayments:w=!1,hasPipelines:$=!1,hasR2sql:d=!1,hasX402:c=!1,identity:g,queues:f=[],schema:
|
|
422
|
-
`:"",
|
|
423
|
-
readonly ai: LunoraAi;`:"",
|
|
424
|
-
`:"",
|
|
421
|
+
`),types:r}},xn=(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))]},lr=({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:b=!1,hasPayments:w=!1,hasPipelines:$=!1,hasR2sql:d=!1,hasX402:c=!1,identity:g,queues:f=[],schema:S,storageRuleBuckets:R=[],useUmbrella:x=!1,workflows:I=[]}={})=>{const y=V(x),Z=xn(S??{tables:[]},R).map(h=>JSON.stringify(h)).join(" | "),ee=a?`import type { LunoraAi } from "@lunora/ai";
|
|
422
|
+
`:"",te=a?`
|
|
423
|
+
readonly ai: LunoraAi;`:"",_=w?`import type { LunoraPayment } from "@lunora/payment";
|
|
424
|
+
`:"",q=w?`
|
|
425
425
|
readonly payments: LunoraPayment;`:"",N=c?`import type { X402Pay } from "@lunora/x402/pay";
|
|
426
|
-
`:"",
|
|
426
|
+
`:"",B=c?`
|
|
427
427
|
readonly x402: X402Pay;`:"",L=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
|
|
428
|
-
`:"",
|
|
428
|
+
`:"",ne=t.length>0?`
|
|
429
429
|
readonly containers: {${t.map(h=>`
|
|
430
430
|
readonly ${h.exportName}: ContainerAccessor;`).join("")}
|
|
431
|
-
};`:"",
|
|
432
|
-
readonly ${h.bindingName}?: unknown;`)),...
|
|
431
|
+
};`:"",G=[...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;`)),...I.map(h=>(m(h.bindingName,`workflow binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` workflow. */
|
|
433
433
|
readonly ${h.bindingName}?: unknown;`)),...f.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(`
|
|
@@ -446,22 +446,26 @@ ${i}
|
|
|
446
446
|
* surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
|
|
447
447
|
*/
|
|
448
448
|
export interface CloudflareBindings {
|
|
449
|
-
readonly [binding: string]: unknown;${
|
|
450
|
-
${
|
|
449
|
+
readonly [binding: string]: unknown;${G?`
|
|
450
|
+
${G}`:""}
|
|
451
451
|
}
|
|
452
452
|
|
|
453
453
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
454
|
-
export type Env = CloudflareBindings;`,P=(h,
|
|
454
|
+
export type Env = CloudflareBindings;`,P=(h,Ie)=>Ie?Kt.get(h)?.field??"":"",j=P("kv",p),E=P("analytics",o),W=P("hyperdrive",l),re=P("browser",s),ae=P("images",u),oe=P("pipelines",$),U=P("r2sql",d),F=(S?.vectorIndexes.length??0)>0,M=F?' | "vectors"':"",K=F?`
|
|
455
|
+
readonly vectors: VectorSearch<VectorIndexName>;`:"",H=F?`
|
|
456
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",z=F?`import type { VectorSearch, VectorSearchReader } from "${y.server}";
|
|
457
|
+
import type { VectorIndexName } from "./dataModel.js";
|
|
458
|
+
`:"",ie=r?`
|
|
455
459
|
/** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
|
|
456
|
-
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",
|
|
460
|
+
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",se=i?`
|
|
457
461
|
/** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
|
|
458
|
-
readonly flags: import("${y.flags}").LunoraFlags;`:"",
|
|
462
|
+
readonly flags: import("${y.flags}").LunoraFlags;`:"",le=b?`
|
|
459
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. */
|
|
460
464
|
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
461
465
|
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
462
|
-
readonly push: import("@lunora/notify").LunoraPush;`:"",
|
|
466
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",X=I.length>0,ve=X?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
463
467
|
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
464
|
-
`:""
|
|
468
|
+
`:"",$e=X?`
|
|
465
469
|
|
|
466
470
|
/** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
|
|
467
471
|
type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
|
|
@@ -472,12 +476,12 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
472
476
|
|
|
473
477
|
/** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
|
|
474
478
|
export interface LunoraWorkflows {
|
|
475
|
-
${
|
|
479
|
+
${I.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
|
|
476
480
|
`)}
|
|
477
|
-
}`:"",
|
|
478
|
-
readonly workflows: LunoraWorkflows;`:"",
|
|
481
|
+
}`:"",ye=X?' | "workflows"':"",we=X?`
|
|
482
|
+
readonly workflows: LunoraWorkflows;`:"",de=f.length>0,Se=de?`import type { QueueProducer } from "@lunora/queue";
|
|
479
483
|
import type * as lunoraQueueDefinitions from "../queues.js";
|
|
480
|
-
`:"",
|
|
484
|
+
`:"",Re=de?`
|
|
481
485
|
|
|
482
486
|
/** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
|
|
483
487
|
type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
|
|
@@ -486,29 +490,29 @@ type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body }
|
|
|
486
490
|
export interface LunoraQueues {
|
|
487
491
|
${f.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${h.exportName}>>;`).join(`
|
|
488
492
|
`)}
|
|
489
|
-
}`:"",
|
|
490
|
-
readonly queues: LunoraQueues;`:"",
|
|
491
|
-
`:"",
|
|
493
|
+
}`:"",xe=de?`
|
|
494
|
+
readonly queues: LunoraQueues;`:"",ce=e.length>0,Ne=ce?`import type { AgentHandle } from "@lunora/agent";
|
|
495
|
+
`:"",Oe=ce?`
|
|
492
496
|
|
|
493
497
|
/** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
|
|
494
498
|
export interface LunoraAgents {
|
|
495
499
|
${e.map(h=>(m(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
|
|
496
500
|
`)}
|
|
497
|
-
}`:"",
|
|
498
|
-
readonly agents: LunoraAgents;`:""
|
|
501
|
+
}`:"",ke=ce?`
|
|
502
|
+
readonly agents: LunoraAgents;`:"",Te=g?`import type { InferIdentity } from "${y.server}";
|
|
499
503
|
import type * as lunoraIdentityContract from "../identity.js";
|
|
500
|
-
`:"",
|
|
504
|
+
`:"",Ae=g?`
|
|
501
505
|
|
|
502
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. */
|
|
503
507
|
export type Identity = InferIdentity<typeof lunoraIdentityContract.${g.exportName}>;
|
|
504
508
|
|
|
505
509
|
/** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
|
|
506
|
-
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",
|
|
507
|
-
readonly auth: NarrowedAuth;`:"",
|
|
508
|
-
`:"",
|
|
510
|
+
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",ue=g?' | "auth"':"",pe=g?`
|
|
511
|
+
readonly auth: NarrowedAuth;`:"",Le=g?", Identity":"",Ce=n?`import type * as lunoraEnvContract from "../env.js";
|
|
512
|
+
`:"",De=n?`
|
|
509
513
|
|
|
510
514
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
511
|
-
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",
|
|
515
|
+
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",he=n?' | "env"':"",ge=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 "${y.server}";
|
|
512
516
|
import type {
|
|
513
517
|
ActionBuilder,
|
|
514
518
|
ActionCtx as ActionCtxBase,
|
|
@@ -532,11 +536,11 @@ import type {
|
|
|
532
536
|
} from "${y.server}";
|
|
533
537
|
|
|
534
538
|
import type { DataModel, DatabaseReaderFacade, DatabaseWriterFacade, Doc, Id as IdOfTable, OrmReader, OrmWriter, Relations, TableName } from "./dataModel.js";
|
|
535
|
-
${
|
|
539
|
+
${z}${ee}${_}${N}${L}${ve}${Se}${Ne}${Te}${Ce}
|
|
536
540
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
537
541
|
|
|
538
542
|
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
539
|
-
export type StorageBucketName = ${
|
|
543
|
+
export type StorageBucketName = ${Z};${C}${$e}${Re}${Oe}${Ae}${De}
|
|
540
544
|
|
|
541
545
|
/**
|
|
542
546
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -590,22 +594,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
|
|
|
590
594
|
*/
|
|
591
595
|
type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
|
|
592
596
|
|
|
593
|
-
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${
|
|
597
|
+
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${M}${ue}${he}> {
|
|
594
598
|
readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
595
599
|
readonly orm: OrmReader;
|
|
596
|
-
readonly storage: ReadOnlyStorage<StorageBucketName>;${
|
|
600
|
+
readonly storage: ReadOnlyStorage<StorageBucketName>;${H}${ie}${j}${se}${le}${E}${ge}${pe}
|
|
597
601
|
}
|
|
598
602
|
|
|
599
|
-
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${
|
|
603
|
+
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${M}${ye}${ue}${he}> {
|
|
600
604
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
601
605
|
readonly orm: OrmWriter;
|
|
602
|
-
readonly storage: ReadOnlyStorage<StorageBucketName>;${
|
|
606
|
+
readonly storage: ReadOnlyStorage<StorageBucketName>;${K}${ie}${j}${se}${le}${E}${ge}${we}${xe}${ke}${pe}
|
|
603
607
|
}
|
|
604
608
|
|
|
605
|
-
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${
|
|
609
|
+
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${M}${ye}${ue}${he}> {
|
|
606
610
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
607
611
|
readonly orm: OrmWriter;
|
|
608
|
-
readonly storage: StorageBase<StorageBucketName>;${
|
|
612
|
+
readonly storage: StorageBase<StorageBucketName>;${K}${ie}${te}${q}${B}${ne}${j}${se}${le}${W}${re}${ae}${E}${oe}${U}${ge}${we}${xe}${ke}${pe}
|
|
609
613
|
}
|
|
610
614
|
|
|
611
615
|
/**
|
|
@@ -663,7 +667,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
|
|
|
663
667
|
* Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
|
|
664
668
|
* so the \`rls()\` chain discovers a policy authored either way the same.
|
|
665
669
|
*/
|
|
666
|
-
export const definePolicy = createPolicyDsl<DataModel, Relations${
|
|
670
|
+
export const definePolicy = createPolicyDsl<DataModel, Relations${Le}>();
|
|
667
671
|
|
|
668
672
|
/**
|
|
669
673
|
* The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
|
|
@@ -680,12 +684,12 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Re}>();
|
|
|
680
684
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
681
685
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
682
686
|
};
|
|
683
|
-
`},kn=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${v(n.filePath)}:${n.exportName}`);return t},dr=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:s=!1,usesSandbox:i=!1}=e,l=n.length>0,u=V(s),{dispatchBody:p,importBlock:b,installBlock:w,migrationBody:$,mutatorPaths:d,shapeBody:c}=yn(n,r,a,o),g=un(t,n),f=pn(i,n),
|
|
684
|
-
`);let
|
|
685
|
-
${
|
|
687
|
+
`},kn=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${v(n.filePath)}:${n.exportName}`);return t},dr=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:s=!1,usesSandbox:i=!1}=e,l=n.length>0,u=V(s),{dispatchBody:p,importBlock:b,installBlock:w,migrationBody:$,mutatorPaths:d,shapeBody:c}=yn(n,r,a,o),g=un(t,n),f=pn(i,n),S=[g.lines,f.lines].filter(C=>C.length>0).join(`
|
|
688
|
+
`);let R=p;S.length>0&&(R=p.length>0?`${p.trimEnd()}
|
|
689
|
+
${S}
|
|
686
690
|
`:`
|
|
687
|
-
${
|
|
688
|
-
`);const x=kn(n),
|
|
691
|
+
${S}
|
|
692
|
+
`);const x=kn(n),I=o.length>0?`import type { RegisteredShape } from "${u.server}";
|
|
689
693
|
`:"",y=o.length>0?`
|
|
690
694
|
/**
|
|
691
695
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
@@ -694,29 +698,29 @@ ${R}
|
|
|
694
698
|
* \`shape_subscribe\` (reads-as-permissions).
|
|
695
699
|
*/
|
|
696
700
|
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${c}};
|
|
697
|
-
`:"",
|
|
701
|
+
`:"",Z=d.length>0?`
|
|
698
702
|
/**
|
|
699
703
|
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
700
704
|
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
701
705
|
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
702
706
|
*/
|
|
703
707
|
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(C=>JSON.stringify(C)).join(", ")}]);
|
|
704
|
-
`:"",
|
|
705
|
-
`:"",
|
|
708
|
+
`:"",ee=w.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
|
|
709
|
+
`:"",te=w.length>0?`
|
|
706
710
|
/**
|
|
707
711
|
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
708
712
|
* onto its function's live \`.args\` object and consulted by the interpreted
|
|
709
713
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
710
714
|
*/
|
|
711
715
|
${w}
|
|
712
|
-
`:"",
|
|
713
|
-
${
|
|
714
|
-
`:"",N=
|
|
715
|
-
${
|
|
716
|
-
`:"",
|
|
717
|
-
`:"",
|
|
718
|
-
|
|
719
|
-
`:"";return
|
|
716
|
+
`:"",_=wn(n),q=_.types?`
|
|
717
|
+
${_.types}
|
|
718
|
+
`:"",N=_.implementation?`
|
|
719
|
+
${_.implementation}
|
|
720
|
+
`:"",B=qe(_.types),L=B.length>0?`import type { ${B.join(", ")} } from "./dataModel.js";
|
|
721
|
+
`:"",ne=l?"context":"_context",G=l?`${bn}
|
|
722
|
+
|
|
723
|
+
`:"";return at(`${k}${b}${g.importLine}${f.importLine}${ee}${I}import { LunoraError } from "${u.server}";
|
|
720
724
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
721
725
|
${L}
|
|
722
726
|
/**
|
|
@@ -742,8 +746,8 @@ ${g.prelude}${f.prelude}
|
|
|
742
746
|
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
743
747
|
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
744
748
|
*/
|
|
745
|
-
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${
|
|
746
|
-
${
|
|
749
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${R}};
|
|
750
|
+
${te}${y}${Z}
|
|
747
751
|
/**
|
|
748
752
|
* Connection-lifecycle manifest: the function paths the generated ShardDO
|
|
749
753
|
* dispatches when a client's WebSocket connects (\`connect\`) or disconnects
|
|
@@ -783,10 +787,10 @@ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
|
783
787
|
* with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
|
|
784
788
|
* \`runAction\` but without re-stating the function path.
|
|
785
789
|
*/
|
|
786
|
-
export interface Caller {${
|
|
790
|
+
export interface Caller {${q}}
|
|
787
791
|
|
|
788
|
-
${
|
|
789
|
-
export const createCaller = (${
|
|
792
|
+
${G}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
793
|
+
export const createCaller = (${ne}: CallerCtx): Caller => ({${N}});
|
|
790
794
|
|
|
791
795
|
/**
|
|
792
796
|
* Single registered data migration, narrowed to the shape the per-shard runner
|
|
@@ -887,10 +891,10 @@ const kvStub: Kv = {
|
|
|
887
891
|
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:D,Dn=e=>e?{build:`
|
|
888
892
|
const envConfig = lunoraEnvContract.${e.exportName}(env);
|
|
889
893
|
`,configField:"",contextField:`
|
|
890
|
-
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,
|
|
894
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:D,In=e=>e?{build:`
|
|
891
895
|
const access = accessFacade(identity, userId);
|
|
892
896
|
`,configField:"",contextField:`
|
|
893
|
-
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,
|
|
897
|
+
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:D,_n=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=i=>`
|
|
894
898
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
895
899
|
const flags: import("${n}").LunoraFlags = createFlags({
|
|
896
900
|
hooks: flagsConfig.hooks,
|
|
@@ -1202,7 +1206,7 @@ const LUNORA_QUEUES_INFO: QueuesResult = ${JSON.stringify(t,void 0,4)};
|
|
|
1202
1206
|
protected override queuesMetadata(): QueuesResult {
|
|
1203
1207
|
return LUNORA_QUEUES_INFO;
|
|
1204
1208
|
}
|
|
1205
|
-
`}},
|
|
1209
|
+
`}},Vn=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:`
|
|
1206
1210
|
const payments: LunoraPayment = config.payment
|
|
1207
1211
|
? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
|
|
1208
1212
|
: paymentStub;
|
|
@@ -1238,7 +1242,7 @@ const paymentStub: LunoraPayment = {
|
|
|
1238
1242
|
${t}
|
|
1239
1243
|
},
|
|
1240
1244
|
} as unknown as LunoraPayment;
|
|
1241
|
-
`}},
|
|
1245
|
+
`}},Gn=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
|
|
1242
1246
|
const x402: X402Pay = config.x402
|
|
1243
1247
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1244
1248
|
: x402Stub;
|
|
@@ -1250,7 +1254,7 @@ const x402Stub: X402Pay = {
|
|
|
1250
1254
|
throw new Error("ctx.x402: no pay rail configured. Pass \\\`x402\\\` to createShardDO().");
|
|
1251
1255
|
},
|
|
1252
1256
|
} as unknown as X402Pay;
|
|
1253
|
-
`}:{build:"",configField:"",contextField:"",imports:[],stub:""},Hn=(e,t,n,r)=>["AdvisoryFinding","DatabaseWriterLike","DataMigrationLike",...r?["FlagsResult"]:[],"MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],gr=({advisories:e=[],agents:t=[],containers:n=[],env:r,flagKeys:a=[],hasAccessFacade:o=!1,hasAi:s=!1,hasAnalytics:i=!1,hasBrowser:l=!1,hasFlags:u=!1,hasHyperdrive:p=!1,hasImages:b=!1,hasKv:w=!1,hasNotify:$=!1,hasPayments:d=!1,hasPipelines:c=!1,hasR2sql:g=!1,hasX402:f=!1,maskMetadata:
|
|
1257
|
+
`}:{build:"",configField:"",contextField:"",imports:[],stub:""},Hn=(e,t,n,r)=>["AdvisoryFinding","DatabaseWriterLike","DataMigrationLike",...r?["FlagsResult"]:[],"MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],gr=({advisories:e=[],agents:t=[],containers:n=[],env:r,flagKeys:a=[],hasAccessFacade:o=!1,hasAi:s=!1,hasAnalytics:i=!1,hasBrowser:l=!1,hasFlags:u=!1,hasHyperdrive:p=!1,hasImages:b=!1,hasKv:w=!1,hasNotify:$=!1,hasPayments:d=!1,hasPipelines:c=!1,hasR2sql:g=!1,hasX402:f=!1,maskMetadata:S,mutators:R=[],queues:x=[],rlsMetadata:I,schema:y,shapes:Z=[],storageRules:ee,studioFeatures:te,useUmbrella:_=!1,workflows:q=[]})=>{const N=V(_),B=R.length>0,L=Z.length>0,{build:ne,configField:G,contextField:C,stub:P}=Tn(s),j=In(o),E=An(w),W=Ln(u,N.flags),re=_n(a,u,N.flags),ae=Cn($),oe=Dn(r),U=Pn(i),F=En(b),M=Fn(p),K=Mn(l),H=qn(g),z=Bn(c),{build:ie,contextField:se,importLines:le,specs:X}=Un(x),{build:ve,contextField:$e,importLines:ye,specs:we}=jn(n,y.jurisdiction),{build:de,contextField:Se,importLines:Re,specs:xe}=Wn(q),{build:ce,contextField:Ne,importLines:Oe,specs:ke}=Kn(t),{build:Te,configField:Ae,contextField:ue,imports:pe,stub:Le}=Vn(d),{build:Ce,configField:De,imports:he,stub:ge}=Gn(f),h=e,Ie=I??{policies:[],roles:[]},it=S??{columns:[]},st=ee??{rules:[]},lt=te??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:dt,override:ct}=Qn(q),{constant:ut,override:pt}=Jn(x),Q=y.vectorIndexes.length>0,me=y.tables.some(O=>O.shardMode==="global"),_e=y.tables.some(O=>O.shardMode==="global"&&O.globalBackend==="hyperdrive"),je=y.tables.some(O=>O.shardMode==="global"&&O.globalBackend!=="hyperdrive"),J=y.tables.some(O=>O.externalSource!==void 0);if(je&&_e)throw new Y("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=y.tables.length>0,ht=vn(y),gt=Sn(y),mt=Nn(y),ft=$n(y),We=Rn(y),Ue=Hn(Q,q.length>0,x.length>0,u);L&&Ue.push("WhereInput");const Ke=On(me),bt=L?`
|
|
1254
1258
|
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 {
|
|
1255
1259
|
const shape = LUNORA_SHAPES[name];
|
|
1256
1260
|
|
|
@@ -1303,15 +1307,15 @@ const x402Stub: X402Pay = {
|
|
|
1303
1307
|
|
|
1304
1308
|
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
1305
1309
|
}
|
|
1306
|
-
`:"",yt=
|
|
1310
|
+
`:"",yt=B?`
|
|
1307
1311
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1308
1312
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1309
1313
|
}
|
|
1310
|
-
`:"",wt=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":"",xt=L?"assertShapeShardable, ":"",
|
|
1311
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",vt=
|
|
1312
|
-
d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",$t=
|
|
1313
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",St=
|
|
1314
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Rt=
|
|
1314
|
+
`:"",wt=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":"",xt=L?"assertShapeShardable, ":"",fe=[`import type { ${Ue.join(", ")} } from "${N.do}";`,`import { applyCdcChanges, ${xt}createShardCtxDb, ${J?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}runDataMigration, runShardMigrations, ${Ke.importFragment}ShardDO as ShardDOBase } from "${N.do}";`,...J?[`import type { ExternalSourceLike, SourceClientLike } from "${N.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${N.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${N.server}";`];Pe&&fe.push(`import { bindOrm, bindTableFacade } from "${N.server}";`),Q&&fe.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&fe.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),fe.push(...j.importLines,...E.importLines,...W.importLines,...ae.importLines,...oe.importLines,...U.importLines,...F.importLines,...M.importLines,...K.importLines,...H.importLines,...z.importLines,...ye,...Re,...le,...Oe,...pe,...he,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...B?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const kt=Q?`
|
|
1315
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",vt=je?`
|
|
1316
|
+
d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",$t=_e?`
|
|
1317
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",St=J?`
|
|
1318
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Rt=me?'\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':"",Nt=Q?`
|
|
1315
1319
|
const vectorsStub: VectorSearchLike = {
|
|
1316
1320
|
deleteByIds: async () => {
|
|
1317
1321
|
throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
|
|
@@ -1329,7 +1333,7 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1329
1333
|
throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
|
|
1330
1334
|
},
|
|
1331
1335
|
};
|
|
1332
|
-
`:"",Ot=
|
|
1336
|
+
`:"",Ot=Q?`
|
|
1333
1337
|
let vectors: VectorSearchLike;
|
|
1334
1338
|
let onWrite: WriteHook | undefined;
|
|
1335
1339
|
|
|
@@ -1342,9 +1346,9 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1342
1346
|
vectors = vectorsStub;
|
|
1343
1347
|
onWrite = undefined;
|
|
1344
1348
|
}
|
|
1345
|
-
`:"",
|
|
1346
|
-
globalDb,`:"",
|
|
1347
|
-
auth: { identity: identity ?? null, userId: userId ?? null },`,Tt=
|
|
1349
|
+
`:"",Qe=me?`
|
|
1350
|
+
globalDb,`:"",Je=`
|
|
1351
|
+
auth: { identity: identity ?? null, userId: userId ?? null },`,Tt=Q?`{${Je}
|
|
1348
1352
|
broadcast: (delta) => {
|
|
1349
1353
|
this.recordChangedTable(delta.table);
|
|
1350
1354
|
},
|
|
@@ -1356,8 +1360,8 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1356
1360
|
scheduler,
|
|
1357
1361
|
schema: schema as unknown as SchemaLike,
|
|
1358
1362
|
sql: this.sql as SqlExec,
|
|
1359
|
-
storage,${
|
|
1360
|
-
}`:`{${
|
|
1363
|
+
storage,${Qe}
|
|
1364
|
+
}`:`{${Je}
|
|
1361
1365
|
broadcast: (delta) => {
|
|
1362
1366
|
this.recordChangedTable(delta.table);
|
|
1363
1367
|
},
|
|
@@ -1368,14 +1372,14 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1368
1372
|
scheduler,
|
|
1369
1373
|
schema: schema as unknown as SchemaLike,
|
|
1370
1374
|
sql: this.sql as SqlExec,
|
|
1371
|
-
storage,${
|
|
1372
|
-
}`,At=
|
|
1373
|
-
vectors,`:"",Lt=
|
|
1374
|
-
orm: bindOrm(facade),`:"",Ct="",
|
|
1375
|
-
`:"",
|
|
1375
|
+
storage,${Qe}
|
|
1376
|
+
}`,At=Q?`
|
|
1377
|
+
vectors,`:"",Lt=Pe?`
|
|
1378
|
+
orm: bindOrm(facade),`:"",Ct="",Ve=_e?"config.hyperdriveGlobal":"config.d1",Dt=me?` const globalDb: DatabaseWriterLike = ${Ve}?.(env, { identity, userId }) ?? globalDbStub;
|
|
1379
|
+
`:"",It=L&&me?`
|
|
1376
1380
|
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 }>> {
|
|
1377
1381
|
const env = this.env as Record<string, unknown>;
|
|
1378
|
-
const globalDb: DatabaseWriterLike = ${
|
|
1382
|
+
const globalDb: DatabaseWriterLike = ${Ve}?.(env, identity) ?? globalDbStub;
|
|
1379
1383
|
const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
|
|
1380
1384
|
|
|
1381
1385
|
let cursor: null | string = null;
|
|
@@ -1402,10 +1406,10 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1402
1406
|
|
|
1403
1407
|
return rows;
|
|
1404
1408
|
}
|
|
1405
|
-
`:"",
|
|
1409
|
+
`:"",_t=J?`
|
|
1406
1410
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1407
1411
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1408
|
-
`:"",Pt=
|
|
1412
|
+
`:"",Pt=J?`
|
|
1409
1413
|
protected override async pollExternalSources(): Promise<number | undefined> {
|
|
1410
1414
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1411
1415
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1506,10 +1510,10 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1506
1510
|
|
|
1507
1511
|
return nextDueAt;
|
|
1508
1512
|
}
|
|
1509
|
-
`:"",
|
|
1513
|
+
`:"",Ge=We.length>0,Et=J||Ge?`
|
|
1510
1514
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1511
1515
|
super(state, env);
|
|
1512
|
-
${
|
|
1516
|
+
${J?`
|
|
1513
1517
|
const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
|
|
1514
1518
|
const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
|
|
1515
1519
|
|
|
@@ -1519,27 +1523,27 @@ ${G?`
|
|
|
1519
1523
|
if (autoSourced) {
|
|
1520
1524
|
void this.scheduleSourcePoll();
|
|
1521
1525
|
}
|
|
1522
|
-
`:""}${
|
|
1526
|
+
`:""}${Ge?`
|
|
1523
1527
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1524
1528
|
void this.scheduleTtlSweep();
|
|
1525
1529
|
}
|
|
1526
1530
|
`:""} }
|
|
1527
|
-
`:"",Ft=
|
|
1531
|
+
`:"",Ft=Pe?`
|
|
1528
1532
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1529
1533
|
${y.tables.map(O=>` facade[${JSON.stringify(O.name)}] = bindTableFacade(db, ${JSON.stringify(O.name)});`).join(`
|
|
1530
1534
|
`)}
|
|
1531
|
-
`:"",Mt=`${
|
|
1535
|
+
`:"",Mt=`${j.build}${E.build}${W.build}${U.build}${oe.build}
|
|
1532
1536
|
const secrets = createSecrets(env);
|
|
1533
|
-
`,qt=`${
|
|
1534
|
-
secrets,`,Bt=
|
|
1537
|
+
`,qt=`${j.contextField}${E.contextField}${W.contextField}${ae.contextField}${U.contextField}${oe.contextField}
|
|
1538
|
+
secrets,`,Bt=ae.build,He=b||p||l||g||c||f,jt=He?`
|
|
1535
1539
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1536
1540
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
1537
1541
|
if (isAction) {
|
|
1538
|
-
${
|
|
1542
|
+
${F.build}${M.build}${K.build}${H.build}${z.build}${Ce}${[...b?[" ctx.images = images;"]:[],...p?[" ctx.sql = sql;"]:[],...l?[" ctx.browser = browser;"]:[],...g?[" ctx.r2sql = r2sql;"]:[],...c?[" ctx.pipelines = pipelines;"]:[],...f?[" ctx.x402 = x402;"]:[]].join(`
|
|
1539
1543
|
`)}
|
|
1540
1544
|
}
|
|
1541
|
-
`:"",Wt=
|
|
1542
|
-
`:"";return`${k}${
|
|
1545
|
+
`:"",Wt=He?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
|
|
1546
|
+
`:"";return`${k}${fe.join(`
|
|
1543
1547
|
`)}
|
|
1544
1548
|
|
|
1545
1549
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1561,13 +1565,13 @@ const LUNORA_TABLE_COLUMNS: Record<string, Array<{ isStorage?: boolean; name: st
|
|
|
1561
1565
|
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(ft,void 0,4)};
|
|
1562
1566
|
|
|
1563
1567
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1564
|
-
const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(
|
|
1568
|
+
const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(We,void 0,4)};
|
|
1565
1569
|
|
|
1566
1570
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1567
|
-
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(
|
|
1571
|
+
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(h,void 0,4)};
|
|
1568
1572
|
|
|
1569
1573
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1570
|
-
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(
|
|
1574
|
+
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(Ie,void 0,4)};
|
|
1571
1575
|
|
|
1572
1576
|
/** 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. */
|
|
1573
1577
|
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(it,void 0,4)};
|
|
@@ -1577,14 +1581,14 @@ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(st,void 0,4)};
|
|
|
1577
1581
|
|
|
1578
1582
|
/** 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. */
|
|
1579
1583
|
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(lt,void 0,4)};
|
|
1580
|
-
${
|
|
1584
|
+
${re.constant}${wt}${dt}${ut}${we}${xe}${X}${ke}
|
|
1581
1585
|
export interface ShardDOConfig {
|
|
1582
1586
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1583
1587
|
cdc?: boolean;
|
|
1584
1588
|
/** 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. */
|
|
1585
1589
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1586
1590
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1587
|
-
storage?: (env: Record<string, unknown>) => unknown;${kt}${
|
|
1591
|
+
storage?: (env: Record<string, unknown>) => unknown;${kt}${G}${E.configField}${W.configField}${U.configField}${F.configField}${M.configField}${K.configField}${H.configField}${z.configField}${Ae}${De}${vt}${$t}${St}
|
|
1588
1592
|
}
|
|
1589
1593
|
|
|
1590
1594
|
const schedulerStub = {
|
|
@@ -1622,7 +1626,7 @@ const storageStub = {
|
|
|
1622
1626
|
throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
|
|
1623
1627
|
},
|
|
1624
1628
|
};
|
|
1625
|
-
${Rt}${
|
|
1629
|
+
${Rt}${_t}${Nt}${P}${E.stub}${W.stub}${U.stub}${F.stub}${M.stub}${K.stub}${H.stub}${z.stub}${Le}${ge}${Ct}
|
|
1626
1630
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1627
1631
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1628
1632
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -1702,7 +1706,7 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
|
|
|
1702
1706
|
|
|
1703
1707
|
return registered.handler(ctx, args);
|
|
1704
1708
|
}
|
|
1705
|
-
${
|
|
1709
|
+
${Ke.override}
|
|
1706
1710
|
protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<{ result: unknown; tables: Set<string> } | null> {
|
|
1707
1711
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
1708
1712
|
|
|
@@ -1735,7 +1739,7 @@ ${qe.override}
|
|
|
1735
1739
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
|
|
1736
1740
|
};
|
|
1737
1741
|
}
|
|
1738
|
-
${yt}${bt}${
|
|
1742
|
+
${yt}${bt}${It}${Pt}
|
|
1739
1743
|
protected override lifecycleHookPaths(event: "connect" | "disconnect"): readonly string[] {
|
|
1740
1744
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1741
1745
|
}
|
|
@@ -1775,7 +1779,7 @@ ${yt}${bt}${_t}${Pt}
|
|
|
1775
1779
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1776
1780
|
return LUNORA_STUDIO_FEATURES;
|
|
1777
1781
|
}
|
|
1778
|
-
${
|
|
1782
|
+
${re.evaluateOverride}${re.subscriptionOverride}${ct}${pt}
|
|
1779
1783
|
protected override advisories(): AdvisoryFinding[] {
|
|
1780
1784
|
return LUNORA_ADVISORIES;
|
|
1781
1785
|
}
|
|
@@ -1997,7 +2001,7 @@ ${ne.evaluateOverride}${ne.subscriptionOverride}${ct}${pt}
|
|
|
1997
2001
|
// dispatch path) fall back to the per-request fields as before.
|
|
1998
2002
|
const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
|
|
1999
2003
|
const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
|
|
2000
|
-
${Ot}${
|
|
2004
|
+
${Ot}${ne}${Mt}${ve}${de}${ie}${ce}
|
|
2001
2005
|
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
2002
2006
|
// Build the storage adapter once and share it between \`ctx.storage\`
|
|
2003
2007
|
// and \`ctx.db.system._storage\` so both read the same R2 binding. The
|
|
@@ -2030,7 +2034,7 @@ ${Dt} // \`ctx.db\`, wrapped in automatic instrumentation: by default
|
|
|
2030
2034
|
// handler making hundreds of queries stays readable. See
|
|
2031
2035
|
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
2032
2036
|
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${Tt}), logFunctionPath, traceAnchor, observability);
|
|
2033
|
-
${Ft}${
|
|
2037
|
+
${Ft}${Te}
|
|
2034
2038
|
|
|
2035
2039
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
2036
2040
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -2065,7 +2069,7 @@ ${Bt}
|
|
|
2065
2069
|
scheduler,
|
|
2066
2070
|
span,
|
|
2067
2071
|
storage,
|
|
2068
|
-
trace,${At}${C}${qt}${
|
|
2072
|
+
trace,${At}${C}${qt}${ue}${$e}${Se}${se}${Ne}
|
|
2069
2073
|
};
|
|
2070
2074
|
${Wt}${jt}
|
|
2071
2075
|
ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
|
|
@@ -2075,19 +2079,19 @@ ${Wt}${jt}
|
|
|
2075
2079
|
return ctx;
|
|
2076
2080
|
}
|
|
2077
2081
|
};
|
|
2078
|
-
`},
|
|
2082
|
+
`},Be=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:T(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}}},zn=(e,t,n)=>{m(e,"drizzle column name");const r=Be(t),a=t.kind==="optional"&&t.inner?t.inner:t,o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;return r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`),a.kind==="id"&&a.tableName&&n.has(a.tableName)&&(s+=`.references(() => ${a.tableName}._id)`),r.notNull&&(s+=".notNull()"),s},Xn=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}),`},Yn=(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}: ${zn(a,o,t)},`)].join(`
|
|
2079
2083
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2080
2084
|
${e.indexes.map(a=>Xn(a)).join(`
|
|
2081
2085
|
`)}
|
|
2082
2086
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2083
2087
|
${n}
|
|
2084
|
-
}${r});`},Zn=e=>{const t=new Set,n=new Set;t.add("text"),t.add("integer"),t.add("sqliteTable");for(const r of e){for(const a of Object.values(r.shape)){const o=
|
|
2088
|
+
}${r});`},Zn=e=>{const t=new Set,n=new Set;t.add("text"),t.add("integer"),t.add("sqliteTable");for(const r of e){for(const a of Object.values(r.shape)){const o=Be(a);t.add(o.builder)}for(const a of r.indexes)n.add(a.unique?"uniqueIndex":"index")}return{columns:[...t].toSorted((r,a)=>r.localeCompare(a)),indexes:[...n].toSorted((r,a)=>r.localeCompare(a))}},Xe=(e,t=!1)=>{if(e.length===0)return`${k}export {};
|
|
2085
2089
|
`;const n=V(t),{columns:r,indexes:a}=Zn(e),o=[...a,...r].toSorted((l,u)=>l.localeCompare(u)),s=new Set(e.map(l=>l.name)),i=e.map(l=>Yn(l,s)).join(`
|
|
2086
2090
|
|
|
2087
2091
|
`);return`${k}import { ${o.join(", ")} } from "${n.serverDrizzle}";
|
|
2088
2092
|
|
|
2089
2093
|
${i}
|
|
2090
|
-
`},mr=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:
|
|
2094
|
+
`},mr=(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)}},fr=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(`
|
|
2091
2095
|
`),a=r.length>0?`
|
|
2092
2096
|
${r}
|
|
2093
2097
|
`:"",o=[...n.entries()].map(([i,l])=>{const u=l.map(p=>{const b=p.workflow?`workflow: ${JSON.stringify(p.workflow.binding)}`:`functionPath: ${JSON.stringify(p.functionPath)}`;return` { name: ${JSON.stringify(p.name)}, ${b}, args: ${JSON.stringify(p.args)} },`}).join(`
|
|
@@ -2145,4 +2149,4 @@ export interface LunoraVectorIndex {
|
|
|
2145
2149
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2146
2150
|
*/
|
|
2147
2151
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2148
|
-
`},yr=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{pr as B,ar as
|
|
2152
|
+
`},yr=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{pr as B,ar as G,gr as J,ur as M,cr as _,Ut as a,dr as b,sr as c,$n as d,mr as e,rr as f,lr as h,hr as j,ir as l,br as n,yr as r,or as s,fr as t,k as w};
|