@lunora/codegen 1.0.0-alpha.383 → 1.0.0-alpha.385
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 +43 -5
- package/dist/index.d.ts +43 -5
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AGENTS_FILENAME-BedyJsOT.mjs → AGENTS_FILENAME-5mDMAMWy.mjs} +1 -1
- package/dist/packem_shared/{CONTAINERS_FILENAME-T1v8pyHN.mjs → CONTAINERS_FILENAME-BJYrxnq2.mjs} +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-Bzf6ZJ9r.mjs → GENERATED_HEADER-B-tYRlRG.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-BGvYo46g.mjs → MUTATORS_FILENAME-D9WbOFm7.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-BJJObZHG.mjs → NOTIFY_FILENAME-CRU_TEKs.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-CSjT8wJW.mjs → OPENRPC_VERSION-CT_E2DcI.mjs} +1 -1
- package/dist/packem_shared/{QUEUES_FILENAME-Dt5RG_P0.mjs → QUEUES_FILENAME-BeGwgqcw.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DXilYf6b.mjs +31 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs +2 -0
- package/dist/packem_shared/SHAPES_FILENAME-D9beIrs1.mjs +1 -0
- package/dist/packem_shared/{SchemaSnapshotParseError-ycDz8gOB.mjs → SchemaSnapshotParseError-DnAuFdpl.mjs} +8 -8
- package/dist/packem_shared/{WORKFLOWS_FILENAME-VAXgqqP-.mjs → WORKFLOWS_FILENAME--RWiu_Vy.mjs} +1 -1
- package/dist/packem_shared/{attribution-DUbGYT4N.mjs → attribution-CTMkuBkn.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-afHH7rN5.mjs → buildOpenApiDocument-67-fasdW.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-B75cjwpy.mjs → context-property-calls-ZK1UcTQR.mjs} +1 -1
- package/dist/packem_shared/{context-root-D4Njep-A.mjs → context-root-DtpwprsY.mjs} +1 -1
- package/dist/packem_shared/{database-calls-aAjZJdma.mjs → database-calls-Cn47SfSU.mjs} +1 -1
- package/dist/packem_shared/{discoverAuthApiCalls-Ce3BdKQr.mjs → discoverAuthApiCalls-DZMYREsq.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-DU5ylqVC.mjs +1 -0
- package/dist/packem_shared/{discoverHttpRoutes-BQM2CPSF.mjs → discoverHttpRoutes-D9Q0lBBb.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DlyCZKX3.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-DldQpEfF.mjs → discoverInserts-7Xdawmuk.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-D6kAKDZG.mjs +1 -0
- package/dist/packem_shared/{discoverMigrations-E9k4Ykku.mjs → discoverMigrations-C649uAWL.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-DZ_kIie5.mjs → discoverNondeterministicCalls-DQgVTcLv.mjs} +1 -1
- package/dist/packem_shared/{discoverQueries-Bq2hqYHP.mjs → discoverQueries-C75OdGHl.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-BrDIti5c.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-Dq6iSXnC.mjs → discoverRlsMetadata-DqZpiGts.mjs} +1 -1
- package/dist/packem_shared/discoverRlsProcedures-BiyDg2ej.mjs +1 -0
- package/dist/packem_shared/discoverSchema-Bs5JUiOE.mjs +1 -0
- package/dist/packem_shared/{discoverStorageRulesMetadata-CJ7h6SPK.mjs → discoverStorageRulesMetadata-H3RJzkH_.mjs} +1 -1
- package/dist/packem_shared/{emitAgents-BeM6PZv4.mjs → emitAgents-iTKWSKan.mjs} +1 -1
- package/dist/packem_shared/{emitApi-GFmStqmq.mjs → emitApi-DWJW8Vu9.mjs} +1 -1
- package/dist/packem_shared/{emitApp-D-6FIpYb.mjs → emitApp-L7PnfjJK.mjs} +1 -1
- package/dist/packem_shared/{emitCrons-Drdn8Mjn.mjs → emitCrons-BvqxeNRr.mjs} +1 -1
- package/dist/packem_shared/{emitDataModel-LTnwnhV6.mjs → emitDataModel-MjAOi3KM.mjs} +1 -1
- package/dist/packem_shared/{emitDrizzleSchema-CM9jh_F0.mjs → emitDrizzleSchema-Dszoyymv.mjs} +1 -1
- package/dist/packem_shared/{emitFunctions-CfSXBV_A.mjs → emitFunctions-CvMrX_cX.mjs} +100 -93
- package/dist/packem_shared/{emitServer-4l7MPmK0.mjs → emitServer-BgI9yXW1.mjs} +1 -1
- package/dist/packem_shared/emitShard-D4sAFu7Z.mjs +1 -0
- package/dist/packem_shared/{exported-procedure-chains-BaCIhnJ7.mjs → exported-procedure-chains-CRM-MVfP.mjs} +1 -1
- package/dist/packem_shared/handler-reference-90LXJART.mjs +1 -0
- package/dist/packem_shared/{index-11LAY5JO.mjs → index-CNI4vSyc.mjs} +1 -1
- package/dist/packem_shared/index-o449rQLQ.mjs +1 -0
- package/dist/packem_shared/ip-reads-Dotjify6.mjs +1 -0
- package/dist/packem_shared/{qualifiers-D1Q_3wo2.mjs → qualifiers-ClaCHu0X.mjs} +1 -1
- package/dist/packem_shared/{server-D69SOfX8.mjs → server-qWq5nN-R.mjs} +1 -1
- package/dist/packem_shared/{shard-CB0Ospyw.mjs → shard-BqfSKnmG.mjs} +94 -91
- package/dist/packem_shared/{shard-runtime-lkQU8trx.mjs → shard-runtime-C1P_uVye.mjs} +1 -1
- package/dist/packem_shared/{shared-A1XHcT4t.mjs → shared-DhqnD5R3.mjs} +6 -6
- package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +1 -0
- package/dist/packem_shared/{unwrap-handler-return-eQRIZSOX.mjs → unwrap-handler-return-c2s2-nk9.mjs} +1 -1
- package/package.json +8 -8
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-kN0pgKNu.mjs +0 -31
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs +0 -2
- package/dist/packem_shared/SHAPES_FILENAME-KyidzoqS.mjs +0 -1
- package/dist/packem_shared/discoverFunctions-CoQM_L6f.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-PUg-BESh.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-_Ey4eJLn.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-CeNnalpk.mjs +0 -1
- package/dist/packem_shared/discoverRlsProcedures-MboagP9z.mjs +0 -1
- package/dist/packem_shared/discoverSchema-Cycd1-H0.mjs +0 -1
- package/dist/packem_shared/emitShard-B4fVJcJA.mjs +0 -1
- package/dist/packem_shared/handler-reference-D1wpw_qR.mjs +0 -1
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import{LunoraError as
|
|
2
|
-
`;case"boolean":return`if (typeof ${
|
|
3
|
-
`;case"date":case"number":case"timestamp":return`if (typeof ${
|
|
4
|
-
`;case"null":return`if (${
|
|
5
|
-
`;default:return`if (typeof ${
|
|
6
|
-
`}},
|
|
7
|
-
`,
|
|
8
|
-
`}},
|
|
9
|
-
const ${i} = new Array(${
|
|
10
|
-
for (let ${
|
|
11
|
-
const ${c} = ${
|
|
12
|
-
${
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{L as pe,i as me,G as U,d as J,I as F,s as ge,b as C,r as fe,c as ye}from"./shared-DhqnD5R3.mjs";import{v as $e}from"./parse-validator-BisfC8bR.mjs";import{renderAgentFunctionRegistry as we,renderSandboxFunctionRegistry as Re}from"./emitApi-DWJW8Vu9.mjs";import{b as ke,a as be,r as j,c as Ne}from"./qualifiers-ClaCHu0X.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const ve=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),B=t=>t.column!==void 0,Oe=(t,r)=>{switch(t){case"bigint":return`if (typeof ${r} !== "bigint") return DEFER;
|
|
2
|
+
`;case"boolean":return`if (typeof ${r} !== "boolean") return DEFER;
|
|
3
|
+
`;case"date":case"number":case"timestamp":return`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return DEFER;
|
|
4
|
+
`;case"null":return`if (${r} !== null) return DEFER;
|
|
5
|
+
`;default:return`if (typeof ${r} !== "string") return DEFER;
|
|
6
|
+
`}},Se=(t,r)=>t.stringMaxLength===void 0?"":`if (${r}.length > ${String(t.stringMaxLength)}) return DEFER;
|
|
7
|
+
`,Pe=(t,r)=>{const n=t.literalValue?.trim();if(!(n===void 0||!pe.test(n)))return{out:r,pre:`if (${r} !== ${n}) return DEFER;
|
|
8
|
+
`}},E=(t,r,n)=>{if(!B(t)&&!(t.unmodelledRefinement||t.sourceText!==void 0)){if(ve.has(t.kind))return t.kind==="any"?{out:r,pre:""}:{out:r,pre:Oe(t.kind,r)+Se(t,r)};switch(t.kind){case"array":return xe(t,r,n);case"literal":return Pe(t,r);case"object":return Te(t,r,n);default:return}}},xe=(t,r,n)=>{const{inner:o}=t;if(!o)return;const s=n.next(),i=`__arr${String(s)}`,a=`__i${String(s)}`,c=`__e${String(s)}`,u=E(o,c,n);if(!u)return;const l=`if (!Array.isArray(${r})) return DEFER;
|
|
9
|
+
const ${i} = new Array(${r}.length);
|
|
10
|
+
for (let ${a} = 0; ${a} < ${r}.length; ${a}++) {
|
|
11
|
+
const ${c} = ${r}[${a}];
|
|
12
|
+
${u.pre}${i}[${a}] = ${u.out};
|
|
13
13
|
}
|
|
14
|
-
`;return{out:i,pre:l}},
|
|
15
|
-
let ${
|
|
14
|
+
`;return{out:i,pre:l}},Ae=(t,r,n,o)=>{const s=JSON.stringify(t);if(r.kind==="optional"){if(r.hasRefinement||r.sourceText!==void 0||B(r))return;const{inner:a}=r;if(!a)return;const c=E(a,n,o);if(!c)return;const u=o.next(),l=`__has${String(u)}`,d=`__val${String(u)}`,f=`let ${l} = false;
|
|
15
|
+
let ${d};
|
|
16
16
|
if (${n} !== undefined) {
|
|
17
|
-
${c.pre}${
|
|
17
|
+
${c.pre}${d} = ${c.out};
|
|
18
18
|
${l} = true;
|
|
19
19
|
}
|
|
20
|
-
`;return{entry:`...(${l} ? { ${
|
|
21
|
-
`,d
|
|
22
|
-
`},
|
|
23
|
-
${
|
|
24
|
-
`;return{out:
|
|
20
|
+
`;return{entry:`...(${l} ? { ${s}: ${d} } : {})`,pre:f}}const i=E(r,n,o);if(i)return{entry:`${s}: ${i.out}`,pre:i.pre}},Le=new Set(Object.getOwnPropertyNames(Object.prototype)),q=(t,r,n)=>{let o="";const s=[];for(const i of Object.keys(t)){const a=t[i];if(!a)return;const c=JSON.stringify(i);let u=`${r}[${c}]`;if(Le.has(i)){const d=`__f${String(n.next())}`;o+=`const ${d} = Object.hasOwn(${r}, ${c}) ? ${r}[${c}] : undefined;
|
|
21
|
+
`,u=d}const l=Ae(i,a,u,n);if(!l)return;o+=l.pre,s.push(l.entry)}return{entries:s.join(", "),pre:o}},H=t=>{const r=`Object.getPrototypeOf(${t})`;return`if (${r} !== Object.prototype && ${r} !== null) return DEFER;
|
|
22
|
+
`},Te=(t,r,n)=>{const o=t.shape??{},s=q(o,r,n);if(!s)return;const i=n.next(),a=`__obj${String(i)}`,c=`if (typeof ${r} !== "object" || ${r} === null || Array.isArray(${r})) return DEFER;
|
|
23
|
+
${H(r)}${s.pre}const ${a} = { ${s.entries} };
|
|
24
|
+
`;return{out:a,pre:c}},z=t=>{let r=0;const o=q(t,"source",{next:()=>(r+=1,r)});if(o)return`(source) => {
|
|
25
25
|
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
26
|
-
${
|
|
27
|
-
}`},
|
|
26
|
+
${H("source")}${o.pre}return { ${o.entries} };
|
|
27
|
+
}`},Fe=(t,r)=>`lunora_${g(t)}_${String(r)}`,D=t=>JSON.stringify(Object.entries(t).toSorted(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{const o=n.kind==="optional",s=o?n.inner??{kind:"unknown"}:n,i=s.kind==="array"?s.inner?.kind:void 0,a=s.kind==="id"?s.tableName:void 0;return{kind:s.kind,name:r,optional:o,...$e(n)?{sensitive:!0}:{},...a===void 0?{}:{table:a},...i===void 0||i==="unknown"?{}:{element:i}}})),W=(t,r,n,o)=>{const s=new Map,i=a=>{s.has(a)||s.set(a,Fe(a,s.size))};for(const a of t)i(a.filePath);for(const a of r)i(a.filePath);for(const a of n)i(a.filePath);for(const a of o)i(a.filePath);return s},Q=(t,r,n,o)=>new Set([...t.filter(s=>s.typeDerivedArgs).map(s=>s.filePath),...r.map(s=>s.filePath),...n.map(s=>s.filePath),...o.map(s=>s.filePath)]),_=t=>Array.isArray(t)?`Object.freeze([${t.map(r=>_(r)).join(", ")}])`:t!==null&&typeof t=="object"?`Object.freeze({ ${Object.entries(t).map(([n,o])=>`${JSON.stringify(n)}: ${_(o)}`).join(", ")} })`:typeof t=="number"&&(!Number.isFinite(t)||Object.is(t,-0))?Object.is(t,-0)?"-0":String(t):JSON.stringify(t),S=t=>`${t}[functionPath]`,Ee=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
28
28
|
const registered = await loadFunction(functionPath);
|
|
29
29
|
|
|
30
30
|
if (!registered) {
|
|
@@ -57,29 +57,29 @@ ${q("source")}${o.pre}return { ${o.entries} };
|
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
return (await registered.handler(context, args ?? {})) as R;
|
|
60
|
-
};`,
|
|
61
|
-
`),
|
|
62
|
-
`),l=
|
|
63
|
-
`),
|
|
60
|
+
};`,_e=(t,r,n=[],o=[],s=!1)=>{const i=W(t,r,n,o),a=Q(t,r,n,o),c=[...i.entries()].filter(([e])=>!s||a.has(e)?!0:t.some(m=>m.filePath===e&&m.channel?.kind==="room")).map(([e,m])=>{if(!F.test(e))throw new L("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);return`import ${s&&!a.has(e)?"type ":""}* as ${m} from "../${e}.js";`}).join(`
|
|
61
|
+
`),u=t.map(e=>{if(!s||a.has(e.filePath))return` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`;const m=ge(e.args);return` "${g(e.filePath)}:${e.exportName}": { args: {}, handler: unloadedFunctionHandler, ...${JSON.stringify({argumentDescriptors:JSON.parse(D(e.args)),kind:e.kind,...m.length===0?{}:{sensitiveArgs:m},...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}},...e.socket===void 0?{}:{auth:e.socket.auth,socketPath:e.socket.path}})}${e.meta===void 0?"":`, [Symbol.for("lunora.procedure.meta")]: ${_(e.meta)}`} } satisfies RegisteredLunoraFunction & Pick<FunctionManifestEntry, "argumentDescriptors" | "channel" | "expose">,`}).join(`
|
|
62
|
+
`),l=r.map(e=>` ${JSON.stringify(e.id)}: ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
63
|
+
`),d=n.map(e=>` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
64
64
|
`),f=o.map(e=>` "${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredShape,`).join(`
|
|
65
|
-
`)
|
|
66
|
-
`),
|
|
67
|
-
`),
|
|
68
|
-
`),
|
|
69
|
-
`):"",
|
|
70
|
-
`):"";return{dispatchBody:
|
|
71
|
-
${
|
|
65
|
+
`),y=n.map(e=>`${g(e.filePath)}:${e.exportName}`),$=[...t.filter(e=>e.readsIp===!0).map(e=>`${g(e.filePath)}:${e.exportName}`),...o.filter(e=>e.readsIp===!0).map(e=>e.exportName)],R=[u,d].filter(e=>e.length>0).join(`
|
|
66
|
+
`),P=t.filter(e=>!s||a.has(e.filePath)).map(e=>{if(e.lifecycle||e.typeDerivedArgs||Object.keys(e.args).length===0)return;const m=z(e.args);return m===void 0?void 0:`installCompiledValidatorMap(${i.get(e.filePath)??""}.${e.exportName}.args, ${m});`}).filter(e=>e!==void 0).join(`
|
|
67
|
+
`),x=t.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=[...t.map(e=>({args:e.args,definition:e,path:`${g(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:`${g(e.filePath)}:${e.exportName}`}))],v=s?N.filter(({definition:e})=>!a.has(e.filePath)):[];for(const{definition:e}of N)if(s&&e.x402&&e.x402.price===void 0)throw new L("INTERNAL",`@lunora/codegen: lazy function registry needs a literal \`.x402({ price })\` value in ${e.filePath}:${e.exportName}`);const p=s?v.map(({definition:e,path:m})=>{const k=i.get(e.filePath)??"",A="channel"in e?e.channel:void 0,b={argumentDescriptors:JSON.parse(D(e.args)),exportName:e.exportName,kind:e.kind,moduleId:k,...A?{channel:A}:{},...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(b)},`}).join(`
|
|
69
|
+
`):"",w=[...new Set(v.map(({definition:e})=>e.filePath))],O=s?w.map(e=>{if(!F.test(e))throw new L("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:R.length>0?`
|
|
71
|
+
${R}
|
|
72
72
|
`:"",importBlock:c.length>0?`${c}
|
|
73
73
|
|
|
74
|
-
`:"",installBlock:
|
|
75
|
-
${
|
|
74
|
+
`:"",installBlock:P,manifestBody:p.length>0?`
|
|
75
|
+
${p}
|
|
76
76
|
`:"",migrationBody:l.length>0?`
|
|
77
77
|
${l}
|
|
78
|
-
`:"",moduleLoaders:
|
|
79
|
-
${
|
|
80
|
-
`:"",mutatorPaths
|
|
78
|
+
`:"",moduleLoaders:O.length>0?`
|
|
79
|
+
${O}
|
|
80
|
+
`:"",ipReaderPaths:$,mutatorPaths:y,roomMessagesBody:x,shapeBody:f.length>0?`
|
|
81
81
|
${f}
|
|
82
|
-
`:""}},
|
|
82
|
+
`:""}},Me=t=>{const r=C(t,o=>{const s=j(fe(o.args),o.filePath),i=s==="{}"?"?":"",a=j(Ne(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${i}: ${s}) => Promise<AsyncIterable<${a}>>;`:`${o.exportName}: (args${i}: ${s}) => Promise<${a}>;`},"type");return{implementation:C(t,o=>`${ye(o.exportName)}: (args) => callRegistered(context, "${g(o.filePath)}:${o.exportName}", args),`,"value"),types:r}},Ie=t=>{const r={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of t)!n.lifecycle||n.lifecycle==="socket"||r[n.lifecycle].push(`${g(n.filePath)}:${n.exportName}`);return r},Ce=t=>{const r=new Map,n=[];for(const o of t){if(o.lifecycle!=="socket"||o.socket===void 0)continue;const{auth:s,origin:i,path:a}=o.socket,c=`${g(o.filePath)}:${o.exportName}`,u=r.get(a);if(!(u?.origin!==void 0&&u.origin===i)){if(u!==void 0)throw new L("DUPLICATE_SOCKET_PATH",`two defineWebSocket routes serve "${a}" (${u.functionPath} and ${c}); socket paths must be unique.`);r.set(a,{functionPath:c,origin:i}),n.push(` ${JSON.stringify(a)}: { auth: ${String(s)}, functionPath: ${JSON.stringify(c)} },`)}}return`
|
|
83
83
|
/**
|
|
84
84
|
* Socket registry: the URL path of each \`defineWebSocket\` route → its function path + auth requirement.
|
|
85
85
|
* Static, so building the worker never evaluates a route's module. The generated ShardDO's \`socketRoute\` override
|
|
@@ -89,7 +89,7 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
|
|
|
89
89
|
${n.join(`
|
|
90
90
|
`)}
|
|
91
91
|
};
|
|
92
|
-
`},
|
|
92
|
+
`},je=(t,r)=>{const n=t.some(c=>c.lifecycle==="socket"),s=n&&r?Ce(t):n&&!r?`
|
|
93
93
|
/**
|
|
94
94
|
* Socket registry: the URL path of each \`defineWebSocket\` route → its function
|
|
95
95
|
* path + auth requirement. The generated ShardDO's \`socketRoute\` override
|
|
@@ -133,7 +133,7 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
|
|
|
133
133
|
* Set on a \`defineWebSocket\` registration: whether the route refuses an
|
|
134
134
|
* anonymous upgrade. Read into \`LUNORA_SOCKETS\` alongside \`socketPath\`.
|
|
135
135
|
*/
|
|
136
|
-
auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:
|
|
136
|
+
auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:s}},De=(t,r,n)=>t?{channelField:` /**
|
|
137
137
|
* Set on a \`defineRoom\` registration: the room's name (without the \`room:\`
|
|
138
138
|
* topic prefix). The generated \`LUNORA_ROOMS\` map keys it on the room's
|
|
139
139
|
* \`room:<name>\` whisper topic so the ShardDO resolves a room topic to this
|
|
@@ -147,8 +147,8 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
|
|
|
147
147
|
export type LunoraRoomMessages = {
|
|
148
148
|
${n}
|
|
149
149
|
};
|
|
150
|
-
`,typeImport:`import type { RoomMessageOf } from "${
|
|
151
|
-
`}:{channelField:"",messagesBlock:"",typeImport:""},
|
|
150
|
+
`,typeImport:`import type { RoomMessageOf } from "${r}";
|
|
151
|
+
`}:{channelField:"",messagesBlock:"",typeImport:""},Ue=(t,r,n)=>t?r?`
|
|
152
152
|
/**
|
|
153
153
|
* Room routes are static metadata so building the worker never evaluates user handlers.
|
|
154
154
|
*/
|
|
@@ -208,69 +208,76 @@ export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
|
|
|
208
208
|
|
|
209
209
|
return registry;
|
|
210
210
|
})();
|
|
211
|
-
`:"",
|
|
211
|
+
`:"",Je=(t,r)=>{const n=Me(t),o=n.types?`
|
|
212
212
|
${n.types}
|
|
213
|
-
`:"",
|
|
213
|
+
`:"",s=n.implementation?`
|
|
214
214
|
${n.implementation}
|
|
215
|
-
`:"",i
|
|
216
|
-
`:"",c=
|
|
215
|
+
`:"",i=be(n.types),a=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
|
|
216
|
+
`:"",c=t.length>0?"context":"_context";let u="";if(t.length>0){let l=Ee;r||(l=l.replace("await loadFunction(functionPath)",S("LUNORA_FUNCTIONS"))),u=`${l}
|
|
217
217
|
|
|
218
|
-
`}return{callRegisteredHelper:
|
|
218
|
+
`}return{callRegisteredHelper:u,dataModelImport:a,implementation:s,parameter:c,types:o}},Ge=t=>{const{agents:r=[],functions:n,lazyFunctions:o=!1,migrations:s=[],mutators:i=[],shapes:a=[],useUmbrella:c=!1,usesSandbox:u=!1}=t,l=J(c),{dispatchBody:d,importBlock:f,installBlock:y,ipReaderPaths:$,manifestBody:R,migrationBody:P,moduleLoaders:x,mutatorPaths:N,roomMessagesBody:v,shapeBody:p}=_e(n,s,i,a,o),w=we(r,n),O=Re(u,n),m=r.length>0||n.some(h=>me(h))?` /**
|
|
219
219
|
* Names of the arguments whose validators carry a \`v.sensitive\` marker. Read by the
|
|
220
220
|
* shard before any validator is loaded, so a lazy function's secret args are
|
|
221
221
|
* masked even on a dispatch that fails before its module evaluates.
|
|
222
222
|
*/
|
|
223
223
|
sensitiveArgs?: readonly string[];
|
|
224
|
-
`:"",
|
|
225
|
-
`);let
|
|
226
|
-
${
|
|
224
|
+
`:"",k=[w.lines,O.lines].filter(h=>h.length>0).join(`
|
|
225
|
+
`);let A=d;k.length>0&&(A=d.length>0?`${d.trimEnd()}
|
|
226
|
+
${k}
|
|
227
227
|
`:`
|
|
228
|
-
${
|
|
229
|
-
`);const b=
|
|
228
|
+
${k}
|
|
229
|
+
`);const b=Ie(n),G=o?"await loadFunction(functionPath)":S("LUNORA_FUNCTIONS"),V=o?` if (${S("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
|
|
230
230
|
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
231
231
|
}
|
|
232
232
|
|
|
233
|
-
`:"",
|
|
234
|
-
`:"",
|
|
233
|
+
`:"",K=a.length>0?`import type { RegisteredShape } from "${l.server}";
|
|
234
|
+
`:"",M=n.some(h=>h.channel?.kind==="room"),T=De(M,l.server,v),Y=a.length>0?`
|
|
235
235
|
/**
|
|
236
236
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
237
237
|
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
238
238
|
* evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
|
|
239
239
|
* \`shape_subscribe\` (reads-as-permissions).
|
|
240
240
|
*/
|
|
241
|
-
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${
|
|
242
|
-
`:"",
|
|
241
|
+
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${p}};
|
|
242
|
+
`:"",Z=N.length>0?`
|
|
243
243
|
/**
|
|
244
244
|
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
245
245
|
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
246
246
|
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
247
247
|
*/
|
|
248
|
-
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${
|
|
249
|
-
`:"",
|
|
250
|
-
|
|
248
|
+
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${N.map(h=>JSON.stringify(h)).join(", ")}]);
|
|
249
|
+
`:"",X=$.length>0?`
|
|
250
|
+
/**
|
|
251
|
+
* Queries and shapes that may read \`ctx.ip\`, decided statically (failing closed). The generated ShardDO marks them
|
|
252
|
+
* address-keyed from its first run, so it never resumes one warm: its rows can depend on the address the cursor
|
|
253
|
+
* was read at, which a claims fingerprint leaves out.
|
|
254
|
+
*/
|
|
255
|
+
export const LUNORA_IP_READER_PATHS: ReadonlySet<string> = new Set([${$.map(h=>JSON.stringify(h)).join(", ")}]);
|
|
256
|
+
`:"",ee=Ue(M,o,n),{fields:te,lifecycleMember:I,registry:re}=je(n,o),ne=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${l.values}";
|
|
257
|
+
`:"",oe=y.length>0?`
|
|
251
258
|
/**
|
|
252
259
|
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
253
260
|
* onto its function's live \`.args\` object and consulted by the interpreted
|
|
254
261
|
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
255
262
|
*/
|
|
256
|
-
${
|
|
257
|
-
`:"",
|
|
263
|
+
${y}
|
|
264
|
+
`:"",se=Je(n,o),{callRegisteredHelper:ae,dataModelImport:ie,implementation:ce,parameter:le,types:de}=se,ue=o?`
|
|
258
265
|
export interface FunctionManifestEntry {
|
|
259
266
|
argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; table?: string }>;
|
|
260
267
|
channel?: { kind: "room"; name: string };
|
|
261
268
|
exportName: string;
|
|
262
269
|
expose?: { cache?: { credentialHeaders?: ReadonlyArray<string>; maxAge?: number; scope?: "private" | "public"; staleWhileRevalidate?: number; tag?: string; vary?: string }; rest?: boolean };
|
|
263
270
|
kind: "action" | "mutation" | "query" | "stream";
|
|
264
|
-
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${
|
|
271
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${I};
|
|
265
272
|
moduleId: string;
|
|
266
273
|
visibility?: "internal" | "public";
|
|
267
274
|
x402?: { readonly price: number | string };
|
|
268
275
|
}
|
|
269
276
|
|
|
270
277
|
/** Static, codegen-derived facts. Request gates can inspect these without evaluating a user module. */
|
|
271
|
-
export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${
|
|
278
|
+
export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${R}};
|
|
272
279
|
|
|
273
|
-
const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${
|
|
280
|
+
const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${x}};
|
|
274
281
|
const loadedModules = new Map<string, Promise<Record<string, unknown>>>();
|
|
275
282
|
const resolvedModules = new Map<string, Record<string, unknown>>();
|
|
276
283
|
const boundFunctions = new Set<string>();
|
|
@@ -280,8 +287,8 @@ const unloadedFunctionHandler = (): never => {
|
|
|
280
287
|
|
|
281
288
|
/** Reuse an evaluated module synchronously, so dispatch does not yield after restoring request scope. */
|
|
282
289
|
export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunction | undefined => {
|
|
283
|
-
const registered = ${
|
|
284
|
-
const manifest = ${
|
|
290
|
+
const registered = ${S("LUNORA_FUNCTIONS")};
|
|
291
|
+
const manifest = ${S("LUNORA_FUNCTION_MANIFEST")};
|
|
285
292
|
|
|
286
293
|
if (!registered || !manifest) {
|
|
287
294
|
return registered;
|
|
@@ -312,7 +319,7 @@ export const getLoadedFunction = (functionPath: string): RegisteredLunoraFunctio
|
|
|
312
319
|
/** Load one function's owning module once per isolate, then merge its live builder result into the registry entry. */
|
|
313
320
|
export const loadFunction = async (functionPath: string): Promise<RegisteredLunoraFunction | undefined> => {
|
|
314
321
|
const registered = getLoadedFunction(functionPath);
|
|
315
|
-
const manifest = ${
|
|
322
|
+
const manifest = ${S("LUNORA_FUNCTION_MANIFEST")};
|
|
316
323
|
|
|
317
324
|
if (registered || !manifest) {
|
|
318
325
|
return registered;
|
|
@@ -339,7 +346,7 @@ export const loadFunction = async (functionPath: string): Promise<RegisteredLuno
|
|
|
339
346
|
return getLoadedFunction(functionPath);
|
|
340
347
|
};
|
|
341
348
|
|
|
342
|
-
`:"",
|
|
349
|
+
`:"",he=o&&R!==""?`
|
|
343
350
|
/**
|
|
344
351
|
* Evaluate every lazy module now and report the ones that fail, keyed by function path. A lazy
|
|
345
352
|
* registry defers a broken module's error to its first call; \`lunora build\` and \`deploy\` run this
|
|
@@ -365,9 +372,9 @@ export const loadAllFunctions = async (): Promise<{ checked: number; failures: R
|
|
|
365
372
|
|
|
366
373
|
return { checked: functionPaths.length, failures };
|
|
367
374
|
};
|
|
368
|
-
`:"";return
|
|
375
|
+
`:"";return ke(`${U}${f}${w.importLine}${O.importLine}${ne}${K}${T.typeImport}import { LunoraError } from "${l.server}";
|
|
369
376
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
370
|
-
${
|
|
377
|
+
${ie}
|
|
371
378
|
/**
|
|
372
379
|
* Single registered function, narrowed to the shape \`handleRpc\` needs.
|
|
373
380
|
* The real argument validators / return types are checked elsewhere — at
|
|
@@ -396,8 +403,8 @@ export interface RegisteredLunoraFunction {
|
|
|
396
403
|
* \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
|
|
397
404
|
* to. \`whisper\` does have one — it runs under the asking socket's identity.
|
|
398
405
|
*/
|
|
399
|
-
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${
|
|
400
|
-
${
|
|
406
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${I};${te}
|
|
407
|
+
${T.channelField} /**
|
|
401
408
|
* Hoisted by the builder when the \`.use()\` chain carries a step with a
|
|
402
409
|
* per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
|
|
403
410
|
* captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
|
|
@@ -413,13 +420,13 @@ ${L.channelField} /**
|
|
|
413
420
|
*/
|
|
414
421
|
x402?: { readonly price: number | string };
|
|
415
422
|
${m}}
|
|
416
|
-
${
|
|
423
|
+
${w.prelude}${O.prelude}${ue}${he}
|
|
417
424
|
/**
|
|
418
425
|
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
419
426
|
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
420
427
|
*/
|
|
421
|
-
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${
|
|
422
|
-
${
|
|
428
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${A}};
|
|
429
|
+
${oe}${Y}${Z}${X}${ee}${T.messagesBlock}${re}
|
|
423
430
|
/**
|
|
424
431
|
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
425
432
|
* client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
|
|
@@ -437,11 +444,11 @@ export const LUNORA_LIFECYCLE_HOOKS: {
|
|
|
437
444
|
reactor: readonly string[];
|
|
438
445
|
whisper: readonly string[];
|
|
439
446
|
} = {
|
|
440
|
-
connect: [${b.connect.map(
|
|
441
|
-
disconnect: [${b.disconnect.map(
|
|
442
|
-
init: [${b.init.map(
|
|
443
|
-
reactor: [${b.reactor.map(
|
|
444
|
-
whisper: [${b.whisper.map(
|
|
447
|
+
connect: [${b.connect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
448
|
+
disconnect: [${b.disconnect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
449
|
+
init: [${b.init.map(h=>JSON.stringify(h)).join(", ")}],
|
|
450
|
+
reactor: [${b.reactor.map(h=>JSON.stringify(h)).join(", ")}],
|
|
451
|
+
whisper: [${b.whisper.map(h=>JSON.stringify(h)).join(", ")}],
|
|
445
452
|
};
|
|
446
453
|
|
|
447
454
|
/**
|
|
@@ -451,7 +458,7 @@ export const LUNORA_LIFECYCLE_HOOKS: {
|
|
|
451
458
|
* functions are treated as not-found so their existence never leaks to clients.
|
|
452
459
|
*/
|
|
453
460
|
export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
|
|
454
|
-
${
|
|
461
|
+
${V} const registered = ${G};
|
|
455
462
|
|
|
456
463
|
if (!registered || registered.visibility === "internal") {
|
|
457
464
|
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
@@ -472,10 +479,10 @@ export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
|
472
479
|
* with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
|
|
473
480
|
* \`runAction\` but without re-stating the function path.
|
|
474
481
|
*/
|
|
475
|
-
export interface Caller {${
|
|
482
|
+
export interface Caller {${de}}
|
|
476
483
|
|
|
477
|
-
${
|
|
478
|
-
export const createCaller = (${
|
|
484
|
+
${ae}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
485
|
+
export const createCaller = (${le}: CallerCtx): Caller => ({${ce}});
|
|
479
486
|
|
|
480
487
|
/**
|
|
481
488
|
* Single registered data migration, narrowed to the shape the per-shard runner
|
|
@@ -494,13 +501,13 @@ export interface RegisteredDataMigration {
|
|
|
494
501
|
* Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
|
|
495
502
|
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
496
503
|
*/
|
|
497
|
-
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${
|
|
498
|
-
`,c)},
|
|
499
|
-
`:"",
|
|
500
|
-
`:"",
|
|
504
|
+
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${P}};
|
|
505
|
+
`,c)},Ve="fn",Ke=t=>{if(t.lazyFunctions!==!0)return{};const{functions:r}=t,n=t.migrations??[],o=t.mutators??[],s=t.shapes??[],i=W(r,n,o,s),a=Q(r,n,o,s),c=[...new Set(r.filter(d=>!a.has(d.filePath)).map(d=>d.filePath))],u=J(t.useUmbrella??!1),l={};for(const d of c){if(!F.test(d))throw new L("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(d)}`);const f=i.get(d)??"",y=`../../${d}.js`,$=r.filter(p=>p.filePath===d&&!p.lifecycle&&Object.keys(p.args).length>0).flatMap(p=>{const w=z(p.args);return w===void 0?[]:[`installCompiledValidatorMap(${f}.${p.exportName}.args, ${w});`]}),R=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
|
|
506
|
+
`:"",P=$.length>0?`import * as ${f} from "${y}";
|
|
507
|
+
`:"",x=$.length>0?`
|
|
501
508
|
/** Install the precompiled argument parsers before the module is dispatched. */
|
|
502
|
-
${
|
|
509
|
+
${$.join(`
|
|
503
510
|
`)}
|
|
504
|
-
`:"",v=
|
|
505
|
-
`:"";l[`${f}.ts`]=`${
|
|
506
|
-
${v}`}return l};export{
|
|
511
|
+
`:"",v=r.some(p=>p.filePath===d&&p.exportName==="default")||n.some(p=>p.filePath===d&&p.exportName==="default")?`export { default } from "${y}";
|
|
512
|
+
`:"";l[`${f}.ts`]=`${U}${R}${P}${x}export * from "${y}";
|
|
513
|
+
${v}`}return l};export{Ve as LAZY_FUNCTION_DIRECTORY,Ge as emitFunctions,Ke as emitLazyFunctionModules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{e}from"./server-
|
|
1
|
+
import"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{e}from"./server-qWq5nN-R.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-BqfSKnmG.mjs";import"./shard-runtime-C1P_uVye.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s}from"ts-morph";import{
|
|
1
|
+
import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-CTMkuBkn.mjs";import{c as n}from"./classify-procedure-call-DtqiTjPg.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-JdN4KXhV.mjs";import{r as v,h}from"./attribution-CTMkuBkn.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=h(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-JdN4KXhV.mjs";import{
|
|
1
|
+
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-JdN4KXhV.mjs";import{j as m,h as p}from"./attribution-CTMkuBkn.mjs";import{t as d}from"./database-calls-Cn47SfSU.mjs";import{w as g,c as h}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as k}from"./property-name-7cBlgK_O.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-JdN4KXhV.mjs";import{e as K,i as S}from"./attribution-CTMkuBkn.mjs";import{u as R,p as q,r as Y,c as O,a as G}from"./unwrap-handler-return-c2s2-nk9.mjs";import{m as J}from"./ip-reads-Dotjify6.mjs";import{b as N,s as X,c as Q}from"./classify-procedure-call-DtqiTjPg.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./static-literal-BwDHHjEJ.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const w=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=w(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?w(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of N(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=N(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},A=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},I=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=A(t,"scope"),o=I(t,"maxAge"),r=I(t,"staleWhileRevalidate"),a=A(t,"tag"),l=A(t,"vary"),c={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=N(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=N(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},p=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},x=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return p(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return p(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return p(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=x(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return p(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return p(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return p(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return p(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():p(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=x(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?p(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=x(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?p(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return p(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return p(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),b=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=b(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},tt=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(d=>U(d.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(d=>be(d)))continue;const c=n.getName(),u=a.map(d=>d.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${c} ships functions (${u}) that nothing re-exports, so none is in the generated api. Add \`export const { ${u} } = ${c}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,E=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:v(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},v=(e,i,t)=>{if(t>Ae)return E(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?b(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?E(e,i):{inner:v(a,i,t+1),kind:"array"}}return Te(e,i,t)??E(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(c=>c.isBooleanLiteral()).map(c=>c.getText(i))).size===Ee.size,r=e.filter(c=>!(o&&c.isBooleanLiteral())).map(c=>v(c,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[l]=a;return a.length===1&&l!==void 0?l:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(c=>!c.isUndefined());if(!i&&r.length===o.length)return v(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?v(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const l=b(o,"lifecycle",e),c=o.getProperty("lifecycle");if(l===void 0&&c!==void 0&&!c.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(l!==void 0){if(!Ne.has(l))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${l}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:l,returnType:"void",visibility:"internal"}}const u=b(o,"visibility",e);if(u!=="internal"&&u!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(u==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const d=o.getProperty("args")?.getTypeAtLocation(e);if(d===void 0||d.isAny()||d.isUnknown()||d.getStringIndexType()!==void 0||d.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const f=Object.fromEntries(d.getProperties().map(m=>[m.getName(),xe(m.getTypeAtLocation(e),e)]));return{...a,args:f,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:u}},ke=8,L=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return L(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?P(t,i+1):void 0},P=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?L(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?P(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?P(r,i+1):void 0}return{deadEnd:e}},T=e=>{const i=L(e);return i!==void 0&&"call"in i?i.call:void 0},k=e=>{const i=L(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(l=>i(l.getName()))){const l=T(a.getNameNode());l&&r.push([a.getName(),l])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:T(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&k(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&k(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(c=>s.isSpreadAssignment(c)||s.isPropertyAssignment(c)&&s.isComputedPropertyName(c.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const l=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(l===void 0||!(s.isTrueLiteral(l)||s.isFalseLiteral(l)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(l),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),l=O(()=>ae(i)),c=O(()=>oe(e)),u=z({kind:t.kind,output:l.value});return G(u?l.erased:c.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...l.value?{output:l.value}:{},returnType:c.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),_=(e,i)=>V(e.getVariableStatements().find(t=>t.isExported()&&t.getDeclarations().some(n=>n.getName()===i))),j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},je=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=T(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},Be=(e,i,t)=>{const n=K(e),o=new Map,r=(c,u)=>{if(c?.channel?.kind!=="room")return;const d=o.get(c.channel.name);if(d!==void 0&&d!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${c.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);o.set(c.channel.name,u)},a=e.getVariableStatements().flatMap(c=>c.getDeclarations()).flatMap(c=>_e(c,u=>n.has(u))).flatMap(([c,u])=>(n.get(c)??[]).filter(d=>S(d)).flatMap(d=>{const f=j(u,d,i,t,_(e,d));return r(f,u),f?[f]:[]})),l=new Set(a.map(c=>c.exportName));for(const c of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,d]of Re(c,f=>n.has(f)))for(const f of(n.get(u)??[]).filter(m=>S(m)&&!l.has(m))){const m=Ie(d,f,i,_(e,f));m&&(a.push(m),l.add(f))}for(const{call:c,entry:u}of je(e,i,t))l.has(u.exportName)||(r(u,c),a.push(u));return a},ze=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},He=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,t.filePath],status:500});i.set(n,t.filePath)}},it=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),l=W(i,r);o.push(...Be(a,l,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),He(o),ze(o),o};export{it as d,w as i,ne as p,tt as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-DtpwprsY.mjs";const o=/rate|limit|\bip\b|geo|throttle/iu,a=/^run[A-Z]/u,l=t=>s.isIdentifier(t)?(t.getSymbol()?.getDeclarations()??[]).some(r=>r.getFirstAncestorByKind(i.ImportDeclaration)?.getModuleSpecifierValue().startsWith("@lunora/")===!0):!1,c=t=>{const e=s.isCallExpression(t)?t.getExpression():t;let r;return s.isIdentifier(e)?r=e:s.isPropertyAccessExpression(e)&&(r=e.getNameNode()),r!==void 0&&l(s.isPropertyAccessExpression(e)?e.getExpression():r)&&!o.test(r.getText())},p=t=>{const e=s.isCallExpression(t)?t.getExpression():void 0;if(s.isElementAccessExpression(e)){const r=e.getArgumentExpression();return(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))&&r.getLiteralText()==="use"}return s.isPropertyAccessExpression(e)&&e.getName()==="use"},g=t=>{const e=t.getParent();return s.isPropertyAccessExpression(e)&&e.getExpression()===t?!a.test(e.getName()):s.isElementAccessExpression(e)&&e.getExpression()===t?s.isStringLiteral(e.getArgumentExpression())||s.isNoSubstitutionTemplateLiteral(e.getArgumentExpression()):s.isVariableDeclaration(e)&&e.getInitializer()?.getText()===t.getText()},u=t=>{if(s.isPropertyAccessExpression(t))return t.getName()==="ip";if(s.isElementAccessExpression(t)){const e=t.getArgumentExpression();return(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralText()==="ip"}return s.isBindingElement(t)?t.getDotDotDotToken()!==void 0||(t.getPropertyNameNode()?.getText()??t.getName())==="ip":s.isShorthandPropertyAssignment(t)&&t.getName()==="ip"},A=t=>{for(const e of t.getDescendants()){if(u(e)||p(e)&&!c(e.getArguments()[0]))return!0;if(s.isIdentifier(e)&&n(e)&&!g(e)){const r=e.getParent();if(!(s.isParameterDeclaration(r)||s.isBindingElement(r)||s.isVariableDeclaration(r)))return!0}}return!1};export{A as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-
|
|
1
|
+
import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-DhqnD5R3.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as N,u as Ke,d as Ue}from"./shared-
|
|
1
|
+
import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as N,u as Ke,d as Ue}from"./shared-DhqnD5R3.mjs";import{p as Je}from"./platform-8oj7iXQy.mjs";const me=/(?:\.d)?\.([cm]?)tsx?$/u,ze=t=>t.replace(me,".d.$1ts"),ye=(t,o)=>{const a=y(t,o).split(ue).join("/").replace(me,".$1js");return a.startsWith(".")?a:`./${a}`},he=t=>t.replaceAll("\\","/"),Y=(t,o,a)=>he(h(t,ze(y(o,a)))),Ye=t=>ye(".",h("services",t.name,y(d(t.wranglerPath),t.main))),Xe=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},T=t=>{const{mtimeMs:o,size:a}=Le(t);return`${String(o)}:${String(a)}`},Ze=new Set([".git",".wrangler","dist","node_modules","target"]),fe=t=>de(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${ce(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${T(a)}`,...fe(a)]:[]}),be=t=>[`${t}:${T(t)}`,...fe(t)],ge=t=>{const o=h(t,"node_modules"),a=D(o)?be(o):[],e=d(t);return e===t?a:[...a,...ge(e)]},et=(t,o)=>{const a=[];try{const e=s=>{for(const n of de(s,{withFileTypes:!0})){const l=h(s,n.name);if(l!==o)if(n.isSymbolicLink())a.push(`${l}->${ce(l)}`);else if(n.isDirectory()){if(n.name==="node_modules")a.push(...be(l));else if(!Ze.has(n.name)){if(!qe(l).isDirectory())throw new Error(`${l} changed during the scan`);e(l)}}else a.push(`${l}:${T(l)}`)}};e(t),a.push(...ge(t))}catch{return}return[...new Set(a)].toSorted((e,s)=>e.localeCompare(s)).join(`
|
|
2
2
|
`)},tt=t=>Ge(d(t)).startsWith("@")?d(d(t)):d(t),se=(t,o)=>!y(o,t).startsWith("..")&&!t.split(ue).includes("node_modules"),ie=(t,o)=>{const a=[];let e=t;for(;e!==d(e)&&!D(h(e,"package.json"));)a.push(e),e=d(e);if(D(h(e,"package.json"))){for(const s of[...a,e,h(e,"package.json")])o.add(s);return e}},at=(t,o,a)=>{let e=t;for(;y(e,o).startsWith("..")&&e!==d(e);)a.add(e),e=d(e);a.add(e)},rt=(t,o)=>{const a=new Set;t.some(e=>se(e,o))&&ie(o,a);for(const e of t){if(se(e,o)){for(let n=d(e);n!==o&&n!==d(n);n=d(n))a.add(n);continue}const s=ie(d(e),a);s===void 0?at(d(e),o,a):a.add(tt(s))}return[...a].map(e=>[e,T(e)])},xe=new Map,le=([t,o])=>{try{return T(t)===o}catch{return!1}},ot=(t,o,a)=>{const e=xe.get(t);return e?.optionsKey===o&&e.stamps.every(n=>le(n))&&e.directories.every(n=>le(n))&&a!==void 0&&e.tree===a?e.files:void 0},nt=(t,o,a)=>{const e=[...o.stamps,...o.directories].every(([,s])=>Math.floor(Number.parseFloat(s))<=a);o.tree!==void 0&&e&&xe.set(t,{...o,tree:o.tree})},st=(t,o)=>({directories:rt(o,t),stamps:o.map(a=>[a,T(a)])}),ht=(t,o)=>{const a=d(t.wranglerPath),e=y(a,t.main);if(e.startsWith("..")||_e(e))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const s=h(o,"services",t.name),n=c.findConfigFile(a,i=>c.sys.fileExists(i)),l=new He({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:s,rootDir:a},skipAddingFilesFromTsConfig:!0,...n===void 0?{}:{tsConfigFilePath:n}}),m=JSON.stringify([t.name,t.main,t.wranglerPath,o]),v=JSON.stringify(l.getCompilerOptions()),w=et(a,Ve(o)),g=ot(m,v,w);if(g!==void 0)return g;const A=Date.now();l.addSourceFileAtPath(t.main),l.resolveSourceFileDependencies();const $=l.getProgram().compilerObject.getSourceFiles().map(i=>i.fileName).filter(i=>D(i)),{directories:F,stamps:S}=st(a,$),u={...l.getCompilerOptions(),preserveSymlinks:!0},O=new Map(l.getSourceFiles().map(i=>i.getFilePath()).filter(i=>!i.endsWith(".d.ts")&&!y(a,i).startsWith("..")).map(i=>[Y(s,a,i),i])),f={};for(const i of l.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const B=O.get(he(i.filePath));if(B===void 0)continue;const R=c.createSourceFile(i.filePath,i.text,c.ScriptTarget.Latest,!1);let{text:b}=i;for(const k of Xe(R).toReversed()){const x=c.resolveModuleName(k.text,B,u,c.sys).resolvedModule?.resolvedFileName;if(x===void 0)continue;const I=Y(s,a,x),W=O.has(I)?I:x;b=`${b.slice(0,k.getStart(R))}${JSON.stringify(ye(d(i.filePath),W))}${b.slice(k.getEnd())}`}f[y(o,i.filePath)]=`${pe}${b}`}if(f[y(o,Y(s,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return nt(m,{files:f,optionsKey:v,directories:F,stamps:S,tree:w},A),f},it=(t,o=[])=>{const a=new Set;for(const e of t.tables)for(const s of Object.values(e.shape)){const n=Ke(s);n.kind==="storage"&&typeof n.bucket=="string"&&n.bucket!==""&&a.add(n.bucket)}for(const e of o)e!==""&&e!=="default"&&a.add(e);return["default",...[...a].toSorted((e,s)=>e.localeCompare(s))]},ft=({agents:t=[],capabilities:o=new Set,containers:a=[],env:e,hasVectors:s=!0,hasFlags:n=!1,hasNotify:l=!1,identity:m,queues:v=[],schema:w,services:g=[],storageRuleBuckets:A=[],topics:$=[],useUmbrella:F=!1,workflows:S=[]}={})=>{const u=Ue(F),O=it(w??{tables:[]},A).map(r=>JSON.stringify(r)).join(" | "),f=r=>r.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",i=[...new Set(a.map(r=>f(r)))].toSorted((r,p)=>r.localeCompare(p)),B=a.length>0?`import type { ${i.join(", ")} } from "@lunora/container";
|
|
3
3
|
`:"",R=a.length>0?`
|
|
4
4
|
readonly containers: {${a.map(r=>`
|