@lunora/codegen 1.0.0-alpha.82 → 1.0.0-alpha.83
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +584 -549
- package/dist/index.d.ts +584 -549
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-CH5disA3.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-oy7DTIDi.mjs +1 -0
- package/dist/packem_shared/{OPENRPC_VERSION-IKkrtXye.mjs → OPENRPC_VERSION-K3RTK2CP.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-ZIqaP_TZ.mjs +9 -0
- package/dist/packem_shared/{buildOpenApiDocument-XeZ1ycwi.mjs → buildOpenApiDocument-Blf3mpIz.mjs} +1 -1
- package/dist/packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs +1 -0
- package/dist/packem_shared/discover-queries-Bhu9SNsy.mjs +1 -0
- package/dist/packem_shared/discoverCrons-DLwFH_K5.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-ZewKJLXx.mjs +1 -0
- package/dist/packem_shared/{discoverQueries-2A0lbpxV.mjs → discoverQueries-g4qZzLpl.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-4nJgoLaJ.mjs +1 -0
- package/dist/packem_shared/{emit-05q6XTbd.mjs → emit-B7IUlWwi.mjs} +265 -215
- package/dist/packem_shared/{emitApp-C2DhPKWE.mjs → emitApp-jRD2D9kI.mjs} +111 -37
- package/package.json +10 -10
- package/dist/packem_shared/DEFAULT_TARGET-BYPEwgZu.mjs +0 -1
- package/dist/packem_shared/GENERATED_HEADER-Cphn03Kf.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DBD0oti8.mjs +0 -12
- package/dist/packem_shared/discover-queries-Ctpk9SA-.mjs +0 -1
- package/dist/packem_shared/discoverCrons-CwtPaymU.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-DQ-4yUUK.mjs +0 -1
- package/dist/packem_shared/discoverSchema-CaTD2Sdx.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as
|
|
1
|
+
import{agentComponent as tt}from"@lunora/agent/component";import{LunoraError as Z}from"@lunora/errors";import{serializeSchemaSnapshot as on,hashSchemaSnapshot as sn}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{n as R}from"./paths-BmX5O1sG.mjs";const nt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",serverCtxField:{field:`
|
|
2
2
|
/** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
|
|
3
3
|
readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",serverCtxField:{field:`
|
|
4
4
|
/** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
|
|
@@ -15,38 +15,38 @@ import{agentComponent as Ze}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"}],
|
|
18
|
+
readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],ln=nt,dn=new Map(ln.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Or=nt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),rt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,cn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),at=e=>e.column!==void 0,un=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
|
|
19
19
|
`;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
|
|
20
20
|
`;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
|
|
21
21
|
`;case"null":return`if (${t} !== null) return DEFER;
|
|
22
22
|
`;default:return`if (typeof ${t} !== "string") return DEFER;
|
|
23
|
-
`}},
|
|
24
|
-
`}},
|
|
23
|
+
`}},pn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!rt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
|
|
24
|
+
`}},Me=(e,t,n)=>{if(!at(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(cn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:un(e.kind,t)};switch(e.kind){case"array":return hn(e,t,n);case"literal":return pn(e,t);case"object":return mn(e,t,n);default:return}}},hn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const a=n.next(),o=`__arr${String(a)}`,i=`__i${String(a)}`,s=`__e${String(a)}`,l=Me(r,s,n);if(!l)return;const u=`if (!Array.isArray(${t})) return DEFER;
|
|
25
25
|
const ${o} = new Array(${t}.length);
|
|
26
26
|
for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
|
|
27
27
|
const ${s} = ${t}[${i}];
|
|
28
28
|
${l.pre}${o}[${i}] = ${l.out};
|
|
29
29
|
}
|
|
30
|
-
`;return{out:o,pre:u}},
|
|
30
|
+
`;return{out:o,pre:u}},gn=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||at(t))return;const{inner:i}=t;if(!i)return;const s=Me(i,n,r);if(!s)return;const l=r.next(),u=`__has${String(l)}`,p=`__val${String(l)}`,f=`let ${u} = false;
|
|
31
31
|
let ${p};
|
|
32
32
|
if (${n} !== undefined) {
|
|
33
33
|
${s.pre}${p} = ${s.out};
|
|
34
34
|
${u} = true;
|
|
35
35
|
}
|
|
36
|
-
`;return{entry:`...(${u} ? { ${a}: ${p} } : {})`,pre:f}}const o=
|
|
36
|
+
`;return{entry:`...(${u} ? { ${a}: ${p} } : {})`,pre:f}}const o=Me(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},ot=(e,t,n)=>{let r="";const a=[];for(const o of Object.keys(e)){const i=e[o];if(!i)return;const s=gn(o,i,t(o),n);if(!s)return;r+=s.pre,a.push(s.entry)}return{entries:a.join(", "),pre:r}},mn=(e,t,n)=>{const r=e.shape??{},a=ot(r,l=>`${t}[${JSON.stringify(l)}]`,n);if(!a)return;const o=n.next(),i=`__obj${String(o)}`,s=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
|
|
37
37
|
${a.pre}const ${i} = { ${a.entries} };
|
|
38
|
-
`;return{out:i,pre:s}},
|
|
38
|
+
`;return{out:i,pre:s}},fn=e=>{let t=0;const n=ot(e,r=>`source[${JSON.stringify(r)}]`,{next:()=>(t+=1,t)});if(n)return`(source) => {
|
|
39
39
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
40
40
|
${n.pre}return { ${n.entries} };
|
|
41
|
-
}`},
|
|
41
|
+
}`},v=`// GENERATED by @lunora/codegen — do not edit.
|
|
42
42
|
// Run \`lunora codegen\` to regenerate.
|
|
43
43
|
|
|
44
|
-
`,
|
|
44
|
+
`,G=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},st=/^[A-Za-z_$][\w$]*$/u,bn=/^[\w./-]+$/u,m=(e,t)=>{if(!st.test(e))throw new Z("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Fe=e=>e.charAt(0).toUpperCase()+e.slice(1),D=e=>st.test(e)?e:JSON.stringify(e),yn={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},wn=e=>{if(e===void 0)return"unknown";if(!rt.test(e))throw new Z("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},C=e=>{const t=yn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?C(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return m(n,"v.id() table name"),`Id<"${n}">`}case"literal":return wn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([n,r])=>it(n,r)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?C(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?C(e.keyType):"string",r=e.valueType?C(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>C(n)).join(" | "):"never";default:return"unknown"}},it=(e,t)=>{const n=D(e);if(t.kind==="optional"){const r=t.inner?C(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${C(t)}`},me=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>it(n,r)).join("; ")} }`},xn=e=>e.kind==="optional"||!!e.column?.hasDefault,kn=e=>{m(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=a.kind==="optional"&&a.inner?a.inner:a,i=C(o),s=D(r);return xn(a)?` ${s}?: ${i};`:` ${s}: ${i};`}).join(`
|
|
45
45
|
`),n=t?`
|
|
46
46
|
${t}
|
|
47
47
|
`:"";return`export interface Insert_${e.name} {
|
|
48
48
|
_id?: Id<"${e.name}">;
|
|
49
|
-
_creationTime?: number;${n}}`},
|
|
49
|
+
_creationTime?: number;${n}}`},Tr=(e,t=!1)=>{const n=G(t);for(const c of e.tables)m(c.name,"table name");const r=e.tables.map(c=>`"${c.name}"`).join(" | ")||"never",a=e.tables.filter(c=>c.extensionKey===void 0).map(c=>`"${c.name}"`).join(" | ")||"never",o=e.tables.map(c=>{const g=Object.entries(c.shape).map(([k,$])=>{const T=D(k);if($.kind==="optional"){const O=$.inner?C($.inner):"unknown";return` ${T}?: ${O};`}return` ${T}: ${C($)};`}).join(`
|
|
50
50
|
`),b=g?`
|
|
51
51
|
${g}
|
|
52
52
|
`:"";return`export interface Doc_${c.name} {
|
|
@@ -58,14 +58,14 @@ ${g}
|
|
|
58
58
|
`),l=e.tables.map(c=>{const g=c.searchIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
59
59
|
`),u=e.tables.map(c=>{const g=c.rankIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
60
60
|
`),p=e.tables.map(c=>{const g=c.shardMode==="global"?"":(c.geoIndexes??[]).map(b=>JSON.stringify(b.name)).join(" | ");return` ${c.name}: ${g||"never"};`}).join(`
|
|
61
|
-
`),f=e.vectorIndexes.map(c=>JSON.stringify(c.name)).join(" | ")||"never",y=e.tables.map(c=>
|
|
61
|
+
`),f=e.vectorIndexes.map(c=>JSON.stringify(c.name)).join(" | ")||"never",y=e.tables.map(c=>kn(c)).join(`
|
|
62
62
|
|
|
63
|
-
`),
|
|
63
|
+
`),N=e.tables.map(c=>` ${c.name}: Insert_${c.name};`).join(`
|
|
64
64
|
`),d=e.tables.map(c=>{const g=c.relations.map(b=>(m(b.table,"relation target table"),` ${D(b.name)}: ${b.kind==="one"?"OneRelation":"ManyRelation"}<"${b.table}">;`)).join(`
|
|
65
65
|
`);return g?` ${c.name}: {
|
|
66
66
|
${g}
|
|
67
67
|
};`:` ${c.name}: {};`}).join(`
|
|
68
|
-
`);return`${
|
|
68
|
+
`);return`${v}import type {
|
|
69
69
|
DatabaseReaderFacade as DatabaseReaderFacadeOf,
|
|
70
70
|
DatabaseWriterFacade as DatabaseWriterFacadeOf,
|
|
71
71
|
LoadWith as LoadWithOf,
|
|
@@ -164,7 +164,7 @@ ${y}
|
|
|
164
164
|
|
|
165
165
|
/** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
|
|
166
166
|
export interface InsertModel {
|
|
167
|
-
${
|
|
167
|
+
${N}
|
|
168
168
|
}
|
|
169
169
|
|
|
170
170
|
export type Insert<T extends keyof DataModel> = InsertModel[T];
|
|
@@ -234,11 +234,11 @@ export interface OrmWriter extends OrmReader {
|
|
|
234
234
|
replace: <T extends keyof DataModel>(table: T, id: Id<T>) => OrmReplaceBuilder<T>;
|
|
235
235
|
update: <T extends keyof DataModel>(table: T, id: Id<T>) => OrmUpdateBuilder<T>;
|
|
236
236
|
}
|
|
237
|
-
`},
|
|
238
|
-
`);return` ${D(
|
|
237
|
+
`},vn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,lt=/^(?:\.\.?\/)*_generated\//u,dt=/\.[A-Za-z]\w*$/u,qe=e=>e.replaceAll(vn,(t,n)=>{const r=n.replace(lt,"./");return`import("${dt.test(r)?r:`${r}.js`}")`}),$n=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Sn=/^(?:\.\.?\/)+/u,Rn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Be=(e,t)=>e.replaceAll($n,(n,r)=>{if(lt.test(r.replace(Sn,"")))return n;const a=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",o=`../${Rn(`${a}/${r}`)}`;return`import("${dt.test(o)?o:`${o}.js`}")`}),Nn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],On=new RegExp(String.raw`import\("@lunora/(?<pkg>${Nn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),Tn={flags:new Set(["/web"]),platform:new Set},ct=(e,t)=>t?e.replaceAll(On,(n,r,a)=>{const o=Tn[r];return a&&o&&!o.has(a)?n:`import("lunorash/${r}${a??""}")`}):e,je=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),An=e=>e.output===void 0||e.output.kind==="any"?e.returnType:C(e.output),Ze=e=>{const t=new Map;for(const r of e){const a=t.get(r.filePath)??[];a.push(r),t.set(r.filePath,a)}const n=([r,a])=>{const o=a.toSorted((i,s)=>i.exportName.localeCompare(s.exportName)).map(i=>{const s=me(i.args),l=qe(Be(An(i),i.filePath));return` ${i.exportName}: FunctionReference<"${i.kind}", ${s}, ${l}>;`}).join(`
|
|
238
|
+
`);return` ${D(R(r))}: {
|
|
239
239
|
${o}
|
|
240
240
|
};`};return[...t.entries()].toSorted(([r],[a])=>r.localeCompare(a)).map(r=>n(r)).join(`
|
|
241
|
-
`)}
|
|
241
|
+
`)},Ln=(e,t)=>{if(e.length===0&&t.length===0)return{block:"",importLine:""};const n=[];let r="";if(e.length>0&&(r+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),r+=`
|
|
242
242
|
/** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
|
|
243
243
|
export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
244
244
|
readonly isLunoraWorkflow: true;
|
|
@@ -270,7 +270,7 @@ export const agents: AgentsRef = {
|
|
|
270
270
|
${i}
|
|
271
271
|
};
|
|
272
272
|
`,n.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
273
|
-
`)}return{block:r,importLine:n.join("")}},
|
|
273
|
+
`)}return{block:r,importLine:n.join("")}},Cn=()=>Object.keys(tt().functions).toSorted((e,t)=>e.localeCompare(t)),ut=e=>new Set(e.filter(t=>R(t.filePath)==="agents").map(t=>t.exportName)),In=()=>new Set(Object.entries(tt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Dn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=ut(t),a=In(),o=t.find(s=>R(s.filePath)==="agents"&&a.has(s.exportName));if(o)throw new Z("INTERNAL",`@lunora/codegen: "agents:${o.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${o.exportName}" export in ${o.filePath}`);const i=Cn().filter(s=>!r.has(s));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
274
274
|
`,lines:i.map(s=>` "agents:${s}": lunoraAgentRuntimeFunctions.${s} as unknown as RegisteredLunoraFunction,`).join(`
|
|
275
275
|
`),prelude:`
|
|
276
276
|
/**
|
|
@@ -279,13 +279,13 @@ ${i}
|
|
|
279
279
|
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
280
280
|
*/
|
|
281
281
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
282
|
-
`}},
|
|
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"}},
|
|
284
|
-
`);return` ${D(
|
|
282
|
+
`}},_n=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>R(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new Z("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
|
|
283
|
+
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},En=(e,t)=>{if(e.length===0)return[];const n=ut(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const a of e)a.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${a.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(a=>!n.has(a.exportName))},Pn=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>R(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},Fn=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=new Map;for(const i of t){const s=n.get(i.filePath)??[];s.push(i),n.set(i.filePath,s)}const r=[...n.entries()].toSorted(([i],[s])=>i.localeCompare(s)),a=r.map(([i,s])=>{const l=s.map(u=>{const p=qe(Be(u.chunkType??"unknown",u.filePath));return` ${D(u.exportName)}: HttpStreamRef<${p}, ${me(u.searchParams)}, ${me(u.params)}>;`}).join(`
|
|
284
|
+
`);return` ${D(R(i))}: {
|
|
285
285
|
${l}
|
|
286
286
|
};`}).join(`
|
|
287
287
|
`),o=r.map(([i,s])=>{const l=s.map(u=>` ${D(u.exportName)}: { method: ${JSON.stringify(u.method)}, path: ${JSON.stringify(u.path)} },`).join(`
|
|
288
|
-
`);return` ${D(
|
|
288
|
+
`);return` ${D(R(i))}: {
|
|
289
289
|
${l}
|
|
290
290
|
},`}).join(`
|
|
291
291
|
`);return{block:`
|
|
@@ -297,15 +297,15 @@ ${a}
|
|
|
297
297
|
export const httpStreams: HttpStreamsRef = {
|
|
298
298
|
${o}
|
|
299
299
|
};
|
|
300
|
-
`,body:a}},
|
|
300
|
+
`,body:a}},Ar=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=G(o),l=[...n.filter(S=>S.visibility!=="internal"),...En(t,n),...Pn(a,n)],u=n.filter(S=>S.visibility==="internal"),p=Ze(l),f=Ze(u),y=Fn(r),N=`${p}
|
|
301
301
|
${f}
|
|
302
|
-
${y.body}`,d=
|
|
302
|
+
${y.body}`,d=je(N),c=d.length>0?`
|
|
303
303
|
import type { ${d.join(", ")} } from "./dataModel.js";
|
|
304
304
|
`:"",g=p?`
|
|
305
305
|
${p}
|
|
306
306
|
`:"",b=f?`
|
|
307
307
|
${f}
|
|
308
|
-
`:"",
|
|
308
|
+
`:"",k=Ln(i,t),$=`export interface ApiTypes {${g}}
|
|
309
309
|
|
|
310
310
|
export const api = anyApi as unknown as ApiTypes;
|
|
311
311
|
|
|
@@ -313,10 +313,10 @@ export const api = anyApi as unknown as ApiTypes;
|
|
|
313
313
|
export interface InternalApiTypes {${b}}
|
|
314
314
|
|
|
315
315
|
export const internal = anyApi as unknown as InternalApiTypes;
|
|
316
|
-
${
|
|
317
|
-
`:"";return
|
|
318
|
-
${
|
|
319
|
-
${
|
|
316
|
+
${k.block}${y.block}`,T=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],O=T.length>0?`import type { ${T.join(", ")} } from "${s.client}";
|
|
317
|
+
`:"";return ct(`${v}import { anyApi } from "${s.client}";
|
|
318
|
+
${O}${k.importLine}${c}
|
|
319
|
+
${$}`,o)},Lr=e=>e?`${v}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
320
320
|
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
321
321
|
|
|
322
322
|
import schema from "../schema.js";
|
|
@@ -333,8 +333,8 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
333
333
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
334
334
|
*/
|
|
335
335
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
336
|
-
`:"",
|
|
337
|
-
export interface ${
|
|
336
|
+
`:"",Cr=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=G(n),a=l=>l.table===void 0?"Row":`Doc<${JSON.stringify(l.table)}> & Row`,o=e.map(l=>{m(l.exportName,"shape export name");const u=a(l),p=me(l.args),f=Object.keys(l.args).length>0,y=f?` args: ${p};`:` args?: ${p};`,N=f?`(args: ${p}) => void`:`(args?: ${p}) => void`,d=`${l.exportName}CollectionOptions`;return`/** Options for the \`${l.exportName}\` shape binding. */
|
|
337
|
+
export interface ${Fe(d)} {
|
|
338
338
|
${y}
|
|
339
339
|
/**
|
|
340
340
|
* Share the optimistic-overlay gate with other collections + mutators on this
|
|
@@ -359,7 +359,7 @@ ${y}
|
|
|
359
359
|
* \`createCollection\`, plus the \`checkpoints\` registry to hand \`bindMutators\` and
|
|
360
360
|
* \`scope\` to re-point the subscription.
|
|
361
361
|
*/
|
|
362
|
-
export const ${l.exportName}CollectionOptions = (options: ${
|
|
362
|
+
export const ${l.exportName}CollectionOptions = (options: ${Fe(d)}): LunoraCollectionOptions<${u}> =>
|
|
363
363
|
lunoraCollectionOptions<${u}>({
|
|
364
364
|
client: options.client,
|
|
365
365
|
...(options.checkpoints === undefined ? {} : { checkpoints: options.checkpoints }),
|
|
@@ -372,22 +372,22 @@ export const ${l.exportName}CollectionOptions = (options: ${Ee(d)}): LunoraColle
|
|
|
372
372
|
|
|
373
373
|
/** Live collection for the \`${l.exportName}\` shape, with its sync controls. */
|
|
374
374
|
export const ${l.exportName}Collection = (
|
|
375
|
-
options: ${
|
|
376
|
-
): { checkpoints: CheckpointRegistry; collection: Collection<${u}, string>; scope: ${
|
|
375
|
+
options: ${Fe(d)},
|
|
376
|
+
): { checkpoints: CheckpointRegistry; collection: Collection<${u}, string>; scope: ${N} } => {
|
|
377
377
|
const { checkpoints, config, scope } = ${l.exportName}CollectionOptions(options);
|
|
378
378
|
|
|
379
379
|
return { checkpoints, collection: createCollection(config), scope };
|
|
380
380
|
};`}).join(`
|
|
381
381
|
|
|
382
|
-
`),i=
|
|
383
|
-
`:"";return`${
|
|
382
|
+
`),i=je(o),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
|
|
383
|
+
`:"";return`${v}import type { LunoraClient, SubscriptionError } from "${r.client}";
|
|
384
384
|
import { lunoraCollectionOptions } from "@lunora/db/collections";
|
|
385
385
|
import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
|
|
386
386
|
import type { Collection } from "@tanstack/db";
|
|
387
387
|
import { createCollection } from "@tanstack/db";
|
|
388
388
|
${s}
|
|
389
389
|
${o}
|
|
390
|
-
`},
|
|
390
|
+
`},Mn=(e,t)=>`lunora_${R(e)}_${String(t)}`,qn=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
391
391
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
392
392
|
|
|
393
393
|
if (!registered) {
|
|
@@ -395,41 +395,41 @@ ${o}
|
|
|
395
395
|
}
|
|
396
396
|
|
|
397
397
|
return (await registered.handler(context, args ?? {})) as R;
|
|
398
|
-
};`,
|
|
399
|
-
`),s=e.map(d=>` "${
|
|
398
|
+
};`,Bn=(e,t,n=[],r=[])=>{const a=new Map,o=d=>{a.has(d)||a.set(d,Mn(d,a.size))};for(const d of e)o(d.filePath);for(const d of t)o(d.filePath);for(const d of n)o(d.filePath);for(const d of r)o(d.filePath);const i=[...a.entries()].map(([d,c])=>{if(!bn.test(d))throw new Z("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(d)}`);return`import * as ${c} from "../${d}.js";`}).join(`
|
|
399
|
+
`),s=e.map(d=>` "${R(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
400
400
|
`),l=t.map(d=>` ${JSON.stringify(d.id)}: ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
401
|
-
`),u=n.map(d=>` "${
|
|
401
|
+
`),u=n.map(d=>` "${R(d.filePath)}:${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
402
402
|
`),p=r.map(d=>` "${d.exportName}": ${a.get(d.filePath)??""}.${d.exportName} as unknown as RegisteredShape,`).join(`
|
|
403
|
-
`),f=n.map(d=>`${
|
|
404
|
-
`),
|
|
403
|
+
`),f=n.map(d=>`${R(d.filePath)}:${d.exportName}`),y=[s,u].filter(d=>d.length>0).join(`
|
|
404
|
+
`),N=e.map(d=>{if(d.lifecycle||Object.keys(d.args).length===0)return;const c=fn(d.args);return c===void 0?void 0:`installCompiledValidatorMap(${a.get(d.filePath)??""}.${d.exportName}.args, ${c});`}).filter(d=>d!==void 0).join(`
|
|
405
405
|
`);return{dispatchBody:y.length>0?`
|
|
406
406
|
${y}
|
|
407
407
|
`:"",importBlock:i.length>0?`${i}
|
|
408
408
|
|
|
409
|
-
`:"",installBlock:
|
|
409
|
+
`:"",installBlock:N,migrationBody:l.length>0?`
|
|
410
410
|
${l}
|
|
411
411
|
`:"",mutatorPaths:f,shapeBody:p.length>0?`
|
|
412
412
|
${p}
|
|
413
|
-
`:""}},
|
|
414
|
-
`);return` ${D(
|
|
413
|
+
`:""}},jn=e=>{const t=new Map;for(const a of e){const o=t.get(a.filePath)??[];o.push(a),t.set(a.filePath,o)}const n=[...t.entries()].toSorted(([a],[o])=>a.localeCompare(o)),r=n.map(([a,o])=>{const i=o.map(s=>{const l=me(s.args),u=l==="{}"?"?":"",p=qe(Be(s.returnType,s.filePath));return s.kind==="stream"?` ${s.exportName}: (args${u}: ${l}) => Promise<AsyncIterable<${p}>>;`:` ${s.exportName}: (args${u}: ${l}) => Promise<${p}>;`}).join(`
|
|
414
|
+
`);return` ${D(R(a))}: {
|
|
415
415
|
${i}
|
|
416
416
|
};`}).join(`
|
|
417
|
-
`);return{implementation:n.map(([a,o])=>{const i=
|
|
417
|
+
`);return{implementation:n.map(([a,o])=>{const i=R(a),s=o.map(l=>` ${l.exportName}: (args) => callRegistered(context, "${i}:${l.exportName}", args),`).join(`
|
|
418
418
|
`);return` ${D(i)}: {
|
|
419
419
|
${s}
|
|
420
420
|
},`}).join(`
|
|
421
|
-
`),types:r}},
|
|
421
|
+
`),types:r}},Wn=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=a.kind==="optional"&&a.inner?a.inner:a;o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},Ir=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasFlags:s=!1,hasHyperdrive:l=!1,hasImages:u=!1,hasKv:p=!1,hasNotify:f=!1,hasPayments:y=!1,hasPipelines:N=!1,hasR2sql:d=!1,hasX402:c=!1,identity:g,queues:b=[],schema:k,storageRuleBuckets:$=[],useUmbrella:T=!1,workflows:O=[]}={})=>{const S=G(T),x=Wn(k??{tables:[]},$).map(h=>JSON.stringify(h)).join(" | "),P=a?`import type { LunoraAi } from "@lunora/ai";
|
|
422
422
|
`:"",ee=a?`
|
|
423
423
|
readonly ai: LunoraAi;`:"",F=y?`import type { LunoraPayment } from "@lunora/payment";
|
|
424
424
|
`:"",te=y?`
|
|
425
425
|
readonly payments: LunoraPayment;`:"",ne=c?`import type { X402Pay } from "@lunora/x402/pay";
|
|
426
426
|
`:"",B=c?`
|
|
427
|
-
readonly x402: X402Pay;`:"",
|
|
427
|
+
readonly x402: X402Pay;`:"",A=t.length>0?`import type { ContainerAccessor } from "@lunora/container";
|
|
428
428
|
`:"",z=t.length>0?`
|
|
429
429
|
readonly containers: {${t.map(h=>`
|
|
430
430
|
readonly ${h.exportName}: ContainerAccessor;`).join("")}
|
|
431
|
-
};`:"",
|
|
432
|
-
readonly ${h.bindingName}?: unknown;`)),...
|
|
431
|
+
};`:"",L=[...a?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(h=>(m(h.bindingName,`container binding "${h.bindingName}"`),` /** Durable Object namespace for the \`${h.exportName}\` container. */
|
|
432
|
+
readonly ${h.bindingName}?: unknown;`)),...O.map(h=>(m(h.bindingName,`workflow binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` workflow. */
|
|
433
433
|
readonly ${h.bindingName}?: unknown;`)),...b.map(h=>(m(h.bindingName,`queue binding "${h.bindingName}"`),` /** Queue producer binding for the \`${h.exportName}\` queue. */
|
|
434
434
|
readonly ${h.bindingName}?: unknown;`)),...e.map(h=>(m(h.bindingName,`agent binding "${h.bindingName}"`),` /** Workflow binding for the \`${h.exportName}\` agent. */
|
|
435
435
|
readonly ${h.bindingName}?: unknown;`))].join(`
|
|
@@ -446,26 +446,26 @@ ${s}
|
|
|
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;${L?`
|
|
450
|
+
${L}`:""}
|
|
451
451
|
}
|
|
452
452
|
|
|
453
453
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
454
|
-
export type Env = CloudflareBindings;`,M=(h,
|
|
455
|
-
readonly vectors: VectorSearch<VectorIndexName>;`:"",se=
|
|
456
|
-
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",
|
|
454
|
+
export type Env = CloudflareBindings;`,M=(h,_e)=>_e?dn.get(h)?.field??"":"",re=M("kv",p),ae=M("analytics",o),ke=M("hyperdrive",l),ve=M("browser",i),$e=M("images",u),oe=M("pipelines",N),K=M("r2sql",d),E=(k?.vectorIndexes.length??0)>0,Q=E?' | "vectors"':"",X=E?`
|
|
455
|
+
readonly vectors: VectorSearch<VectorIndexName>;`:"",se=E?`
|
|
456
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",H=E?`import type { VectorSearch, VectorSearchReader } from "${S.server}";
|
|
457
457
|
import type { VectorIndexName } from "./dataModel.js";
|
|
458
458
|
`:"",j=r?`
|
|
459
459
|
/** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
|
|
460
460
|
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",W=s?`
|
|
461
461
|
/** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
|
|
462
|
-
readonly flags: import("${
|
|
462
|
+
readonly flags: import("${S.flags}").LunoraFlags;`:"",U=f?`
|
|
463
463
|
/** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
|
|
464
464
|
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
465
465
|
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
466
|
-
readonly push: import("@lunora/notify").LunoraPush;`:"",q=
|
|
466
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",q=O.length>0,Y=q?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
467
467
|
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
468
|
-
`:""
|
|
468
|
+
`:"",Se=q?`
|
|
469
469
|
|
|
470
470
|
/** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
|
|
471
471
|
type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
|
|
@@ -476,12 +476,12 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
476
476
|
|
|
477
477
|
/** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
|
|
478
478
|
export interface LunoraWorkflows {
|
|
479
|
-
${
|
|
479
|
+
${O.map(h=>` get(name: ${JSON.stringify(h.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${h.exportName}>>;`).join(`
|
|
480
480
|
`)}
|
|
481
481
|
}`:"",fe=q?' | "workflows"':"",be=q?`
|
|
482
|
-
readonly workflows: LunoraWorkflows;`:"",ie=b.length>0,
|
|
482
|
+
readonly workflows: LunoraWorkflows;`:"",ie=b.length>0,Re=ie?`import type { QueueProducer } from "@lunora/queue";
|
|
483
483
|
import type * as lunoraQueueDefinitions from "../queues.js";
|
|
484
|
-
`:"",
|
|
484
|
+
`:"",Ne=ie?`
|
|
485
485
|
|
|
486
486
|
/** Message body type carried by a \`defineQueue\` definition (its phantom \`__lunoraBody\`). */
|
|
487
487
|
type QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;
|
|
@@ -491,28 +491,28 @@ export interface LunoraQueues {
|
|
|
491
491
|
${b.map(h=>` readonly ${h.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${h.exportName}>>;`).join(`
|
|
492
492
|
`)}
|
|
493
493
|
}`:"",ye=ie?`
|
|
494
|
-
readonly queues: LunoraQueues;`:"",le=e.length>0,
|
|
495
|
-
`:"",
|
|
494
|
+
readonly queues: LunoraQueues;`:"",le=e.length>0,Oe=le?`import type { AgentHandle } from "@lunora/agent";
|
|
495
|
+
`:"",Te=le?`
|
|
496
496
|
|
|
497
497
|
/** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
|
|
498
498
|
export interface LunoraAgents {
|
|
499
499
|
${e.map(h=>(m(h.exportName,`agent export "${h.exportName}"`),` readonly ${h.exportName}: AgentHandle;`)).join(`
|
|
500
500
|
`)}
|
|
501
501
|
}`:"",we=le?`
|
|
502
|
-
readonly agents: LunoraAgents;`:"",
|
|
502
|
+
readonly agents: LunoraAgents;`:"",Ae=g?`import type { InferIdentity } from "${S.server}";
|
|
503
503
|
import type * as lunoraIdentityContract from "../identity.js";
|
|
504
|
-
`:"",
|
|
504
|
+
`:"",Le=g?`
|
|
505
505
|
|
|
506
506
|
/** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
|
|
507
507
|
export type Identity = InferIdentity<typeof lunoraIdentityContract.${g.exportName}>;
|
|
508
508
|
|
|
509
509
|
/** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
|
|
510
510
|
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",de=g?' | "auth"':"",ce=g?`
|
|
511
|
-
readonly auth: NarrowedAuth;`:"",
|
|
512
|
-
`:"",
|
|
511
|
+
readonly auth: NarrowedAuth;`:"",Ce=g?", Identity":"",Ie=n?`import type * as lunoraEnvContract from "../env.js";
|
|
512
|
+
`:"",De=n?`
|
|
513
513
|
|
|
514
514
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
515
|
-
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",ue=n?' | "env"':"",pe=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${
|
|
515
|
+
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${n.exportName}>;`:"",ue=n?' | "env"':"",pe=n?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${v}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${S.server}";
|
|
516
516
|
import type {
|
|
517
517
|
ActionBuilder,
|
|
518
518
|
ActionCtx as ActionCtxBase,
|
|
@@ -533,14 +533,14 @@ import type {
|
|
|
533
533
|
Storage as StorageBase,
|
|
534
534
|
TableReader,
|
|
535
535
|
Validator,
|
|
536
|
-
} from "${
|
|
536
|
+
} from "${S.server}";
|
|
537
537
|
|
|
538
538
|
import type { DataModel, DatabaseReaderFacade, DatabaseWriterFacade, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, OrmReader, OrmWriter, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
|
|
539
|
-
${
|
|
539
|
+
${H}${P}${F}${ne}${A}${Y}${Re}${Oe}${Ae}${Ie}
|
|
540
540
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
541
541
|
|
|
542
542
|
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
543
|
-
export type StorageBucketName = ${
|
|
543
|
+
export type StorageBucketName = ${x};${I}${Se}${Ne}${Te}${Le}${De}
|
|
544
544
|
|
|
545
545
|
/**
|
|
546
546
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -618,7 +618,7 @@ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${Q}$
|
|
|
618
618
|
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${Q}${fe}${de}${ue}> {
|
|
619
619
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
620
620
|
readonly orm: OrmWriter;
|
|
621
|
-
readonly storage: StorageBase<StorageBucketName>;${X}${j}${ee}${te}${B}${z}${re}${W}${U}${
|
|
621
|
+
readonly storage: StorageBase<StorageBucketName>;${X}${j}${ee}${te}${B}${z}${re}${W}${U}${ke}${ve}${$e}${ae}${oe}${K}${pe}${be}${ye}${we}${ce}
|
|
622
622
|
}
|
|
623
623
|
|
|
624
624
|
/**
|
|
@@ -651,7 +651,7 @@ export const internalAction = lunoraBuilders.internalAction as unknown as Intern
|
|
|
651
651
|
/**
|
|
652
652
|
* \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
|
|
653
653
|
* custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
|
|
654
|
-
* \`${
|
|
654
|
+
* \`${S.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
|
|
655
655
|
* schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
|
|
656
656
|
* \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
|
|
657
657
|
* no \`as unknown as\` cast. Runtime-identical to the package export; only the
|
|
@@ -676,7 +676,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
|
|
|
676
676
|
* Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
|
|
677
677
|
* so the \`rls()\` chain discovers a policy authored either way the same.
|
|
678
678
|
*/
|
|
679
|
-
export const definePolicy = createPolicyDsl<DataModel, Relations${
|
|
679
|
+
export const definePolicy = createPolicyDsl<DataModel, Relations${Ce}>();
|
|
680
680
|
|
|
681
681
|
/**
|
|
682
682
|
* The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
|
|
@@ -693,13 +693,13 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Le}>();
|
|
|
693
693
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
694
694
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
695
695
|
};
|
|
696
|
-
`},
|
|
697
|
-
`);let
|
|
698
|
-
${
|
|
696
|
+
`},Un=e=>{const t={connect:[],disconnect:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${R(n.filePath)}:${n.exportName}`);return t},Dr=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,l=n.length>0,u=G(i),{dispatchBody:p,importBlock:f,installBlock:y,migrationBody:N,mutatorPaths:d,shapeBody:c}=Bn(n,r,a,o),g=Dn(t,n),b=_n(s,n),k=[g.lines,b.lines].filter(I=>I.length>0).join(`
|
|
697
|
+
`);let $=p;k.length>0&&($=p.length>0?`${p.trimEnd()}
|
|
698
|
+
${k}
|
|
699
699
|
`:`
|
|
700
|
-
${
|
|
701
|
-
`);const
|
|
702
|
-
`:""
|
|
700
|
+
${k}
|
|
701
|
+
`);const T=Un(n),O=o.length>0?`import type { RegisteredShape } from "${u.server}";
|
|
702
|
+
`:"",S=o.length>0?`
|
|
703
703
|
/**
|
|
704
704
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
705
705
|
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
@@ -707,14 +707,14 @@ ${x}
|
|
|
707
707
|
* \`shape_subscribe\` (reads-as-permissions).
|
|
708
708
|
*/
|
|
709
709
|
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${c}};
|
|
710
|
-
`:"",
|
|
710
|
+
`:"",x=d.length>0?`
|
|
711
711
|
/**
|
|
712
712
|
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
713
713
|
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
714
714
|
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
715
715
|
*/
|
|
716
716
|
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(I=>JSON.stringify(I)).join(", ")}]);
|
|
717
|
-
`:"",
|
|
717
|
+
`:"",P=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
|
|
718
718
|
`:"",ee=y.length>0?`
|
|
719
719
|
/**
|
|
720
720
|
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
@@ -722,16 +722,16 @@ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${d.map(I=>JSO
|
|
|
722
722
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
723
723
|
*/
|
|
724
724
|
${y}
|
|
725
|
-
`:"",F=
|
|
725
|
+
`:"",F=jn(n),te=F.types?`
|
|
726
726
|
${F.types}
|
|
727
727
|
`:"",ne=F.implementation?`
|
|
728
728
|
${F.implementation}
|
|
729
|
-
`:"",B=
|
|
730
|
-
`:"",z=l?"context":"_context",
|
|
729
|
+
`:"",B=je(F.types),A=B.length>0?`import type { ${B.join(", ")} } from "./dataModel.js";
|
|
730
|
+
`:"",z=l?"context":"_context",L=l?`${qn}
|
|
731
731
|
|
|
732
|
-
`:"";return
|
|
732
|
+
`:"";return ct(`${v}${f}${g.importLine}${b.importLine}${P}${O}import { LunoraError } from "${u.server}";
|
|
733
733
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
734
|
-
${
|
|
734
|
+
${A}
|
|
735
735
|
/**
|
|
736
736
|
* Single registered function, narrowed to the shape \`handleRpc\` needs.
|
|
737
737
|
* The real argument validators / return types are checked elsewhere — at
|
|
@@ -755,8 +755,8 @@ ${g.prelude}${b.prelude}
|
|
|
755
755
|
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
756
756
|
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
757
757
|
*/
|
|
758
|
-
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${
|
|
759
|
-
${ee}${
|
|
758
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${$}};
|
|
759
|
+
${ee}${S}${x}
|
|
760
760
|
/**
|
|
761
761
|
* Connection-lifecycle manifest: the function paths the generated ShardDO
|
|
762
762
|
* dispatches when a client's WebSocket connects (\`connect\`) or disconnects
|
|
@@ -764,8 +764,8 @@ ${ee}${$}${w}
|
|
|
764
764
|
* DO runs every hook under the socket's verified identity via system dispatch.
|
|
765
765
|
*/
|
|
766
766
|
export const LUNORA_LIFECYCLE_HOOKS: { connect: readonly string[]; disconnect: readonly string[] } = {
|
|
767
|
-
connect: [${
|
|
768
|
-
disconnect: [${
|
|
767
|
+
connect: [${T.connect.map(I=>JSON.stringify(I)).join(", ")}],
|
|
768
|
+
disconnect: [${T.disconnect.map(I=>JSON.stringify(I)).join(", ")}],
|
|
769
769
|
};
|
|
770
770
|
|
|
771
771
|
/**
|
|
@@ -798,7 +798,7 @@ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
|
798
798
|
*/
|
|
799
799
|
export interface Caller {${te}}
|
|
800
800
|
|
|
801
|
-
${
|
|
801
|
+
${L}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
802
802
|
export const createCaller = (${z}: CallerCtx): Caller => ({${ne}});
|
|
803
803
|
|
|
804
804
|
/**
|
|
@@ -818,8 +818,8 @@ export interface RegisteredDataMigration {
|
|
|
818
818
|
* Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
|
|
819
819
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
820
820
|
*/
|
|
821
|
-
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${
|
|
822
|
-
`,i)},
|
|
821
|
+
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${N}};
|
|
822
|
+
`,i)},Kn=e=>{const t={};for(const n of e.tables){const r={};for(const[a,o]of Object.entries(n.shape)){const i=o.kind==="optional"&&o.inner?o.inner:o;i.kind==="id"&&i.tableName!==void 0&&(r[a]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},Qn=e=>{const t={};for(const n of e.tables){const r=[];for(const[a,o]of Object.entries(n.shape))(o.kind==="optional"&&o.inner?o.inner:o).kind==="storage"&&r.push(a);r.length>0&&(t[n.name]=r)}return t},Hn=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(a=>({fields:[...a.fields],name:a.name,type:"index",...a.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(a=>({fields:[a.field,...a.filterFields??[]],name:a.name,type:"search"})),...(n.geoIndexes??[]).map(a=>({fields:[a.field],name:a.name,type:"geo"})),...n.rankIndexes.map(a=>({fields:a.sortBy.map(o=>o.field),name:a.name,type:"rank"})),...n.vectorIndexes.map(a=>({fields:a.field===void 0?[]:[a.field],name:a.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},Jn=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},Vn=e=>{const t={};for(const n of e.tables){const r=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"}];for(const[a,o]of Object.entries(n.shape)){const i=o.kind==="optional"||!!o.column?.hasDefault,s=o.kind==="optional"&&o.inner?o.inner:o,l={name:a,optional:i,type:s.kind};s.kind==="id"&&s.tableName!==void 0&&(l.ref=s.tableName),s.kind==="storage"&&(l.isStorage=!0),r.push(l)}t[n.name]=r}return t},Gn=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
823
823
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
824
824
|
this.ensureMigrated();
|
|
825
825
|
|
|
@@ -827,7 +827,7 @@ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${R}}
|
|
|
827
827
|
|
|
828
828
|
return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
|
|
829
829
|
}
|
|
830
|
-
`}:{importFragment:"",override:""},
|
|
830
|
+
`}:{importFragment:"",override:""},zn=e=>{if(!e)return{build:"",configField:"",contextField:"",stub:""};const t='throw new Error("ctx.ai: no AI binding found. Add an \\`ai\\` binding (env.AI) to wrangler.jsonc, or pass \\`ai\\` to createShardDO().");';return{build:`
|
|
831
831
|
const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
|
|
832
832
|
// Correlate AI-Gateway-routed calls with the Lunora trace: thread the
|
|
833
833
|
// function path + trace id into createAi, which folds them into the
|
|
@@ -858,7 +858,7 @@ const aiStub: LunoraAi = {
|
|
|
858
858
|
${t}
|
|
859
859
|
}) as unknown as LunoraAi["workersai"],
|
|
860
860
|
};
|
|
861
|
-
`}},_={build:"",configField:"",contextField:"",importLines:[],stub:""},
|
|
861
|
+
`}},_={build:"",configField:"",contextField:"",importLines:[],stub:""},Xn=e=>{if(!e)return _;const t='throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");';return{build:`
|
|
862
862
|
const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
|
|
863
863
|
const kv: Kv = kvBinding ? createKv({ namespace: kvBinding as KVNamespaceLike }) : kvStub;
|
|
864
864
|
`,configField:`
|
|
@@ -884,7 +884,7 @@ const kvStub: Kv = {
|
|
|
884
884
|
${t}
|
|
885
885
|
},
|
|
886
886
|
};
|
|
887
|
-
`}},
|
|
887
|
+
`}},Yn=(e,t)=>e?{build:`
|
|
888
888
|
const flags: import("${t}").LunoraFlags = createFlags({
|
|
889
889
|
hooks: flagsConfig.hooks,
|
|
890
890
|
logger: flagsConfig.logger,
|
|
@@ -893,17 +893,17 @@ const kvStub: Kv = {
|
|
|
893
893
|
});
|
|
894
894
|
`,configField:`
|
|
895
895
|
flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
|
|
896
|
-
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:_,
|
|
896
|
+
flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:_,Zn=e=>e?{build:`
|
|
897
897
|
const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
|
|
898
898
|
`,configField:"",contextField:`
|
|
899
899
|
notify,
|
|
900
|
-
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:_,
|
|
900
|
+
push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:_,er=e=>e?{build:`
|
|
901
901
|
const envConfig = lunoraEnvContract.${e.exportName}(env);
|
|
902
902
|
`,configField:"",contextField:`
|
|
903
|
-
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:_,
|
|
903
|
+
env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:_,tr=e=>e?{build:`
|
|
904
904
|
const access = accessFacade(identity, userId);
|
|
905
905
|
`,configField:"",contextField:`
|
|
906
|
-
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:_,
|
|
906
|
+
access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:_,nr=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
|
|
907
907
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
908
908
|
const flags: import("${n}").LunoraFlags = createFlags({
|
|
909
909
|
hooks: flagsConfig.hooks,
|
|
@@ -967,7 +967,7 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
967
967
|
|
|
968
968
|
return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
|
|
969
969
|
}
|
|
970
|
-
`;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},
|
|
970
|
+
`;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},rr=e=>{if(!e)return _;const t='throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");';return{build:`
|
|
971
971
|
const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
|
|
972
972
|
const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
|
|
973
973
|
`,configField:`
|
|
@@ -981,7 +981,7 @@ const analyticsStub: AnalyticsClient = {
|
|
|
981
981
|
${t}
|
|
982
982
|
},
|
|
983
983
|
};
|
|
984
|
-
`}},
|
|
984
|
+
`}},ar=e=>{if(!e)return _;const t='throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");';return{build:`
|
|
985
985
|
const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
|
|
986
986
|
const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
|
|
987
987
|
`,configField:`
|
|
@@ -995,7 +995,7 @@ const imagesStub: Images = {
|
|
|
995
995
|
${t}
|
|
996
996
|
},
|
|
997
997
|
};
|
|
998
|
-
`}},
|
|
998
|
+
`}},or=e=>e?{build:`
|
|
999
999
|
const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
|
|
1000
1000
|
`,configField:`
|
|
1001
1001
|
sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
|
|
@@ -1005,7 +1005,7 @@ const sqlStub: SqlClient = {
|
|
|
1005
1005
|
throw new Error("ctx.sql: provide a \\\`sql\\\` config thunk that builds a SqlClient from your driver, e.g. \\\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\\`.");
|
|
1006
1006
|
},
|
|
1007
1007
|
};
|
|
1008
|
-
`}:_,
|
|
1008
|
+
`}:_,sr=e=>{if(!e)return _;const t="throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");";return{build:`
|
|
1009
1009
|
const browser: Browser = config.browser ? config.browser(env) : browserStub;
|
|
1010
1010
|
`,configField:`
|
|
1011
1011
|
browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
|
|
@@ -1033,7 +1033,7 @@ const browserStub: Browser = {
|
|
|
1033
1033
|
${t}
|
|
1034
1034
|
},
|
|
1035
1035
|
};
|
|
1036
|
-
`}},
|
|
1036
|
+
`}},ir=e=>{if(!e)return _;const t='throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");';return{build:`
|
|
1037
1037
|
const r2sqlEnv = env as Record<string, unknown>;
|
|
1038
1038
|
const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
|
|
1039
1039
|
const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
|
|
@@ -1065,7 +1065,7 @@ const r2sqlStub: R2SqlClient = {
|
|
|
1065
1065
|
${t}
|
|
1066
1066
|
},
|
|
1067
1067
|
};
|
|
1068
|
-
`}},
|
|
1068
|
+
`}},lr=e=>e?{build:`
|
|
1069
1069
|
const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
|
|
1070
1070
|
const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
|
|
1071
1071
|
`,configField:`
|
|
@@ -1075,14 +1075,14 @@ const pipelinesStub: PipelineClient = {
|
|
|
1075
1075
|
throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\\`pipelines\\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\\`pipelines\\\` to createShardDO().");
|
|
1076
1076
|
},
|
|
1077
1077
|
};
|
|
1078
|
-
`}:_,
|
|
1078
|
+
`}:_,_r=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(o=>(m(o.exportName,`container export "${o.exportName}"`),m(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
|
|
1079
1079
|
export class ${o.className} extends LunoraContainer {
|
|
1080
1080
|
public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
|
|
1081
1081
|
super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
|
|
1082
1082
|
}
|
|
1083
1083
|
}
|
|
1084
1084
|
`)).join(`
|
|
1085
|
-
`),a=e.map(o=>o.exportName).join(", ");return`${
|
|
1085
|
+
`),a=e.map(o=>o.exportName).join(", ");return`${v}/**
|
|
1086
1086
|
* Container-enabled Durable Object classes for the containers declared in
|
|
1087
1087
|
* \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
|
|
1088
1088
|
* requires each \`containers[].class_name\` to be exported by the worker:
|
|
@@ -1100,7 +1100,7 @@ import { ${a} } from "../containers.js";
|
|
|
1100
1100
|
|
|
1101
1101
|
export { ContainerProxy } from "@lunora/container/do";
|
|
1102
1102
|
|
|
1103
|
-
${r}`},
|
|
1103
|
+
${r}`},dr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)m(r.exportName,`container export "${r.exportName}"`),m(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const a=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${a} },`}).join(`
|
|
1104
1104
|
`);return{build:`
|
|
1105
1105
|
const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
|
|
1106
1106
|
`,contextField:`
|
|
@@ -1109,14 +1109,14 @@ ${r}`},nr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1109
1109
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1110
1110
|
${n}
|
|
1111
1111
|
];
|
|
1112
|
-
`}},
|
|
1112
|
+
`}},Er=e=>{if(e.length===0)return"";const t=e.map(r=>(m(r.exportName,`workflow export "${r.exportName}"`),m(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
|
|
1113
1113
|
export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
|
|
1114
1114
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1115
1115
|
super(ctx, env, ${r.exportName}, "${r.exportName}");
|
|
1116
1116
|
}
|
|
1117
1117
|
}
|
|
1118
1118
|
`)).join(`
|
|
1119
|
-
`),n=e.map(r=>r.exportName).join(", ");return`${
|
|
1119
|
+
`),n=e.map(r=>r.exportName).join(", ");return`${v}/**
|
|
1120
1120
|
* WorkflowEntrypoint classes for the workflows declared in
|
|
1121
1121
|
* \`lunora/workflows.ts\`. Re-export them from your worker entry — wrangler
|
|
1122
1122
|
* requires each \`workflows[].class_name\` to be exported by the worker:
|
|
@@ -1137,7 +1137,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
1137
1137
|
/** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
|
|
1138
1138
|
type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
|
|
1139
1139
|
|
|
1140
|
-
${t}`},
|
|
1140
|
+
${t}`},Pr=e=>{if(e.length===0)return"";const t=e.filter(a=>a.voice).length>0,n=e.map(a=>{m(a.exportName,`agent export "${a.exportName}"`),m(a.className,`agent class "${a.className}"`);const o=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent (binding \`${a.bindingName}\`). */
|
|
1141
1141
|
export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
1142
1142
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1143
1143
|
super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
|
|
@@ -1151,7 +1151,7 @@ export class ${i} extends VoiceSessionDO {
|
|
|
1151
1151
|
}
|
|
1152
1152
|
}
|
|
1153
1153
|
`;return`${o}${l}`}).join(`
|
|
1154
|
-
`),r=e.map(a=>a.exportName).join(", ");return`${
|
|
1154
|
+
`),r=e.map(a=>a.exportName).join(", ");return`${v}/**
|
|
1155
1155
|
* WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
|
|
1156
1156
|
* Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
|
|
1157
1157
|
* Workflow. Re-export them from your worker entry — wrangler requires each
|
|
@@ -1165,8 +1165,8 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
|
|
|
1165
1165
|
|
|
1166
1166
|
import { ${r} } from "../agents.js";
|
|
1167
1167
|
|
|
1168
|
-
${n}`},
|
|
1169
|
-
`);return`${
|
|
1168
|
+
${n}`},Fr=e=>{const t=e.filter(a=>a.mode==="push");if(t.length===0)return"";for(const a of t)m(a.exportName,`queue export "${a.exportName}"`);const n=t.map(a=>a.exportName).join(", "),r=t.map(a=>` ${JSON.stringify(a.name)}: { definition: ${a.exportName}, exportName: ${JSON.stringify(a.exportName)} },`).join(`
|
|
1169
|
+
`);return`${v}/**
|
|
1170
1170
|
* Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
|
|
1171
1171
|
* composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
|
|
1172
1172
|
* by \`batch.queue\` to the matching \`defineQueue\` handler. Wired automatically
|
|
@@ -1180,7 +1180,7 @@ import { ${n} } from "../queues.js";
|
|
|
1180
1180
|
export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
|
|
1181
1181
|
${r}
|
|
1182
1182
|
};
|
|
1183
|
-
`},
|
|
1183
|
+
`},cr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`workflow export "${n.exportName}"`),m(n.bindingName,`workflow binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}" },`).join(`
|
|
1184
1184
|
`);return{build:`
|
|
1185
1185
|
const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS);
|
|
1186
1186
|
`,contextField:`
|
|
@@ -1189,7 +1189,7 @@ ${r}
|
|
|
1189
1189
|
const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
|
|
1190
1190
|
${t}
|
|
1191
1191
|
];
|
|
1192
|
-
`}},
|
|
1192
|
+
`}},ur=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`queue export "${n.exportName}"`),m(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
|
|
1193
1193
|
`);return{build:`
|
|
1194
1194
|
const queues = createQueueContext(env, LUNORA_QUEUES);
|
|
1195
1195
|
`,contextField:`
|
|
@@ -1198,7 +1198,7 @@ ${t}
|
|
|
1198
1198
|
const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
|
|
1199
1199
|
${t}
|
|
1200
1200
|
];
|
|
1201
|
-
`}},
|
|
1201
|
+
`}},pr=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)m(n.exportName,`agent export "${n.exportName}"`),m(n.bindingName,`agent binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
|
|
1202
1202
|
`);return{build:`
|
|
1203
1203
|
const agents = createAgentContext(env, LUNORA_AGENTS);
|
|
1204
1204
|
`,contextField:`
|
|
@@ -1207,21 +1207,21 @@ ${t}
|
|
|
1207
1207
|
const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
|
|
1208
1208
|
${t}
|
|
1209
1209
|
];
|
|
1210
|
-
`}},
|
|
1210
|
+
`}},hr=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return{constant:`
|
|
1211
1211
|
/** Read-only declared-workflow metadata (discovered from \`lunora/workflows.ts\`) served via \`__lunora_admin__:listWorkflows\` for the studio's workflows view. */
|
|
1212
1212
|
const LUNORA_WORKFLOWS_INFO: WorkflowsResult = ${JSON.stringify(t,void 0,4)};
|
|
1213
1213
|
`,override:`
|
|
1214
1214
|
protected override workflowsMetadata(): WorkflowsResult {
|
|
1215
1215
|
return LUNORA_WORKFLOWS_INFO;
|
|
1216
1216
|
}
|
|
1217
|
-
`}},
|
|
1217
|
+
`}},gr=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return{constant:`
|
|
1218
1218
|
/** Read-only declared-queue metadata (discovered from \`lunora/queues.ts\`) served via \`__lunora_admin__:listQueues\` for the studio's queues view. */
|
|
1219
1219
|
const LUNORA_QUEUES_INFO: QueuesResult = ${JSON.stringify(t,void 0,4)};
|
|
1220
1220
|
`,override:`
|
|
1221
1221
|
protected override queuesMetadata(): QueuesResult {
|
|
1222
1222
|
return LUNORA_QUEUES_INFO;
|
|
1223
1223
|
}
|
|
1224
|
-
`}},
|
|
1224
|
+
`}},mr=e=>{if(!e)return{build:"",configField:"",contextField:"",imports:[],stub:""};const t='throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");';return{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
|
|
1225
1225
|
const payments: LunoraPayment = config.payment
|
|
1226
1226
|
? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
|
|
1227
1227
|
: paymentStub;
|
|
@@ -1257,7 +1257,7 @@ const paymentStub: LunoraPayment = {
|
|
|
1257
1257
|
${t}
|
|
1258
1258
|
},
|
|
1259
1259
|
} as unknown as LunoraPayment;
|
|
1260
|
-
`}},
|
|
1260
|
+
`}},fr=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
|
|
1261
1261
|
const x402: X402Pay = config.x402
|
|
1262
1262
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1263
1263
|
: x402Stub;
|
|
@@ -1269,10 +1269,10 @@ const x402Stub: X402Pay = {
|
|
|
1269
1269
|
throw new Error("ctx.x402: no pay rail configured. Pass \\\`x402\\\` to createShardDO().");
|
|
1270
1270
|
},
|
|
1271
1271
|
} as unknown as X402Pay;
|
|
1272
|
-
`}:{build:"",configField:"",contextField:"",imports:[],stub:""},
|
|
1272
|
+
`}:{build:"",configField:"",contextField:"",imports:[],stub:""},br=(e,t,n,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],Mr=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:l=!1,hasBrowser:u=!1,hasFlags:p=!1,hasHyperdrive:f=!1,hasImages:y=!1,hasKv:N=!1,hasNotify:d=!1,hasPayments:c=!1,hasPipelines:g=!1,hasR2sql:b=!1,hasX402:k=!1,maskMetadata:$,mutators:T=[],queues:O=[],rlsMetadata:S,schema:x,schemaSnapshot:P,shapes:ee=[],storageRules:F,studioFeatures:te,useUmbrella:ne=!1,workflows:B=[]})=>{const A=G(ne),z=T.length>0,L=ee.length>0,I=P===void 0?"":on(P),M=P===void 0?"":`
|
|
1273
1273
|
/** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
|
|
1274
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1275
|
-
`,re=
|
|
1274
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(sn(P))}, json: ${JSON.stringify(I)} };
|
|
1275
|
+
`,re=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:ae,configField:ke,contextField:ve,stub:$e}=zn(s),oe=tr(i),K=Xn(N),E=Yn(p,A.flags),Q=nr(o,p,A.flags),X=Zn(d),se=er(a),H=rr(l),j=ar(y),W=or(f),U=sr(u),q=ir(b),Y=lr(g),{build:Se,contextField:fe,importLines:be,specs:ie}=ur(O),{build:Re,contextField:Ne,importLines:ye,specs:le}=dr(r,x.jurisdiction),{build:Oe,contextField:Te,importLines:we,specs:Ae}=cr(B),{build:Le,contextField:de,importLines:ce,specs:Ce}=pr(n),{build:Ie,configField:De,contextField:ue,imports:pe,stub:h}=mr(c),{build:_e,configField:ht,imports:gt,stub:mt}=fr(k),ft=e,bt=t,yt=S??{policies:[],roles:[]},wt=$??{columns:[]},xt=F??{rules:[]},kt=te??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:vt,override:$t}=hr(B),{constant:St,override:Rt}=gr(O),J=x.vectorIndexes.length>0,Ue=new Set(x.tables.filter(w=>typeof w.shardMode=="object"&&w.shardMode.kind==="shardBy").map(w=>w.name)),xe=x.vectorIndexes.some(w=>Ue.has(w.table)),he=x.tables.some(w=>w.shardMode==="global"),Ee=x.tables.some(w=>w.shardMode==="global"&&w.globalBackend==="hyperdrive"),Ke=x.tables.some(w=>w.shardMode==="global"&&w.globalBackend!=="hyperdrive"),V=x.tables.some(w=>w.externalSource!==void 0);if(Ke&&Ee)throw new Z("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Pe=x.tables.length>0,Nt=Kn(x),Ot=Hn(x),Tt=Vn(x),At=Qn(x),Qe=Jn(x),He=br(J,B.length>0,O.length>0,p);L&&He.push("WhereInput");const Je=Gn(he),Lt=L?`
|
|
1276
1276
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
1277
1277
|
const shape = LUNORA_SHAPES[name];
|
|
1278
1278
|
|
|
@@ -1325,15 +1325,15 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1325
1325
|
|
|
1326
1326
|
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
1327
1327
|
}
|
|
1328
|
-
`:"",
|
|
1328
|
+
`:"",Ct=z?`
|
|
1329
1329
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1330
1330
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1331
1331
|
}
|
|
1332
|
-
`:"",
|
|
1333
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
1334
|
-
d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1335
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1336
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
1332
|
+
`:"",It=L?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Dt=L?"assertShapeShardable, ":"",ge=[`import type { ${He.join(", ")} } from "${A.do}";`,`import { applyCdcChanges, ${Dt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${V?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${xe?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Je.importFragment}ShardDO as ShardDOBase } from "${A.do}";`,...V?[`import type { ExternalSourceLike, SourceClientLike } from "${A.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${A.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${A.server}";`];Pe&&ge.push(`import { bindOrm, bindTableFacade } from "${A.server}";`),J&&ge.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&ge.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ge.push(...oe.importLines,...K.importLines,...E.importLines,...X.importLines,...se.importLines,...H.importLines,...j.importLines,...W.importLines,...U.importLines,...q.importLines,...Y.importLines,...ye,...we,...be,...ce,...pe,...gt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...z?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const _t=J?`
|
|
1333
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Et=Ke?`
|
|
1334
|
+
d1?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Pt=Ee?`
|
|
1335
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ft=V?`
|
|
1336
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Mt=he?'\nconst globalDbStub: DatabaseWriterLike = {\n aggregate: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n count: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n delete: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findFirst: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findFirstOrThrow: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n findMany: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n get: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n groupBy: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n insert: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n normalizeId: () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n patch: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n query: () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n rank: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n rankPage: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n replace: async () => {\n throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");\n },\n};\n':"",qt=J?`
|
|
1337
1337
|
const vectorsStub: VectorSearchLike = {
|
|
1338
1338
|
deleteByIds: async () => {
|
|
1339
1339
|
throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
|
|
@@ -1351,22 +1351,24 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1351
1351
|
throw new Error("ctx.vectors: no vectors configured. Pass \`vectors\` to createShardDO().");
|
|
1352
1352
|
},
|
|
1353
1353
|
};
|
|
1354
|
-
`:"",
|
|
1354
|
+
`:"",Bt=xe?`
|
|
1355
|
+
const vectorShardKey = this.currentShardKey();
|
|
1356
|
+
`:"",jt=xe?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",Wt=xe?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${x.vectorIndexes.filter(w=>Ue.has(w.table)).map(w=>JSON.stringify(w.name)).join(", ")}] }`:"",Ut=J?`
|
|
1355
1357
|
let vectors: VectorSearchLike;
|
|
1356
1358
|
let onWrite: WriteHook | undefined;
|
|
1357
1359
|
|
|
1358
1360
|
if (config.vectors) {
|
|
1359
1361
|
const lunora = createVectors({ indexes: config.vectors(env) });
|
|
1360
|
-
|
|
1361
|
-
vectors = createContextVectors(lunora);
|
|
1362
|
-
onWrite = createVectorSyncHook({ schema: schema as unknown as VectorSchemaLike, vectors });
|
|
1362
|
+
${Bt}
|
|
1363
|
+
vectors = createContextVectors(lunora${Wt});
|
|
1364
|
+
onWrite = createVectorSyncHook({ ${jt}schema: schema as unknown as VectorSchemaLike, vectors });
|
|
1363
1365
|
} else {
|
|
1364
1366
|
vectors = vectorsStub;
|
|
1365
1367
|
onWrite = undefined;
|
|
1366
1368
|
}
|
|
1367
|
-
`:"",
|
|
1368
|
-
globalDb,`:"",
|
|
1369
|
-
auth: { identity: identity ?? null, userId: userId ?? null },`,
|
|
1369
|
+
`:"",Ve=he?`
|
|
1370
|
+
globalDb,`:"",Ge=`
|
|
1371
|
+
auth: { identity: identity ?? null, userId: userId ?? null },`,Kt=J?`{${Ge}
|
|
1370
1372
|
broadcast: (delta) => {
|
|
1371
1373
|
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
1372
1374
|
},
|
|
@@ -1380,8 +1382,8 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1380
1382
|
scheduler,
|
|
1381
1383
|
schema: schema as unknown as SchemaLike,
|
|
1382
1384
|
sql: this.sql as SqlExec,
|
|
1383
|
-
storage,${
|
|
1384
|
-
}`:`{${
|
|
1385
|
+
storage,${Ve}
|
|
1386
|
+
}`:`{${Ge}
|
|
1385
1387
|
broadcast: (delta) => {
|
|
1386
1388
|
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
1387
1389
|
},
|
|
@@ -1394,14 +1396,14 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1394
1396
|
scheduler,
|
|
1395
1397
|
schema: schema as unknown as SchemaLike,
|
|
1396
1398
|
sql: this.sql as SqlExec,
|
|
1397
|
-
storage,${
|
|
1398
|
-
}`,
|
|
1399
|
-
vectors,`:"",
|
|
1400
|
-
orm: bindOrm(facade),`:"",
|
|
1401
|
-
`:"",
|
|
1399
|
+
storage,${Ve}
|
|
1400
|
+
}`,Qt=J?`
|
|
1401
|
+
vectors,`:"",Ht=Pe?`
|
|
1402
|
+
orm: bindOrm(facade),`:"",Jt="",ze=Ee?"config.hyperdriveGlobal":"config.d1",Vt=he?` const globalDb: DatabaseWriterLike = ${ze}?.(env, { identity, userId }) ?? globalDbStub;
|
|
1403
|
+
`:"",Gt=L&&he?`
|
|
1402
1404
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1403
1405
|
const env = this.env as Record<string, unknown>;
|
|
1404
|
-
const globalDb: DatabaseWriterLike = ${
|
|
1406
|
+
const globalDb: DatabaseWriterLike = ${ze}?.(env, identity) ?? globalDbStub;
|
|
1405
1407
|
const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
|
|
1406
1408
|
|
|
1407
1409
|
let cursor: null | string = null;
|
|
@@ -1428,10 +1430,10 @@ const vectorsStub: VectorSearchLike = {
|
|
|
1428
1430
|
|
|
1429
1431
|
return rows;
|
|
1430
1432
|
}
|
|
1431
|
-
`:"",
|
|
1433
|
+
`:"",zt=V?`
|
|
1432
1434
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1433
1435
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1434
|
-
`:"",
|
|
1436
|
+
`:"",Xt=V?`
|
|
1435
1437
|
protected override async pollExternalSources(): Promise<number | undefined> {
|
|
1436
1438
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1437
1439
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1444,15 +1446,6 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1444
1446
|
|
|
1445
1447
|
const shardKey = this.currentShardKey();
|
|
1446
1448
|
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
1447
|
-
const writer = createShardCtxDb({
|
|
1448
|
-
broadcast: (delta) => {
|
|
1449
|
-
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
1450
|
-
},
|
|
1451
|
-
cdc: config.cdc ?? false,
|
|
1452
|
-
scheduler,
|
|
1453
|
-
schema: schema as unknown as SchemaLike,
|
|
1454
|
-
sql: this.sql as SqlExec,
|
|
1455
|
-
});
|
|
1456
1449
|
|
|
1457
1450
|
let clients = sourceClientCache.get(this);
|
|
1458
1451
|
|
|
@@ -1499,14 +1492,31 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1499
1492
|
// Logs panel and stamp \`polledAt\` so a persistent misconfig backs
|
|
1500
1493
|
// off to \`refresh.everyMs\` instead of retrying every alarm tick.
|
|
1501
1494
|
this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`));
|
|
1502
|
-
} else if (source.mode === "incremental") {
|
|
1503
|
-
// Incremental (plan 136): pull only rows past the durable
|
|
1504
|
-
// watermark (or a full-pull seed/reconcile), upsert-only.
|
|
1505
|
-
// eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
|
|
1506
|
-
await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
|
|
1507
1495
|
} else {
|
|
1508
|
-
//
|
|
1509
|
-
|
|
1496
|
+
// A FRESH tracker per TABLE, not one shared across the whole
|
|
1497
|
+
// loop: one table's runaway pull must not spend a budget a
|
|
1498
|
+
// sibling table needs, and a limit hit here must not block
|
|
1499
|
+
// that sibling from getting its own full budget this tick.
|
|
1500
|
+
const writer = createShardCtxDb({
|
|
1501
|
+
broadcast: (delta) => {
|
|
1502
|
+
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
1503
|
+
},
|
|
1504
|
+
cdc: config.cdc ?? false,
|
|
1505
|
+
headroom: this.alarmHeadroom(),
|
|
1506
|
+
scheduler,
|
|
1507
|
+
schema: schema as unknown as SchemaLike,
|
|
1508
|
+
sql: this.sql as SqlExec,
|
|
1509
|
+
});
|
|
1510
|
+
|
|
1511
|
+
if (source.mode === "incremental") {
|
|
1512
|
+
// Incremental (plan 136): pull only rows past the durable
|
|
1513
|
+
// watermark (or a full-pull seed/reconcile), upsert-only.
|
|
1514
|
+
// eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
|
|
1515
|
+
await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
|
|
1516
|
+
} else {
|
|
1517
|
+
// eslint-disable-next-line no-await-in-loop -- one sourced table at a time; slices are independent but small and sequential keeps the writer transaction simple
|
|
1518
|
+
await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
|
|
1519
|
+
}
|
|
1510
1520
|
}
|
|
1511
1521
|
|
|
1512
1522
|
// Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
|
|
@@ -1514,6 +1524,33 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1514
1524
|
// stale-immediate and re-arm the alarm in a hammering loop.
|
|
1515
1525
|
polledAt.set(table, Date.now());
|
|
1516
1526
|
} catch (error) {
|
|
1527
|
+
if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
|
|
1528
|
+
// Batch full, not a genuine failure. Incremental mode only
|
|
1529
|
+
// persists its watermark AFTER a full apply (see
|
|
1530
|
+
// \`pullExternalSourceIncrementalTick\`), so this throw left it
|
|
1531
|
+
// untouched — the next tick safely re-pulls/re-applies the
|
|
1532
|
+
// SAME slice (idempotent upsert). Full-pull mode (and an
|
|
1533
|
+
// incremental source's own occasional full-pull/reconcile
|
|
1534
|
+
// sweep) has no resumable cursor at all — deliberately not
|
|
1535
|
+
// inventing one here; a retry just redoes the whole pull,
|
|
1536
|
+
// safe if wasteful. Either way: warn instead of
|
|
1537
|
+
// \`recordExternalSourceError\`, and leave \`polledAt\`
|
|
1538
|
+
// UNCHANGED (skip the stamp below via \`continue\`) so this
|
|
1539
|
+
// table stays "due" and \`nextPollAlarmTarget\`'s existing
|
|
1540
|
+
// due-now floor re-arms the shared alarm promptly — not a
|
|
1541
|
+
// fresh \`setAlarm(now)\`.
|
|
1542
|
+
this.logs.push({
|
|
1543
|
+
functionPath: \`source:\${table}\`,
|
|
1544
|
+
level: "warn",
|
|
1545
|
+
message: \`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
|
|
1546
|
+
timestamp: Date.now(),
|
|
1547
|
+
});
|
|
1548
|
+
|
|
1549
|
+
nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
|
|
1550
|
+
|
|
1551
|
+
continue;
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1517
1554
|
this.recordExternalSourceError(table, error);
|
|
1518
1555
|
// Stamp on failure too, so a persistently failing source throttles
|
|
1519
1556
|
// to \`refresh.everyMs\` rather than being hammered every tick.
|
|
@@ -1532,10 +1569,10 @@ const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
|
1532
1569
|
|
|
1533
1570
|
return nextDueAt;
|
|
1534
1571
|
}
|
|
1535
|
-
`:"",
|
|
1572
|
+
`:"",Xe=Qe.length>0,Yt=V||Xe?`
|
|
1536
1573
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1537
1574
|
super(state, env);
|
|
1538
|
-
${
|
|
1575
|
+
${V?`
|
|
1539
1576
|
const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
|
|
1540
1577
|
const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
|
|
1541
1578
|
|
|
@@ -1545,27 +1582,27 @@ ${G?`
|
|
|
1545
1582
|
if (autoSourced) {
|
|
1546
1583
|
void this.scheduleSourcePoll();
|
|
1547
1584
|
}
|
|
1548
|
-
`:""}${
|
|
1585
|
+
`:""}${Xe?`
|
|
1549
1586
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1550
1587
|
void this.scheduleTtlSweep();
|
|
1551
1588
|
}
|
|
1552
1589
|
`:""} }
|
|
1553
|
-
`:"",
|
|
1590
|
+
`:"",Zt=Pe?`
|
|
1554
1591
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1555
|
-
${
|
|
1592
|
+
${x.tables.map(w=>` facade[${JSON.stringify(w.name)}] = bindTableFacade(db, ${JSON.stringify(w.name)});`).join(`
|
|
1556
1593
|
`)}
|
|
1557
|
-
`:"",
|
|
1594
|
+
`:"",en=`${oe.build}${K.build}${E.build}${H.build}${se.build}
|
|
1558
1595
|
const secrets = createSecrets(env);
|
|
1559
|
-
`,
|
|
1560
|
-
secrets,`,
|
|
1596
|
+
`,tn=`${oe.contextField}${K.contextField}${E.contextField}${X.contextField}${H.contextField}${se.contextField}
|
|
1597
|
+
secrets,`,nn=X.build,Ye=y||f||u||b||g||k,rn=Ye?`
|
|
1561
1598
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
1562
1599
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
1563
1600
|
if (isAction) {
|
|
1564
|
-
${j.build}${W.build}${U.build}${q.build}${Y.build}${
|
|
1601
|
+
${j.build}${W.build}${U.build}${q.build}${Y.build}${_e}${[...y?[" ctx.images = images;"]:[],...f?[" ctx.sql = sql;"]:[],...u?[" ctx.browser = browser;"]:[],...b?[" ctx.r2sql = r2sql;"]:[],...g?[" ctx.pipelines = pipelines;"]:[],...k?[" ctx.x402 = x402;"]:[]].join(`
|
|
1565
1602
|
`)}
|
|
1566
1603
|
}
|
|
1567
|
-
`:"",
|
|
1568
|
-
`:"";return`${
|
|
1604
|
+
`:"",an=Ye?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
|
|
1605
|
+
`:"";return`${v}${ge.join(`
|
|
1569
1606
|
`)}
|
|
1570
1607
|
|
|
1571
1608
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1575,45 +1612,45 @@ interface FunctionReference {
|
|
|
1575
1612
|
}
|
|
1576
1613
|
|
|
1577
1614
|
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1578
|
-
const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(
|
|
1615
|
+
const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(Nt,void 0,4)};
|
|
1579
1616
|
|
|
1580
1617
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1581
|
-
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(
|
|
1618
|
+
const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(Ot,void 0,4)};
|
|
1582
1619
|
|
|
1583
1620
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1584
|
-
const LUNORA_TABLE_COLUMNS: Record<string, Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }>> = ${JSON.stringify(
|
|
1621
|
+
const LUNORA_TABLE_COLUMNS: Record<string, Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }>> = ${JSON.stringify(Tt,void 0,4)};
|
|
1585
1622
|
|
|
1586
1623
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1587
|
-
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(
|
|
1624
|
+
const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(At,void 0,4)};
|
|
1588
1625
|
|
|
1589
1626
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1590
|
-
const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(
|
|
1627
|
+
const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(Qe,void 0,4)};
|
|
1591
1628
|
|
|
1592
1629
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1593
|
-
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(
|
|
1630
|
+
const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(ft,void 0,4)};
|
|
1594
1631
|
|
|
1595
1632
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1596
|
-
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(
|
|
1633
|
+
const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(bt,void 0,4)};
|
|
1597
1634
|
|
|
1598
1635
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1599
|
-
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(
|
|
1636
|
+
const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(yt,void 0,4)};
|
|
1600
1637
|
|
|
1601
1638
|
/** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
|
|
1602
|
-
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(
|
|
1639
|
+
const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(wt,void 0,4)};
|
|
1603
1640
|
|
|
1604
1641
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1605
|
-
const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(
|
|
1642
|
+
const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(xt,void 0,4)};
|
|
1606
1643
|
|
|
1607
1644
|
/** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
|
|
1608
|
-
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(
|
|
1609
|
-
${M}${Q.constant}${
|
|
1645
|
+
const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(kt,void 0,4)};
|
|
1646
|
+
${M}${Q.constant}${It}${vt}${St}${le}${Ae}${ie}${Ce}
|
|
1610
1647
|
export interface ShardDOConfig {
|
|
1611
1648
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1612
1649
|
cdc?: boolean;
|
|
1613
1650
|
/** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
|
|
1614
1651
|
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1615
1652
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1616
|
-
storage?: (env: Record<string, unknown>) => unknown;${
|
|
1653
|
+
storage?: (env: Record<string, unknown>) => unknown;${_t}${ke}${K.configField}${E.configField}${H.configField}${j.configField}${W.configField}${U.configField}${q.configField}${Y.configField}${De}${ht}${Et}${Pt}${Ft}
|
|
1617
1654
|
}
|
|
1618
1655
|
|
|
1619
1656
|
const schedulerStub = {
|
|
@@ -1651,7 +1688,7 @@ const storageStub = {
|
|
|
1651
1688
|
throw new Error("ctx.storage: no storage configured. Pass \`storage\` to createShardDO().");
|
|
1652
1689
|
},
|
|
1653
1690
|
};
|
|
1654
|
-
${
|
|
1691
|
+
${Mt}${zt}${qt}${$e}${K.stub}${E.stub}${H.stub}${j.stub}${W.stub}${U.stub}${q.stub}${Y.stub}${h}${mt}${Jt}
|
|
1655
1692
|
// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
1656
1693
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
1657
1694
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
@@ -1688,10 +1725,10 @@ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: R
|
|
|
1688
1725
|
* from the worker entry so wrangler binds it by name.
|
|
1689
1726
|
*/
|
|
1690
1727
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1691
|
-
class extends ShardDOBase {${
|
|
1728
|
+
class extends ShardDOBase {${Yt}
|
|
1692
1729
|
private migrated = false;
|
|
1693
1730
|
|
|
1694
|
-
public override async handleRpc(functionPath: string, args: Record<string, unknown
|
|
1731
|
+
public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker): Promise<unknown> {
|
|
1695
1732
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
1696
1733
|
|
|
1697
1734
|
// Internal functions are reachable server-side only: via \`ctx.run*\`
|
|
@@ -1704,7 +1741,13 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
|
|
|
1704
1741
|
|
|
1705
1742
|
this.ensureMigrated();
|
|
1706
1743
|
|
|
1707
|
-
|
|
1744
|
+
// \`headroom\`, when the caller supplied one, is threaded straight
|
|
1745
|
+
// through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
|
|
1746
|
+
// fallback (the racy shared-field read) entirely for THIS dispatch.
|
|
1747
|
+
// The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
|
|
1748
|
+
// \`handleRunAs\` don't mint their own and omit it, so they keep the
|
|
1749
|
+
// prior fallback behavior unchanged.
|
|
1750
|
+
const ctx = this.buildCtx({ functionPath, headroom });
|
|
1708
1751
|
|
|
1709
1752
|
// A mutation's writes must commit all-or-nothing: wrap its dispatch in
|
|
1710
1753
|
// the DO's BEGIN/COMMIT span so any throw (a validator, an RLS denial,
|
|
@@ -1731,7 +1774,7 @@ export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOSt
|
|
|
1731
1774
|
|
|
1732
1775
|
return registered.handler(ctx, args);
|
|
1733
1776
|
}
|
|
1734
|
-
${
|
|
1777
|
+
${Je.override}
|
|
1735
1778
|
protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
1736
1779
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
1737
1780
|
|
|
@@ -1766,7 +1809,7 @@ ${Qe.override}
|
|
|
1766
1809
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
|
|
1767
1810
|
};
|
|
1768
1811
|
}
|
|
1769
|
-
${
|
|
1812
|
+
${Ct}${Lt}${Gt}${Xt}
|
|
1770
1813
|
protected override lifecycleHookPaths(event: "connect" | "disconnect"): readonly string[] {
|
|
1771
1814
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1772
1815
|
}
|
|
@@ -1806,7 +1849,7 @@ ${At}${Tt}${Kt}${Jt}
|
|
|
1806
1849
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1807
1850
|
return LUNORA_STUDIO_FEATURES;
|
|
1808
1851
|
}
|
|
1809
|
-
${Q.evaluateOverride}${Q.subscriptionOverride}${
|
|
1852
|
+
${Q.evaluateOverride}${Q.subscriptionOverride}${$t}${Rt}
|
|
1810
1853
|
protected override advisories(): AdvisoryFinding[] {
|
|
1811
1854
|
return LUNORA_ADVISORIES;
|
|
1812
1855
|
}
|
|
@@ -1966,7 +2009,7 @@ ${Q.evaluateOverride}${Q.subscriptionOverride}${kt}${$t}
|
|
|
1966
2009
|
return importShardRows(writer, schema as unknown as SchemaLike, { rows: args.rows, startLine: args.startLine });
|
|
1967
2010
|
}
|
|
1968
2011
|
|
|
1969
|
-
protected override async deleteRowThroughWriter(table: string, id: string): Promise<void> {
|
|
2012
|
+
protected override async deleteRowThroughWriter(table: string, id: string, headroom?: TransactionHeadroomTracker): Promise<void> {
|
|
1970
2013
|
const definition = (schema as unknown as SchemaLike).tables[table];
|
|
1971
2014
|
|
|
1972
2015
|
if (!definition) {
|
|
@@ -1988,6 +2031,13 @@ ${Q.evaluateOverride}${Q.subscriptionOverride}${kt}${$t}
|
|
|
1988
2031
|
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
1989
2032
|
},
|
|
1990
2033
|
cdc: config.cdc ?? false,
|
|
2034
|
+
// \`runShardBulkDelete\` (a normal \`/rpc\` dispatch) calls this with no
|
|
2035
|
+
// explicit \`headroom\`, so it falls back to \`this.transactionHeadroom()\`
|
|
2036
|
+
// — the SAME per-dispatch meter every other write goes through, mirroring
|
|
2037
|
+
// \`buildCtx\`'s \`options.headroom ?? this.transactionHeadroom()\`. The TTL
|
|
2038
|
+
// sweep (an alarm work item, no dispatch in flight) passes its own
|
|
2039
|
+
// by-value tracker explicitly instead.
|
|
2040
|
+
headroom: headroom ?? this.transactionHeadroom(),
|
|
1991
2041
|
scheduler,
|
|
1992
2042
|
schema: schema as unknown as SchemaLike,
|
|
1993
2043
|
sql: this.sql as SqlExec,
|
|
@@ -2096,7 +2146,7 @@ ${Q.evaluateOverride}${Q.subscriptionOverride}${kt}${$t}
|
|
|
2096
2146
|
// dispatch path) fall back to the per-request fields as before.
|
|
2097
2147
|
const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
|
|
2098
2148
|
const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
|
|
2099
|
-
${
|
|
2149
|
+
${Ut}${ae}${en}${Re}${Oe}${Se}${Le}
|
|
2100
2150
|
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
2101
2151
|
// Build the storage adapter once and share it between \`ctx.storage\`
|
|
2102
2152
|
// and \`ctx.db.system._storage\` so both read the same R2 binding. The
|
|
@@ -2123,13 +2173,13 @@ ${Mt}${ae}${Ht}${Se}${Ne}${$e}${Ae}
|
|
|
2123
2173
|
// so both write to the same trace.
|
|
2124
2174
|
const span = this.makeDispatchSpan(traceAnchor, observability);
|
|
2125
2175
|
|
|
2126
|
-
${
|
|
2176
|
+
${Vt} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
|
|
2127
2177
|
// adds aggregate counters (call count, total time, per-operation
|
|
2128
2178
|
// breakdown) to the wide event rather than a span per call, so a
|
|
2129
2179
|
// handler making hundreds of queries stays readable. See
|
|
2130
2180
|
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
2131
|
-
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${
|
|
2132
|
-
${
|
|
2181
|
+
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${Kt}), logFunctionPath, traceAnchor, observability);
|
|
2182
|
+
${Zt}${Ie}
|
|
2133
2183
|
|
|
2134
2184
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
2135
2185
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -2137,7 +2187,7 @@ ${Gt}${Ce}
|
|
|
2137
2187
|
// writing mutation's trace from the shared per-request field.
|
|
2138
2188
|
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
|
|
2139
2189
|
const metrics = this.makeMetrics(logFunctionPath, observability);
|
|
2140
|
-
${
|
|
2190
|
+
${nn}
|
|
2141
2191
|
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
2142
2192
|
// captured ONCE so the whole handler body sees a single stable value.
|
|
2143
2193
|
// Query/mutation handlers must be deterministic (they may be re-run on
|
|
@@ -2160,13 +2210,13 @@ ${Xt}
|
|
|
2160
2210
|
ip: this.getCurrentIp(),
|
|
2161
2211
|
log,
|
|
2162
2212
|
metrics,
|
|
2163
|
-
now,${
|
|
2213
|
+
now,${Ht}
|
|
2164
2214
|
scheduler,
|
|
2165
2215
|
span,
|
|
2166
2216
|
storage,
|
|
2167
|
-
trace,${
|
|
2217
|
+
trace,${Qt}${ve}${tn}${ue}${Ne}${Te}${fe}${de}
|
|
2168
2218
|
};
|
|
2169
|
-
${
|
|
2219
|
+
${an}${rn}
|
|
2170
2220
|
ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
|
|
2171
2221
|
ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
|
|
2172
2222
|
ctx.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("query", reference.__lunoraRef, fnArgs, ctx);
|
|
@@ -2174,21 +2224,21 @@ ${Zt}${Yt}
|
|
|
2174
2224
|
return ctx;
|
|
2175
2225
|
}
|
|
2176
2226
|
};
|
|
2177
|
-
`},
|
|
2227
|
+
`},We=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:C(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?We(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},pt=(e,t)=>{const n=e.kind==="optional"&&e.inner?e.inner:e;return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},yr=(e,t,n)=>{m(e,"drizzle column name");const r=We(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const i=pt(t,n);return i!==void 0&&(o+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(o+=".notNull()"),o},wr=e=>{m(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(m(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},xr=(e,t)=>{m(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([a,o])=>` ${a}: ${yr(a,o,t)},`)].join(`
|
|
2178
2228
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2179
|
-
${e.indexes.map(a=>
|
|
2229
|
+
${e.indexes.map(a=>wr(a)).join(`
|
|
2180
2230
|
`)}
|
|
2181
2231
|
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
2182
2232
|
${n}
|
|
2183
|
-
}${r});`},
|
|
2184
|
-
`;const n=
|
|
2233
|
+
}${r});`},kr=e=>e.typeAnnotation?.includes('Id<"')??!1,vr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let a=!1,o=!1;for(const i of e){for(const s of Object.values(i.shape)){const l=We(s);n.add(l.builder),o=o||kr(l),a=a||pt(s,t)!==void 0}for(const s of i.indexes)r.add(s.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,s)=>i.localeCompare(s)),indexes:[...r].toSorted((i,s)=>i.localeCompare(s)),needsAnyColumn:a,needsId:o}},et=(e,t=!1)=>{if(e.length===0)return`${v}export {};
|
|
2234
|
+
`;const n=G(t),r=new Set(e.map(f=>f.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=vr(e,r),l=[...o,...a].toSorted((f,y)=>f.localeCompare(y)),u=e.map(f=>xr(f,r)).join(`
|
|
2185
2235
|
|
|
2186
2236
|
`),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
|
|
2187
2237
|
`:"",s?`import type { Id } from "./dataModel.js";
|
|
2188
|
-
`:""].join("");return`${
|
|
2238
|
+
`:""].join("");return`${v}import { ${l.join(", ")} } from "${n.serverDrizzle}";
|
|
2189
2239
|
${p}
|
|
2190
2240
|
${u}
|
|
2191
|
-
`},
|
|
2241
|
+
`},qr=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:et(n,t),shard:et(r,t)}},Br=e=>{const t=[],n=new Map;for(const s of e){const l=n.get(s.cron);l?l.push(s):(n.set(s.cron,[s]),t.push(s.cron))}const r=t.map(s=>` ${JSON.stringify(s)},`).join(`
|
|
2192
2242
|
`),a=r.length>0?`
|
|
2193
2243
|
${r}
|
|
2194
2244
|
`:"",o=[...n.entries()].map(([s,l])=>{const u=l.map(p=>{const f=p.workflow?`workflow: ${JSON.stringify(p.workflow.binding)}`:`functionPath: ${JSON.stringify(p.functionPath)}`;return` { name: ${JSON.stringify(p.name)}, ${f}, args: ${JSON.stringify(p.args)} },`}).join(`
|
|
@@ -2197,7 +2247,7 @@ ${u}
|
|
|
2197
2247
|
],`}).join(`
|
|
2198
2248
|
`),i=o.length>0?`
|
|
2199
2249
|
${o}
|
|
2200
|
-
`:"";return`${
|
|
2250
|
+
`:"";return`${v}/**
|
|
2201
2251
|
* One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
|
|
2202
2252
|
* the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
|
|
2203
2253
|
* shard; \`workflow\` is a \`WORKFLOW_*\` binding name whose durable workflow is
|
|
@@ -2222,10 +2272,10 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${a}];
|
|
|
2222
2272
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2223
2273
|
*/
|
|
2224
2274
|
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${i}};
|
|
2225
|
-
`},
|
|
2275
|
+
`},jr=e=>{const t=[...e].toSorted((r,a)=>r.name.localeCompare(a.name)).map(r=>{const a=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&a.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&a.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&a.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&a.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${a.join(", ")} },`}).join(`
|
|
2226
2276
|
`),n=t.length>0?`
|
|
2227
2277
|
${t}
|
|
2228
|
-
`:"";return`${
|
|
2278
|
+
`:"";return`${v}/**
|
|
2229
2279
|
* One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
|
|
2230
2280
|
* or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
|
|
2231
2281
|
* for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
|
|
@@ -2246,4 +2296,4 @@ export interface LunoraVectorIndex {
|
|
|
2246
2296
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2247
2297
|
*/
|
|
2248
2298
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2249
|
-
`},
|
|
2299
|
+
`},Wr=e=>{const t=new Set,n=[];for(const r of e)t.has(r.cron)||(t.add(r.cron),n.push(r.cron));return n};export{jr as $,Wr as A,Dr as B,Cr as C,Ar as I,Lr as O,Ir as P,v as R,Br as S,Nn as a,Mr as b,Qn as c,Tr as g,Pr as i,Fr as l,Or as n,_r as o,ln as r,Er as s,qr as v};
|