@lunora/codegen 1.0.0-alpha.319 → 1.0.0-alpha.320

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/index.d.mts +23 -2
  2. package/dist/index.d.ts +23 -2
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{NOTIFY_FILENAME-CjbDYC2a.mjs → NOTIFY_FILENAME-bAt7J3cs.mjs} +1 -1
  5. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bo67h-3B.mjs +11 -0
  6. package/dist/packem_shared/chain-Cm6BMT8g.mjs +1 -0
  7. package/dist/packem_shared/classify-procedure-call-DVxdUhZt.mjs +1 -0
  8. package/dist/packem_shared/{context-property-calls-Bw8u2Pz4.mjs → context-property-calls-Cn3upNgZ.mjs} +1 -1
  9. package/dist/packem_shared/{context-root-YkWLB6M2.mjs → context-root-BdxINX-T.mjs} +1 -1
  10. package/dist/packem_shared/{database-calls-BnVUlTx_.mjs → database-calls-BKozZUEW.mjs} +1 -1
  11. package/dist/packem_shared/discoverFunctions-CZgLhsMn.mjs +1 -0
  12. package/dist/packem_shared/discoverHyperdriveCalls-DV4IglLE.mjs +1 -0
  13. package/dist/packem_shared/{discoverInserts-DUbjhNzk.mjs → discoverInserts-BjxXCACZ.mjs} +1 -1
  14. package/dist/packem_shared/discoverMaskProcedures-DE-8CDen.mjs +1 -0
  15. package/dist/packem_shared/{discoverNondeterministicCalls-D7Ovq8ae.mjs → discoverNondeterministicCalls-DvhyKM-f.mjs} +1 -1
  16. package/dist/packem_shared/{discoverQueries-BNqjOBY_.mjs → discoverQueries-C8E7TeRT.mjs} +1 -1
  17. package/dist/packem_shared/discoverR2sqlCalls-DVcfMO6-.mjs +1 -0
  18. package/dist/packem_shared/{discoverRlsMetadata-CbdfaVep.mjs → discoverRlsMetadata-QRsWRQbM.mjs} +1 -1
  19. package/dist/packem_shared/{discoverRlsProcedures-BeLdV5RT.mjs → discoverRlsProcedures-Du7ITNTQ.mjs} +1 -1
  20. package/dist/packem_shared/{discoverStorageRulesMetadata-BBMy9JVZ.mjs → discoverStorageRulesMetadata-ClzKLdCV.mjs} +1 -1
  21. package/dist/packem_shared/{emitAgents-DuSp0uSJ.mjs → emitAgents-CR2_X_ov.mjs} +1 -1
  22. package/dist/packem_shared/emitFunctions-rjyb7h7k.mjs +422 -0
  23. package/dist/packem_shared/{emitShard-Ddgmq6De.mjs → emitShard-D3Po46nf.mjs} +1 -1
  24. package/dist/packem_shared/{exported-procedure-chains-DAl7xBBx.mjs → exported-procedure-chains-BNBUkXui.mjs} +1 -1
  25. package/dist/packem_shared/{index-DvmKcoFV.mjs → index-JnqBWRYO.mjs} +1 -1
  26. package/dist/packem_shared/{shard-DYYhXxEG.mjs → shard-CsOnD3Na.mjs} +226 -117
  27. package/dist/packem_shared/{shard-runtime-BQ6ZNigW.mjs → shard-runtime-BpoCV-aM.mjs} +13 -8
  28. package/package.json +1 -1
  29. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DwqkR6hn.mjs +0 -11
  30. package/dist/packem_shared/chain-CubC5VoS.mjs +0 -1
  31. package/dist/packem_shared/classify-procedure-call-CcgP-9I0.mjs +0 -1
  32. package/dist/packem_shared/discoverFunctions-5Zy6K4uA.mjs +0 -1
  33. package/dist/packem_shared/discoverHyperdriveCalls-DFbp-ILH.mjs +0 -1
  34. package/dist/packem_shared/discoverMaskProcedures-BfVFPpAJ.mjs +0 -1
  35. package/dist/packem_shared/discoverR2sqlCalls-TNwsmYje.mjs +0 -1
  36. package/dist/packem_shared/emitFunctions-amc10WSc.mjs +0 -291
@@ -1 +1 @@
1
- import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-B81lOULB.mjs";import{w as d}from"./classify-procedure-call-CcgP-9I0.mjs";import{e as m}from"./exported-procedure-chains-DAl7xBBx.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
1
+ import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-B81lOULB.mjs";import{w as d}from"./classify-procedure-call-DVxdUhZt.mjs";import{e as m}from"./exported-procedure-chains-BNBUkXui.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
@@ -1 +1 @@
1
- import"./json-data-Chfs2Cz5.mjs";import{o as i,j as r,s as n,h as o,t as g,k as u,d as F,w as p,m as l,g as d,f,i as k,u as w,l as A,v as Q}from"./shard-runtime-BQ6ZNigW.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,u as emitPaymentFragments,F as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,d as emitServiceFragments,f as emitTopicFragments,k as emitWorkflowFragments,w as emitWorkflows,A as emitWorkflowsMetadataFragments,Q as queueAliasFindings};
1
+ import"./json-data-Chfs2Cz5.mjs";import{o as i,j as r,s as n,h as o,t as g,k as u,d as F,w as p,m as l,g as d,f,i as k,u as w,l as A,v as Q}from"./shard-runtime-BpoCV-aM.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,u as emitPaymentFragments,F as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,d as emitServiceFragments,f as emitTopicFragments,k as emitWorkflowFragments,w as emitWorkflows,A as emitWorkflowsMetadataFragments,Q as queueAliasFindings};
@@ -0,0 +1,422 @@
1
+ import{LunoraError as P}from"@lunora/errors";import{L as oe,G as C,d as j,I as M,b as F,r as se,c as ae}from"./shared-DnCokNcE.mjs";import{renderAgentFunctionRegistry as ie,renderSandboxFunctionRegistry as ce}from"./emitApi-CDgIPAG2.mjs";import{b as le,a as de,r as _,c as ue}from"./qualifiers-DEdXn5wP.mjs";import{s as f}from"./dispatch-namespace-DwTjD7BU.mjs";const he=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),D=r=>r.column!==void 0,me=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
2
+ `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
3
+ `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
4
+ `;case"null":return`if (${t} !== null) return DEFER;
5
+ `;default:return`if (typeof ${t} !== "string") return DEFER;
6
+ `}},pe=(r,t)=>r.stringMaxLength===void 0?"":`if (${t}.length > ${String(r.stringMaxLength)}) return DEFER;
7
+ `,ge=(r,t)=>{const n=r.literalValue?.trim();if(!(n===void 0||!oe.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
8
+ `}},T=(r,t,n)=>{if(!D(r)&&!(r.unmodelledRefinement||r.sourceText!==void 0)){if(he.has(r.kind))return r.kind==="any"?{out:t,pre:""}:{out:t,pre:me(r.kind,t)+pe(r,t)};switch(r.kind){case"array":return fe(r,t,n);case"literal":return ge(r,t);case"object":return we(r,t,n);default:return}}},fe=(r,t,n)=>{const{inner:o}=r;if(!o)return;const a=n.next(),i=`__arr${String(a)}`,s=`__i${String(a)}`,d=`__e${String(a)}`,u=T(o,d,n);if(!u)return;const c=`if (!Array.isArray(${t})) return DEFER;
9
+ const ${i} = new Array(${t}.length);
10
+ for (let ${s} = 0; ${s} < ${t}.length; ${s}++) {
11
+ const ${d} = ${t}[${s}];
12
+ ${u.pre}${i}[${s}] = ${u.out};
13
+ }
14
+ `;return{out:i,pre:c}},ye=(r,t,n,o)=>{const a=JSON.stringify(r);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||D(t))return;const{inner:s}=t;if(!s)return;const d=T(s,n,o);if(!d)return;const u=o.next(),c=`__has${String(u)}`,l=`__val${String(u)}`,g=`let ${c} = false;
15
+ let ${l};
16
+ if (${n} !== undefined) {
17
+ ${d.pre}${l} = ${d.out};
18
+ ${c} = true;
19
+ }
20
+ `;return{entry:`...(${c} ? { ${a}: ${l} } : {})`,pre:g}}const i=T(t,n,o);if(i)return{entry:`${a}: ${i.out}`,pre:i.pre}},$e=new Set(Object.getOwnPropertyNames(Object.prototype)),U=(r,t,n)=>{let o="";const a=[];for(const i of Object.keys(r)){const s=r[i];if(!s)return;const d=JSON.stringify(i);let u=`${t}[${d}]`;if($e.has(i)){const l=`__f${String(n.next())}`;o+=`const ${l} = Object.hasOwn(${t}, ${d}) ? ${t}[${d}] : undefined;
21
+ `,u=l}const c=ye(i,s,u,n);if(!c)return;o+=c.pre,a.push(c.entry)}return{entries:a.join(", "),pre:o}},J=r=>{const t=`Object.getPrototypeOf(${r})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
22
+ `},we=(r,t,n)=>{const o=r.shape??{},a=U(o,t,n);if(!a)return;const i=n.next(),s=`__obj${String(i)}`,d=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
23
+ ${J(t)}${a.pre}const ${s} = { ${a.entries} };
24
+ `;return{out:s,pre:d}},B=r=>{let t=0;const o=U(r,"source",{next:()=>(t+=1,t)});if(o)return`(source) => {
25
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
26
+ ${J("source")}${o.pre}return { ${o.entries} };
27
+ }`},Re=(r,t)=>`lunora_${f(r)}_${String(t)}`,I=r=>JSON.stringify(Object.entries(r).toSorted(([t],[n])=>t.localeCompare(n)).map(([t,n])=>{const o=n.kind==="optional",a=o?n.inner??{kind:"unknown"}:n,i=a.kind==="array"?a.inner?.kind:void 0,s=a.kind==="id"?a.tableName:void 0;return{kind:a.kind,name:t,optional:o,...s===void 0?{}:{table:s},...i===void 0||i==="unknown"?{}:{element:i}}})),H=(r,t,n,o)=>{const a=new Map,i=s=>{a.has(s)||a.set(s,Re(s,a.size))};for(const s of r)i(s.filePath);for(const s of t)i(s.filePath);for(const s of n)i(s.filePath);for(const s of o)i(s.filePath);return a},q=(r,t,n)=>new Set([...r.map(o=>o.filePath),...t.map(o=>o.filePath),...n.map(o=>o.filePath)]),k=r=>`${r}[functionPath]`,Ne=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
28
+ const registered = await loadFunction(functionPath);
29
+
30
+ if (!registered) {
31
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
32
+ }
33
+
34
+ // A mutation is routed through the caller's own \`ctx.runMutation\` rather than
35
+ // invoked directly, so \`createCaller(ctx).ns.someMutation()\` gets exactly what
36
+ // \`ctx.runMutation(api.ns.someMutation)\` gets: the BEGIN/COMMIT span (or the
37
+ // enclosing one, when the caller is already inside a transaction), the jobs it
38
+ // schedules held until that span commits, and the deferred object deletes
39
+ // flushed only once it has. Called straight, a mutation composed from an action
40
+ // or a stream had none of the three — its writes autocommitted one row at a
41
+ // time and its \`ctx.scheduler\` calls dispatched immediately, so a mid-handler
42
+ // throw left the earlier writes durable and the job already enqueued.
43
+ //
44
+ // The fallback covers a context that is not a shard dispatch (\`runMutation\` is
45
+ // installed by \`buildCtx\` on every kind but a query's TYPE omits it); there is
46
+ // no transaction to join in that case, so a direct call is all there is.
47
+ //
48
+ // A query is routed through \`ctx.runQuery\` for the same reason: that is what
49
+ // hands it a query view of a mutation's or action's ctx (no request origin,
50
+ // query-guarded \`run*\`) instead of the caller's own.
51
+ if (registered.kind === "mutation" || registered.kind === "query") {
52
+ const run = (context as { runMutation?: unknown; runQuery?: unknown })[registered.kind === "mutation" ? "runMutation" : "runQuery"];
53
+
54
+ if (typeof run === "function") {
55
+ return (await run.call(context, { __lunoraRef: functionPath }, args ?? {})) as R;
56
+ }
57
+ }
58
+
59
+ return (await registered.handler(context, args ?? {})) as R;
60
+ };`,be=(r,t,n=[],o=[],a=!1)=>{const i=H(r,t,n,o),s=q(t,n,o),d=[...i.entries()].filter(([e])=>!a||s.has(e)?!0:r.some(m=>m.filePath===e&&m.channel?.kind==="room")).map(([e,m])=>{if(!M.test(e))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);return`import ${a&&!s.has(e)?"type ":""}* as ${m} from "../${e}.js";`}).join(`
61
+ `),u=r.map(e=>!a||s.has(e.filePath)?` "${f(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`:` "${f(e.filePath)}:${e.exportName}": { args: {}, handler: unloadedFunctionHandler, ...${JSON.stringify({argumentDescriptors:JSON.parse(I(e.args)),kind:e.kind,...e.channel?{channel:e.channel}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}}})} } satisfies RegisteredLunoraFunction & Pick<FunctionManifestEntry, "argumentDescriptors" | "channel" | "expose">,`).join(`
62
+ `),c=t.map(e=>` ${JSON.stringify(e.id)}: ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredDataMigration,`).join(`
63
+ `),l=n.map(e=>` "${f(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`).join(`
64
+ `),g=o.map(e=>` "${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredShape,`).join(`
65
+ `),y=n.map(e=>`${f(e.filePath)}:${e.exportName}`),$=[u,l].filter(e=>e.length>0).join(`
66
+ `),v=r.filter(e=>!a||s.has(e.filePath)).map(e=>{if(e.lifecycle||Object.keys(e.args).length===0)return;const m=B(e.args);return m===void 0?void 0:`installCompiledValidatorMap(${i.get(e.filePath)??""}.${e.exportName}.args, ${m});`}).filter(e=>e!==void 0).join(`
67
+ `),O=r.filter(e=>e.channel?.kind==="room").map(e=>` ${JSON.stringify(e.channel?.name??"")}: RoomMessageOf<typeof ${i.get(e.filePath)??""}[${JSON.stringify(e.exportName)}]>;`).join(`
68
+ `),N=[...r.map(e=>({args:e.args,definition:e,path:`${f(e.filePath)}:${e.exportName}`})),...n.map(e=>({args:e.args,definition:{...e,expose:void 0,kind:"mutation",lifecycle:void 0,visibility:void 0,x402:void 0},path:`${f(e.filePath)}:${e.exportName}`}))],x=a?N.filter(({definition:e})=>!s.has(e.filePath)):[];for(const{definition:e}of N)if(a&&e.x402&&e.x402.price===void 0)throw new P("INTERNAL",`@lunora/codegen: lazy function registry needs a literal \`.x402({ price })\` value in ${e.filePath}:${e.exportName}`);const b=a?x.map(({definition:e,path:m})=>{const R=i.get(e.filePath)??"",S="channel"in e?e.channel:void 0,A={argumentDescriptors:JSON.parse(I(e.args)),exportName:e.exportName,kind:e.kind,moduleId:R,...S?{channel:S}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}}};return` ${JSON.stringify(m)}: ${JSON.stringify(A)},`}).join(`
69
+ `):"",h=[...new Set(x.map(({definition:e})=>e.filePath))],w=a?h.map(e=>{if(!M.test(e))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);const m=i.get(e)??"";return` ${JSON.stringify(m)}: () => import(${JSON.stringify(`./fn/${m}.js`)}),`}).join(`
70
+ `):"";return{dispatchBody:$.length>0?`
71
+ ${$}
72
+ `:"",importBlock:d.length>0?`${d}
73
+
74
+ `:"",installBlock:v,manifestBody:b.length>0?`
75
+ ${b}
76
+ `:"",migrationBody:c.length>0?`
77
+ ${c}
78
+ `:"",moduleLoaders:w.length>0?`
79
+ ${w}
80
+ `:"",mutatorPaths:y,roomMessagesBody:O,shapeBody:g.length>0?`
81
+ ${g}
82
+ `:""}},ke=r=>{const t=F(r,o=>{const a=_(se(o.args),o.filePath),i=a==="{}"?"?":"",s=_(ue(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${i}: ${a}) => Promise<AsyncIterable<${s}>>;`:`${o.exportName}: (args${i}: ${a}) => Promise<${s}>;`},"type");return{implementation:F(r,o=>`${ae(o.exportName)}: (args) => callRegistered(context, "${f(o.filePath)}:${o.exportName}", args),`,"value"),types:t}},ve=r=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of r)n.lifecycle&&t[n.lifecycle].push(`${f(n.filePath)}:${n.exportName}`);return t},Oe=(r,t,n)=>r?{channelField:` /**
83
+ * Set on a \`defineRoom\` registration: the room's name (without the \`room:\`
84
+ * topic prefix). The generated \`LUNORA_ROOMS\` map keys it on the room's
85
+ * \`room:<name>\` whisper topic so the ShardDO resolves a room topic to this
86
+ * path.
87
+ */
88
+ channel?: { readonly kind: "room"; readonly name: string };
89
+ `,messagesBlock:`
90
+ /**
91
+ * The message type each \`defineRoom\` carries, read off the room's own registration. The generated \`rooms\` references type a client's \`connectRoom\` from it.
92
+ */
93
+ export type LunoraRoomMessages = {
94
+ ${n}
95
+ };
96
+ `,typeImport:`import type { RoomMessageOf } from "${t}";
97
+ `}:{channelField:"",messagesBlock:"",typeImport:""},xe=(r,t,n)=>r?t?`
98
+ /**
99
+ * Room routes are static metadata so building the worker never evaluates user handlers.
100
+ */
101
+ export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
102
+ const registry: Record<string, string> = {};
103
+ const owners = new Map<string, string>();
104
+
105
+ for (const { owner, path, topic } of [
106
+ ${n.filter(o=>o.channel?.kind==="room").map(o=>` { owner: ${JSON.stringify(o.filePath)}, path: ${JSON.stringify(`${f(o.filePath)}:${o.exportName}`)}, topic: ${JSON.stringify(`room:${o.channel?.name??""}`)} },`).join(`
107
+ `)}
108
+ ]) {
109
+ const prior = owners.get(topic);
110
+
111
+ if (prior !== undefined && prior !== owner) {
112
+ throw new Error(\`two defineRoom registrations are named "\${topic.slice("room:".length)}"; room names must be unique\`);
113
+ }
114
+
115
+ if (prior === undefined) {
116
+ owners.set(topic, owner);
117
+ registry[topic] = path;
118
+ }
119
+ }
120
+
121
+ return registry;
122
+ })();
123
+ `:`
124
+ /**
125
+ * Room registry: the whisper topic of each \`defineRoom\` registration → its
126
+ * function path. The generated ShardDO's \`roomHandlerPath\` override resolves a
127
+ * room topic through this map so a room's typed \`onJoin\`/\`onMessage\`/\`onLeave\`
128
+ * dispatch server-side, reusing the whisper channel for membership and fan-out.
129
+ * Two registrations under one name throw at module load: the map would otherwise
130
+ * silently keep whichever came last.
131
+ */
132
+ export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
133
+ const registry: Record<string, string> = {};
134
+ const owners = new Map<string, unknown>();
135
+
136
+ for (const [path, fn] of Object.entries(LUNORA_FUNCTIONS)) {
137
+ if (fn.channel?.kind !== "room") {
138
+ continue;
139
+ }
140
+
141
+ const topic = \`room:\${fn.channel.name}\`;
142
+ const owner = owners.get(topic);
143
+
144
+ // The same registration exported under two names (an alias) is one room.
145
+ if (owner !== undefined && owner !== fn) {
146
+ throw new Error(\`two defineRoom registrations are named "\${fn.channel.name}"; room names must be unique\`);
147
+ }
148
+
149
+ if (owner === undefined) {
150
+ owners.set(topic, fn);
151
+ registry[topic] = path;
152
+ }
153
+ }
154
+
155
+ return registry;
156
+ })();
157
+ `:"",Se=(r,t)=>{const n=ke(r),o=n.types?`
158
+ ${n.types}
159
+ `:"",a=n.implementation?`
160
+ ${n.implementation}
161
+ `:"",i=de(n.types),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
162
+ `:"",d=r.length>0?"context":"_context";let u="";if(r.length>0){let c=Ne;t||(c=c.replace("await loadFunction(functionPath)",k("LUNORA_FUNCTIONS"))),u=`${c}
163
+
164
+ `}return{callRegisteredHelper:u,dataModelImport:s,implementation:a,parameter:d,types:o}},Ee=r=>{const{agents:t=[],functions:n,lazyFunctions:o=!1,migrations:a=[],mutators:i=[],shapes:s=[],useUmbrella:d=!1,usesSandbox:u=!1}=r,c=j(d),{dispatchBody:l,importBlock:g,installBlock:y,manifestBody:$,migrationBody:v,moduleLoaders:O,mutatorPaths:N,roomMessagesBody:x,shapeBody:b}=be(n,a,i,s,o),h=ie(t,n),w=ce(u,n),e=[h.lines,w.lines].filter(p=>p.length>0).join(`
165
+ `);let m=l;e.length>0&&(m=l.length>0?`${l.trimEnd()}
166
+ ${e}
167
+ `:`
168
+ ${e}
169
+ `);const R=ve(n),S=o?"await loadFunction(functionPath)":k("LUNORA_FUNCTIONS"),A=o?` if (${k("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
170
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
171
+ }
172
+
173
+ `:"",Q=s.length>0?`import type { RegisteredShape } from "${c.server}";
174
+ `:"",E=n.some(p=>p.channel?.kind==="room"),L=Oe(E,c.server,x),G=s.length>0?`
175
+ /**
176
+ * Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
177
+ * The generated ShardDO's \`resolveShape\` override looks a shape up by name and
178
+ * evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
179
+ * \`shape_subscribe\` (reads-as-permissions).
180
+ */
181
+ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${b}};
182
+ `:"",V=N.length>0?`
183
+ /**
184
+ * Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
185
+ * ShardDO's \`isCustomMutator\` override routes through the client-watermark push
186
+ * protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
187
+ */
188
+ export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${N.map(p=>JSON.stringify(p)).join(", ")}]);
189
+ `:"",z=xe(E,o,n),W=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${c.values}";
190
+ `:"",K=y.length>0?`
191
+ /**
192
+ * AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
193
+ * onto its function's live \`.args\` object and consulted by the interpreted
194
+ * parser as a zero-allocation fast path; anything it can't model is deferred.
195
+ */
196
+ ${y}
197
+ `:"",Y=Se(n,o),{callRegisteredHelper:X,dataModelImport:Z,implementation:ee,parameter:te,types:re}=Y,ne=o?`
198
+ export interface FunctionManifestEntry {
199
+ argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; table?: string }>;
200
+ channel?: { kind: "room"; name: string };
201
+ exportName: string;
202
+ expose?: { cache?: { credentialHeaders?: ReadonlyArray<string>; maxAge?: number; scope?: "private" | "public"; staleWhileRevalidate?: number; tag?: string; vary?: string }; rest?: boolean };
203
+ kind: "action" | "mutation" | "query" | "stream";
204
+ lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper";
205
+ moduleId: string;
206
+ visibility?: "internal" | "public";
207
+ x402?: { readonly price: number | string };
208
+ }
209
+
210
+ /** Static, codegen-derived facts. Request gates can inspect these without evaluating a user module. */
211
+ export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${$}};
212
+
213
+ const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${O}};
214
+ const loadedModules = new Map<string, Promise<Record<string, unknown>>>();
215
+ const resolvedModules = new Map<string, Record<string, unknown>>();
216
+ const unloadedFunctionHandler = (): never => {
217
+ throw new Error("a lazy function was invoked before it was prepared");
218
+ };
219
+
220
+ /** Reuse an evaluated module synchronously, so dispatch does not yield after restoring request scope. */
221
+ export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunction | undefined => {
222
+ const registered = ${k("LUNORA_FUNCTIONS")};
223
+ const manifest = ${k("LUNORA_FUNCTION_MANIFEST")};
224
+
225
+ if (!registered || !manifest) {
226
+ return registered;
227
+ }
228
+
229
+ const module = resolvedModules.get(manifest.moduleId);
230
+
231
+ if (module === undefined) {
232
+ return undefined;
233
+ }
234
+
235
+ const loaded = module[manifest.exportName];
236
+
237
+ if (typeof loaded !== "object" || loaded === null) {
238
+ throw new Error(\`lazy module export for "\${functionPath}" is not a registered function\`);
239
+ }
240
+
241
+ Object.assign(registered, loaded);
242
+
243
+ return registered;
244
+ };
245
+
246
+ /** Load one function's owning module once per isolate, then merge its live builder result into the registry entry. */
247
+ export const loadFunction = async (functionPath: string): Promise<RegisteredLunoraFunction | undefined> => {
248
+ const registered = getLoadedFunction(functionPath);
249
+ const manifest = ${k("LUNORA_FUNCTION_MANIFEST")};
250
+
251
+ if (registered || !manifest) {
252
+ return registered;
253
+ }
254
+
255
+ let pending = loadedModules.get(manifest.moduleId);
256
+
257
+ if (pending === undefined) {
258
+ const loader = MODULE_LOADERS[manifest.moduleId];
259
+
260
+ if (loader === undefined) {
261
+ throw new Error(\`no lazy module loader registered for "\${functionPath}"\`);
262
+ }
263
+
264
+ pending = loader();
265
+ loadedModules.set(manifest.moduleId, pending);
266
+ }
267
+
268
+ let module: Record<string, unknown>;
269
+
270
+ try {
271
+ module = await pending;
272
+ } catch (error: unknown) {
273
+ if (loadedModules.get(manifest.moduleId) === pending) {
274
+ loadedModules.delete(manifest.moduleId);
275
+ }
276
+
277
+ throw error;
278
+ }
279
+
280
+ resolvedModules.set(manifest.moduleId, module);
281
+
282
+ return getLoadedFunction(functionPath);
283
+ };
284
+ `:"";return le(`${C}${g}${h.importLine}${w.importLine}${W}${Q}${L.typeImport}import { LunoraError } from "${c.server}";
285
+ import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
286
+ ${Z}
287
+ /**
288
+ * Single registered function, narrowed to the shape \`handleRpc\` needs.
289
+ * The real argument validators / return types are checked elsewhere — at
290
+ * the dispatch site we erase to \`unknown\` so a single map can host every
291
+ * registered function.
292
+ */
293
+ export interface RegisteredLunoraFunction {
294
+ kind: "action" | "mutation" | "query" | "stream";
295
+ args: Record<string, unknown>;
296
+ /**
297
+ * Present on a \`"stream"\` declared \`durable\`: its run is persisted and
298
+ * survives the socket that opened it. Absent on every other kind, and on an
299
+ * ephemeral stream.
300
+ */
301
+ durable?: { ttlMs?: number };
302
+ /**
303
+ * For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
304
+ * For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
305
+ * \`AbortSignal\` as a third argument — the runtime drives it frame-by-frame.
306
+ */
307
+ handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
308
+ /**
309
+ * The lifecycle moment a hook fires on, when this registration came from
310
+ * \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`/\`onWhisper\`.
311
+ * Read at dispatch to decide whether the function runs system-trusted:
312
+ * \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
313
+ * to. \`whisper\` does have one — it runs under the asking socket's identity.
314
+ */
315
+ lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper";
316
+ ${L.channelField} /**
317
+ * Hoisted by the builder when the \`.use()\` chain carries a step with a
318
+ * per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
319
+ * captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
320
+ * inside the dispatch callback, and a reactive-cache HIT skips that
321
+ * callback, so such a query must never be memoized.
322
+ */
323
+ perDispatch?: boolean;
324
+ /** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
325
+ visibility?: "internal" | "public";
326
+ /**
327
+ * \`.x402({ price })\` tag on a paid public procedure. The origin worker
328
+ * paywalls it; the shard refuses to subscribe it (\`isPaidFunction\`).
329
+ */
330
+ x402?: { readonly price: number | string };
331
+ }
332
+ ${h.prelude}${w.prelude}${ne}
333
+ /**
334
+ * Static dispatch table. The key matches the \`__lunoraRef\` the client
335
+ * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
336
+ */
337
+ export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${m}};
338
+ ${K}${G}${V}${z}${L.messagesBlock}
339
+ /**
340
+ * Lifecycle manifest: the function paths the generated ShardDO dispatches when a
341
+ * client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
342
+ * per Durable Object instance before any handler runs (\`init\`), after a
343
+ * write flush when a watched read's result changed (\`reactor\`), and before a
344
+ * socket joins or broadcasts to a whisper topic (\`whisper\`). Each path also
345
+ * resolves through {@link LUNORA_FUNCTIONS}. The socket-scoped moments run under
346
+ * the socket's verified identity; \`init\` and \`reactor\` have no caller, so they
347
+ * run anonymous — all via system dispatch.
348
+ */
349
+ export const LUNORA_LIFECYCLE_HOOKS: {
350
+ connect: readonly string[];
351
+ disconnect: readonly string[];
352
+ init: readonly string[];
353
+ reactor: readonly string[];
354
+ whisper: readonly string[];
355
+ } = {
356
+ connect: [${R.connect.map(p=>JSON.stringify(p)).join(", ")}],
357
+ disconnect: [${R.disconnect.map(p=>JSON.stringify(p)).join(", ")}],
358
+ init: [${R.init.map(p=>JSON.stringify(p)).join(", ")}],
359
+ reactor: [${R.reactor.map(p=>JSON.stringify(p)).join(", ")}],
360
+ whisper: [${R.whisper.map(p=>JSON.stringify(p)).join(", ")}],
361
+ };
362
+
363
+ /**
364
+ * Resolve and invoke a registered function from an external caller. Throws a
365
+ * LunoraError-shaped object (404) when the path is unknown — the runtime's
366
+ * structural error mapper turns that into the right HTTP status. Internal
367
+ * functions are treated as not-found so their existence never leaks to clients.
368
+ */
369
+ export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
370
+ ${A} const registered = ${S};
371
+
372
+ if (!registered || registered.visibility === "internal") {
373
+ throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
374
+ }
375
+
376
+ return registered.handler(context, args);
377
+ };
378
+
379
+ /**
380
+ * A handler context accepted by {@link createCaller}. The runtime context the
381
+ * shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
382
+ */
383
+ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
384
+
385
+ /**
386
+ * Typed, in-process server-to-server caller. Every registered function — public
387
+ * *and* internal — is reachable; each call dispatches against the same shard
388
+ * with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
389
+ * \`runAction\` but without re-stating the function path.
390
+ */
391
+ export interface Caller {${re}}
392
+
393
+ ${X}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
394
+ export const createCaller = (${te}: CallerCtx): Caller => ({${ee}});
395
+
396
+ /**
397
+ * Single registered data migration, narrowed to the shape the per-shard runner
398
+ * consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
399
+ * validation lives in \`defineMigration\`.
400
+ */
401
+ export interface RegisteredDataMigration {
402
+ batchSize?: number;
403
+ down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
404
+ id: string;
405
+ table: string;
406
+ up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
407
+ }
408
+
409
+ /**
410
+ * Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
411
+ * shard DO's admin RPC and the CLI resolve migrations to run through this map.
412
+ */
413
+ export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${v}};
414
+ `,d)},Fe=r=>{if(r.lazyFunctions!==!0)return{};const{functions:t}=r,n=r.migrations??[],o=r.mutators??[],a=r.shapes??[],i=H(t,n,o,a),s=q(n,o,a),d=[...new Set(t.filter(l=>!s.has(l.filePath)).map(l=>l.filePath))],u=j(r.useUmbrella??!1),c={};for(const l of d){if(!M.test(l))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);const g=i.get(l)??"",y=`../../${l}.js`,$=t.filter(h=>h.filePath===l&&!h.lifecycle&&Object.keys(h.args).length>0).flatMap(h=>{const w=B(h.args);return w===void 0?[]:[`installCompiledValidatorMap(${g}.${h.exportName}.args, ${w});`]}),v=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
415
+ `:"",O=$.length>0?`import * as ${g} from "${y}";
416
+ `:"",N=$.length>0?`
417
+ /** Install the precompiled argument parsers before the module is dispatched. */
418
+ ${$.join(`
419
+ `)}
420
+ `:"",b=t.some(h=>h.filePath===l&&h.exportName==="default")||n.some(h=>h.filePath===l&&h.exportName==="default")?`export { default } from "${y}";
421
+ `:"";c[`fn/${g}.ts`]=`${C}${v}${O}${N}export * from "${y}";
422
+ ${b}`}return c};export{Ee as emitFunctions,Fe as emitLazyFunctionModules};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DYYhXxEG.mjs";import"./shard-runtime-BQ6ZNigW.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-CsOnD3Na.mjs";import"./shard-runtime-BpoCV-aM.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -1 +1 @@
1
- import{Node as s}from"ts-morph";import{b as t,d as c}from"./attribution-hVBriwzy.mjs";import{c as n}from"./classify-procedure-call-CcgP-9I0.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
1
+ import{Node as s}from"ts-morph";import{b as t,d as c}from"./attribution-hVBriwzy.mjs";import{c as n}from"./classify-procedure-call-DVxdUhZt.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
@@ -1 +1 @@
1
- import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-B81lOULB.mjs";import{b as m,d as p}from"./attribution-hVBriwzy.mjs";import{t as d}from"./database-calls-BnVUlTx_.mjs";import{w as g,c as h}from"./classify-procedure-call-CcgP-9I0.mjs";import{a as k}from"./project-config-file-BV7RR-l6.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
1
+ import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-B81lOULB.mjs";import{b as m,d as p}from"./attribution-hVBriwzy.mjs";import{t as d}from"./database-calls-BKozZUEW.mjs";import{w as g,c as h}from"./classify-procedure-call-DVxdUhZt.mjs";import{a as k}from"./project-config-file-BV7RR-l6.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};