@lunora/codegen 1.0.0-alpha.190 → 1.0.0-alpha.192
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 +8 -7
- package/dist/index.d.ts +8 -7
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-DycP5oCG.mjs → GENERATED_HEADER-VOvxb_1e.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-CZh4jN4q.mjs → NOTIFY_FILENAME-Bgq52CnU.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-BNobmd0k.mjs → OPENRPC_VERSION-COQLvoDY.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-DLqvtzGf.mjs → SCHEMA_SNAPSHOT_FILENAME-CuWCb603.mjs} +4 -4
- package/dist/packem_shared/{buildOpenApiDocument-BomWVHVV.mjs → buildOpenApiDocument-D_-3ZGH1.mjs} +1 -1
- package/dist/packem_shared/chain-BWtZ1NER.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-BIlyTUBD.mjs +1 -0
- package/dist/packem_shared/{context-property-calls-Ce9xGl_o.mjs → context-property-calls-H37QsE0Q.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-DB9G_XrW.mjs → discoverFunctions-C9O2RBTz.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DP3Vb0HC.mjs +1 -0
- package/dist/packem_shared/{discoverMaskProcedures-BLAzNB90.mjs → discoverMaskProcedures-CNkhbP5z.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-DkVVHe3U.mjs → discoverNondeterministicCalls-Dy6k2aPS.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-FaK1-wbV.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-CwWRPb8N.mjs → discoverRlsMetadata-DwULXx5T.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-vJZq3yhb.mjs → discoverRlsProcedures-D_J8cH-m.mjs} +1 -1
- package/dist/packem_shared/{discoverStorageRulesMetadata-xhxu-mkS.mjs → discoverStorageRulesMetadata-C3ywuLJd.mjs} +1 -1
- package/dist/packem_shared/{emit-B_n-PvH3.mjs → emit-CTDEkEXh.mjs} +59 -50
- package/dist/packem_shared/{emitApp-DvDGeMCt.mjs → emitApp-DLEEN6Yy.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-C9FHwphy.mjs → exported-procedure-chains-Bqdp4ywr.mjs} +1 -1
- package/dist/packem_shared/{index-D_Z8rX-f.mjs → index-C4eKBBMk.mjs} +1 -1
- package/package.json +4 -4
- package/dist/packem_shared/chain-Dp_6wzI9.mjs +0 -1
- package/dist/packem_shared/classify-procedure-call-C8jbo0IJ.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DgAYcZRD.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-6u0OKy2N.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as l,handlerOf as d}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{c as f}from"./classify-procedure-call-
|
|
1
|
+
import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as l,handlerOf as d}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{c as f}from"./classify-procedure-call-BIlyTUBD.mjs";const u={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},m=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),p=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},h=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=p(t.getExpression());if(i!==void 0)return n==="fetch"&&m.has(i)?"fetch":u[`${i}.${n}`]},x=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},N=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=f(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=d(t,n.receiver);return i?{exportName:e.getName(),handler:i,kind:n.kind}:void 0},E=(e,t)=>{const n=[];for(const i of e.handler.getDescendantsOfKind(a.CallExpression)){const o=h(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}for(const i of e.handler.getDescendantsOfKind(a.NewExpression)){const o=x(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}return n},S=(e,t)=>{const n=[];for(const i of e.getVariableStatements())if(i.isExported())for(const o of i.getDeclarations()){const r=N(o);r&&n.push(...E(r,t))}return n},w=(e,t)=>{const n=[];for(const i of c(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,l(t,i)))}return n};export{w as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as r}from"./context-property-calls-H37QsE0Q.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|
package/dist/packem_shared/{discoverRlsMetadata-CwWRPb8N.mjs → discoverRlsMetadata-DwULXx5T.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as d,lunoraRelativePath as x,stringPropertyOf as c}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{e as h}from"./exported-procedure-chains-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as d,lunoraRelativePath as x,stringPropertyOf as c}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{e as h}from"./exported-procedure-chains-Bqdp4ywr.mjs";import{r as A}from"./chain-BWtZ1NER.mjs";const L=new Set(["delete","insert","read","update"]),P=(e,t,i)=>{const r=e.getArguments()[0];if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){if(!o.isObjectLiteralExpression(n))continue;const a=c(n,"on");a===void 0||!L.has(a)||s.push({file:t,on:a,procedure:i,table:c(n,"table")??""})}return s},u=e=>{if(!o.isObjectLiteralExpression(e))return[];const t=e.getProperty("permissions");if(!t||!o.isPropertyAssignment(t))return[];const i=t.getInitializer();if(!i||!o.isArrayLiteralExpression(i))return[];const r=[];for(const s of i.getElements()){if(o.isStringLiteral(s)){r.push(s.getLiteralText());continue}if(o.isCallExpression(s)){const n=s.getArguments()[0];n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}}return r},f=(e,t)=>t===void 0?e:{...e,description:t},E=e=>{if(o.isCallExpression(e)){const t=e.getArguments()[0];if(!t||!o.isStringLiteral(t))return;const i=e.getArguments()[1],r=i?c(i,"description"):void 0,s=i?u(i):[];return f({name:t.getLiteralText(),permissions:s},r)}if(o.isObjectLiteralExpression(e)){const t=c(e,"name");return t===void 0?void 0:f({name:t,permissions:u(e)},c(e,"description"))}},v=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const i=t.getProperty("roles");if(!i||!o.isPropertyAssignment(i))return[];const r=i.getInitializer();if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){const a=E(n);a&&s.push(a)}return s},y=(e,t,i)=>{const r=A(e);return{policies:r.flatMap(s=>P(s,t,i)),roles:r.flatMap(s=>v(s))}},F=(e,t)=>{const i=[],r=new Map;for(const s of d(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=x(t,s);for(const{name:m,receiver:g}of h(n)){const p=y(g,a,m);i.push(...p.policies);for(const l of p.roles)r.has(l.name)||r.set(l.name,l)}}return{policies:i,roles:[...r.values()]}};export{F as default};
|
package/dist/packem_shared/{discoverRlsProcedures-vJZq3yhb.mjs → discoverRlsProcedures-D_J8cH-m.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,tablesAccessedIn as d}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{c as p}from"./classify-procedure-call-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,tablesAccessedIn as d}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{c as p}from"./classify-procedure-call-BIlyTUBD.mjs";import{r as m}from"./chain-BWtZ1NER.mjs";const b=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const s=[];for(const r of t.getElements()){if(!o.isObjectLiteralExpression(r))continue;const i=r.getProperty("table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&s.push(n.getLiteralText())}return s},g=e=>{const t=m(e);return{rlsTables:t.flatMap(s=>b(s)),usesRls:t.length>0}},h=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),y=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),v=(e,t)=>{if(!o.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=p(s);if(!r)return;const i=r.receiver?g(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:l}=d(e,h,y);return{exportName:e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:l,usesRls:i.usesRls,visibility:r.visibility}},S=(e,t)=>{const s=[];for(const r of f(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=u(t,r);for(const l of i.getVariableStatements())if(l.isExported())for(const c of l.getDeclarations()){const a=v(c,n);a&&s.push(a)}}return s};export{S as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{w as d}from"./classify-procedure-call-
|
|
1
|
+
import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{w as d}from"./classify-procedure-call-BIlyTUBD.mjs";import{e as m}from"./exported-procedure-chains-Bqdp4ywr.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,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Nn,isD1GlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as
|
|
1
|
+
import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Nn,isD1GlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as A}from"./paths-C-9fwEgQ.mjs";import{acceptsAbsentIr as On}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const mt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access",requiredPackage:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai",requiredPackage:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
|
|
2
2
|
/** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
|
|
3
3
|
readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",requiredPackage:"@lunora/browser",serverCtxField:{field:`
|
|
4
4
|
/** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
|
|
@@ -44,12 +44,12 @@ ${yt("source")}${r.pre}return { ${r.entries} };
|
|
|
44
44
|
}`},S=`// GENERATED by @lunora/codegen — do not edit.
|
|
45
45
|
// Run \`lunora codegen\` to regenerate.
|
|
46
46
|
|
|
47
|
-
`,oe=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},wt=/^[A-Za-z_$][\w$]*$/u,jn=/^[\w./-]+$/u,f=(e,t)=>{if(!wt.test(e))throw new X("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ve=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>wt.test(e)?e:JSON.stringify(e),Y=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),Wn={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},Un=e=>{if(e===void 0)return"unknown";if(!gt.test(e))throw new X("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},
|
|
47
|
+
`,oe=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},wt=/^[A-Za-z_$][\w$]*$/u,jn=/^[\w./-]+$/u,f=(e,t)=>{if(!wt.test(e))throw new X("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ve=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>wt.test(e)?e:JSON.stringify(e),Y=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),Wn={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},Un=e=>{if(e===void 0)return"unknown";if(!gt.test(e))throw new X("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},N=e=>{const t=Wn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?N(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return f(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Un(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,a])=>kt(r,a)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?N(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?N(e.keyType):"string",r=e.valueType?N(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>N(n)).join(" | "):"never";default:return"unknown"}},kt=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?N(t.inner):"unknown";return`${n}?: ${r}`}return On(t)?`${n}?: ${N(t)}`:`${n}: ${N(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>kt(n,r)).join("; ")} }`},xt=e=>e.kind==="optional"||!!e.column?.hasDefault,se=e=>e.kind==="optional"&&e.inner?e.inner:e,Kn=e=>{f(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=se(a),i=N(o),s=q(r);return xt(a)?` ${s}?: ${i};`:` ${s}: ${i};`}).join(`
|
|
48
48
|
`),n=t?`
|
|
49
49
|
${t}
|
|
50
50
|
`:"";return`export interface Insert_${e.name} {
|
|
51
51
|
_id?: Id<"${e.name}">;
|
|
52
|
-
_creationTime?: number;${n}}`},Je="schema",da=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const $=q(x);if(v.kind==="optional"){const
|
|
52
|
+
_creationTime?: number;${n}}`},Je="schema",da=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const $=q(x);if(v.kind==="optional"){const T=v.inner?N(v.inner):"unknown";return` ${$}?: ${T};`}return` ${$}: ${N(v)};`}).join(`
|
|
53
53
|
`),b=l?`
|
|
54
54
|
${l}
|
|
55
55
|
`:"",R=u.commitOrdered===!0?`
|
|
@@ -161,8 +161,8 @@ export interface Relations {
|
|
|
161
161
|
${y}
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
`,Je)},Qn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,vt=/^(?:\.\.?\/)*_generated\//u,St=/\.[A-Za-z]\w*$/u,Hn=e=>e.replaceAll(Qn,(t,n)=>{const r=n.replace(vt,"./");return`import("${St.test(r)?r:`${r}.js`}")`}),Vn=/import\("(?<spec>[^"]+)"\)/gu,dt="node_modules/",Gn=/^@types\//u,Jn=e=>e.replaceAll(Vn,(t,n)=>{const r=n.lastIndexOf(dt);if(r===-1||r>0&&n[r-1]!=="/")return t;const a=n.slice(r+dt.length);return a===""||Gn.test(a)?t:`import("${a}")`}),zn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Yn=/^(?:\.\.?\/)+/u,Xn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Zn=(e,t)=>e.replaceAll(zn,(n,r)=>{if(vt.test(r.replace(Yn,"")))return n;const a=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Xn(`${a}/${r}`)}`;return`import("${St.test(i)?i:`${i}.js`}")`}),L=(e,t)=>Hn(Zn(Jn(e),t)),er=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],tr=new RegExp(String.raw`import\("@lunora/(?<pkg>${er.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),nr={flags:new Set(["/web"]),platform:new Set},Rt=(e,t)=>t?e.replaceAll(tr,(n,r,a)=>{const o=nr[r];return a&&o&&!o.has(a)?n:`import("lunorash/${r}${a??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),$t=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:
|
|
165
|
-
`);return` ${q(
|
|
164
|
+
`,Je)},Qn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,vt=/^(?:\.\.?\/)*_generated\//u,St=/\.[A-Za-z]\w*$/u,Hn=e=>e.replaceAll(Qn,(t,n)=>{const r=n.replace(vt,"./");return`import("${St.test(r)?r:`${r}.js`}")`}),Vn=/import\("(?<spec>[^"]+)"\)/gu,dt="node_modules/",Gn=/^@types\//u,Jn=e=>e.replaceAll(Vn,(t,n)=>{const r=n.lastIndexOf(dt);if(r===-1||r>0&&n[r-1]!=="/")return t;const a=n.slice(r+dt.length);return a===""||Gn.test(a)?t:`import("${a}")`}),zn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Yn=/^(?:\.\.?\/)+/u,Xn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Zn=(e,t)=>e.replaceAll(zn,(n,r)=>{if(vt.test(r.replace(Yn,"")))return n;const a=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Xn(`${a}/${r}`)}`;return`import("${St.test(i)?i:`${i}.js`}")`}),L=(e,t)=>Hn(Zn(Jn(e),t)),er=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],tr=new RegExp(String.raw`import\("@lunora/(?<pkg>${er.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),nr={flags:new Set(["/web"]),platform:new Set},Rt=(e,t)=>t?e.replaceAll(tr,(n,r,a)=>{const o=nr[r];return a&&o&&!o.has(a)?n:`import("lunorash/${r}${a??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),$t=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:N(e.output),Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},ut=e=>{const t=([n,r])=>{const a=r.toSorted((o,i)=>o.exportName.localeCompare(i.exportName)).map(o=>{const i=L(xe(o.args),o.filePath),s=L($t(o),o.filePath);return` ${o.exportName}: FunctionReference<"${o.kind}", ${i}, ${s}>;`}).join(`
|
|
165
|
+
`);return` ${q(A(n))}: {
|
|
166
166
|
${a}
|
|
167
167
|
};`};return Ye(e).map(n=>t(n)).join(`
|
|
168
168
|
`)},rr=(e,t)=>{if(e.length===0&&t.length===0)return{block:"",importLine:""};const n=[];let r="";if(e.length>0&&(r+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),r+=`
|
|
@@ -197,7 +197,7 @@ export const agents: AgentsRef = {
|
|
|
197
197
|
${i}
|
|
198
198
|
};
|
|
199
199
|
`,n.push(`import type { AgentRunInput } from "@lunora/agent";
|
|
200
|
-
`)}return{block:r,importLine:n.join("")}},ar=()=>Object.keys(pt().functions).toSorted((e,t)=>e.localeCompare(t)),Tt=e=>new Set(e.filter(t=>
|
|
200
|
+
`)}return{block:r,importLine:n.join("")}},ar=()=>Object.keys(pt().functions).toSorted((e,t)=>e.localeCompare(t)),Tt=e=>new Set(e.filter(t=>A(t.filePath)==="agents").map(t=>t.exportName)),or=()=>new Set(Object.entries(pt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),sr=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Tt(t),a=or(),o=t.find(s=>A(s.filePath)==="agents"&&a.has(s.exportName));if(o)throw new X("INTERNAL",`@lunora/codegen: "agents:${o.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${o.exportName}" export in ${o.filePath}`);const i=ar().filter(s=>!r.has(s));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
|
|
201
201
|
`,lines:i.map(s=>` "agents:${s}": lunoraAgentRuntimeFunctions.${s} as unknown as RegisteredLunoraFunction,`).join(`
|
|
202
202
|
`),prelude:`
|
|
203
203
|
/**
|
|
@@ -206,13 +206,13 @@ ${i}
|
|
|
206
206
|
* subscribe to the public queries (\`agents:agentMessages\` is the live thread view).
|
|
207
207
|
*/
|
|
208
208
|
const lunoraAgentRuntimeFunctions = agentComponent().functions;
|
|
209
|
-
`}},ir=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>
|
|
210
|
-
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},lr=(e,t)=>{if(e.length===0)return[];const n=Tt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const a of e)a.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${a.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(a=>!n.has(a.exportName))},cr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>
|
|
211
|
-
`);return` ${q(
|
|
209
|
+
`}},ir=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>A(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new X("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
|
|
210
|
+
`,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},lr=(e,t)=>{if(e.length===0)return[];const n=Tt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const a of e)a.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${a.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(a=>!n.has(a.exportName))},cr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>A(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},dr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,s])=>{const c=s.map(d=>{const h=L(d.chunkType??"unknown",d.filePath),g=L(xe(d.searchParams),d.filePath),y=L(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${h}, ${g}, ${y}>;`}).join(`
|
|
211
|
+
`);return` ${q(A(i))}: {
|
|
212
212
|
${c}
|
|
213
213
|
};`}).join(`
|
|
214
214
|
`),a=n.map(([i,s])=>{const c=s.map(d=>` ${Y(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
|
|
215
|
-
`);return` ${Y(
|
|
215
|
+
`);return` ${Y(A(i))}: {
|
|
216
216
|
${c}
|
|
217
217
|
},`}).join(`
|
|
218
218
|
`);return{block:`
|
|
@@ -240,7 +240,7 @@ export const api = anyApi as unknown as ApiTypes;
|
|
|
240
240
|
export interface InternalApiTypes {${x}}
|
|
241
241
|
|
|
242
242
|
export const internal = anyApi as unknown as InternalApiTypes;
|
|
243
|
-
${v.block}${y.block}`,
|
|
243
|
+
${v.block}${y.block}`,T=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],H=T.length>0?`import type { ${T.join(", ")} } from "${s.client}";
|
|
244
244
|
`:"";return Rt(`${S}import { anyApi } from "${s.client}";
|
|
245
245
|
${H}${v.importLine}${b}
|
|
246
246
|
${$}`,o)},ha=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
@@ -314,7 +314,7 @@ import type { Collection } from "@tanstack/db";
|
|
|
314
314
|
import { createCollection } from "@tanstack/db";
|
|
315
315
|
${s}
|
|
316
316
|
${o}
|
|
317
|
-
`},ur=(e,t)=>`lunora_${
|
|
317
|
+
`},ur=(e,t)=>`lunora_${A(e)}_${String(t)}`,hr=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
318
318
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
319
319
|
|
|
320
320
|
if (!registered) {
|
|
@@ -344,11 +344,11 @@ ${o}
|
|
|
344
344
|
|
|
345
345
|
return (await registered.handler(context, args ?? {})) as R;
|
|
346
346
|
};`,pr=(e,t,n=[],r=[])=>{const a=new Map,o=l=>{a.has(l)||a.set(l,ur(l,a.size))};for(const l of e)o(l.filePath);for(const l of t)o(l.filePath);for(const l of n)o(l.filePath);for(const l of r)o(l.filePath);const i=[...a.entries()].map(([l,b])=>{if(!jn.test(l))throw new X("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${b} from "../${l}.js";`}).join(`
|
|
347
|
-
`),s=e.map(l=>` "${
|
|
347
|
+
`),s=e.map(l=>` "${A(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
348
348
|
`),c=t.map(l=>` ${JSON.stringify(l.id)}: ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
349
|
-
`),d=n.map(l=>` "${
|
|
349
|
+
`),d=n.map(l=>` "${A(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
350
350
|
`),h=r.map(l=>` "${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
|
|
351
|
-
`),g=n.map(l=>`${
|
|
351
|
+
`),g=n.map(l=>`${A(l.filePath)}:${l.exportName}`),y=[s,d].filter(l=>l.length>0).join(`
|
|
352
352
|
`),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const b=qn(l.args);return b===void 0?void 0:`installCompiledValidatorMap(${a.get(l.filePath)??""}.${l.exportName}.args, ${b});`}).filter(l=>l!==void 0).join(`
|
|
353
353
|
`);return{dispatchBody:y.length>0?`
|
|
354
354
|
${y}
|
|
@@ -359,14 +359,14 @@ ${c}
|
|
|
359
359
|
`:"",mutatorPaths:g,shapeBody:h.length>0?`
|
|
360
360
|
${h}
|
|
361
361
|
`:""}},mr=e=>{const t=Ye(e),n=t.map(([a,o])=>{const i=o.map(s=>{const c=L(xe(s.args),s.filePath),d=c==="{}"?"?":"",h=L($t(s),s.filePath);return s.kind==="stream"?` ${s.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${h}>>;`:` ${s.exportName}: (args${d}: ${c}) => Promise<${h}>;`}).join(`
|
|
362
|
-
`);return` ${q(
|
|
362
|
+
`);return` ${q(A(a))}: {
|
|
363
363
|
${i}
|
|
364
364
|
};`}).join(`
|
|
365
|
-
`);return{implementation:t.map(([a,o])=>{const i=
|
|
365
|
+
`);return{implementation:t.map(([a,o])=>{const i=A(a),s=o.map(c=>` ${Y(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
|
|
366
366
|
`);return` ${Y(i)}: {
|
|
367
367
|
${s}
|
|
368
368
|
},`}).join(`
|
|
369
|
-
`),types:n}},gr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=se(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},ma=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasVectors:s=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:h=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:R=!1,identity:x,queues:v=[],schema:$,storageRuleBuckets:
|
|
369
|
+
`),types:n}},gr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=se(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},ma=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasVectors:s=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:h=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:R=!1,identity:x,queues:v=[],schema:$,storageRuleBuckets:T=[],useUmbrella:H=!1,workflows:O=[]}={})=>{const C=oe(H),k=gr($??{tables:[]},T).map(p=>JSON.stringify(p)).join(" | "),P=a?`import type { LunoraAi } from "@lunora/ai";
|
|
370
370
|
`:"",M=a?`
|
|
371
371
|
readonly ai: LunoraAi;`:"",ie=u?`import type { LunoraPayment } from "@lunora/payment";
|
|
372
372
|
`:"",le=u?`
|
|
@@ -376,7 +376,7 @@ ${s}
|
|
|
376
376
|
`:"",ee=t.length>0?`
|
|
377
377
|
readonly containers: {${t.map(p=>`
|
|
378
378
|
readonly ${p.exportName}: ContainerAccessor;`).join("")}
|
|
379
|
-
};`:"",
|
|
379
|
+
};`:"",w=[...a?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(p=>(f(p.bindingName,`container binding "${p.bindingName}"`),` /** Durable Object namespace for the \`${p.exportName}\` container. */
|
|
380
380
|
readonly ${p.bindingName}?: unknown;`)),...O.map(p=>(f(p.bindingName,`workflow binding "${p.bindingName}"`),` /** Workflow binding for the \`${p.exportName}\` workflow. */
|
|
381
381
|
readonly ${p.bindingName}?: unknown;`)),...v.map(p=>(f(p.bindingName,`queue binding "${p.bindingName}"`),` /** Queue producer binding for the \`${p.exportName}\` queue. */
|
|
382
382
|
readonly ${p.bindingName}?: unknown;`)),...e.map(p=>(f(p.bindingName,`agent binding "${p.bindingName}"`),` /** Workflow binding for the \`${p.exportName}\` agent. */
|
|
@@ -394,8 +394,8 @@ ${s}
|
|
|
394
394
|
* surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
|
|
395
395
|
*/
|
|
396
396
|
export interface CloudflareBindings {
|
|
397
|
-
readonly [binding: string]: unknown;${
|
|
398
|
-
${
|
|
397
|
+
readonly [binding: string]: unknown;${w?`
|
|
398
|
+
${w}`:""}
|
|
399
399
|
}
|
|
400
400
|
|
|
401
401
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
@@ -577,7 +577,7 @@ export interface OrmWriter extends OrmReader {
|
|
|
577
577
|
}
|
|
578
578
|
|
|
579
579
|
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
580
|
-
export type StorageBucketName = ${
|
|
580
|
+
export type StorageBucketName = ${k};${Ae}${De}${Ee}${Pe}${Fe}${je}
|
|
581
581
|
|
|
582
582
|
/**
|
|
583
583
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -730,12 +730,12 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Be}>();
|
|
|
730
730
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
731
731
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
732
732
|
};
|
|
733
|
-
`},fr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${
|
|
733
|
+
`},fr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${A(n.filePath)}:${n.exportName}`);return t},ga=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,c=n.length>0,d=oe(i),{dispatchBody:h,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=pr(n,r,a,o),R=sr(t,n),x=ir(s,n),v=[R.lines,x.lines].filter(w=>w.length>0).join(`
|
|
734
734
|
`);let $=h;v.length>0&&($=h.length>0?`${h.trimEnd()}
|
|
735
735
|
${v}
|
|
736
736
|
`:`
|
|
737
737
|
${v}
|
|
738
|
-
`);const
|
|
738
|
+
`);const T=fr(n),H=o.length>0?`import type { RegisteredShape } from "${d.server}";
|
|
739
739
|
`:"",O=o.length>0?`
|
|
740
740
|
/**
|
|
741
741
|
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
@@ -750,8 +750,8 @@ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${b}};
|
|
|
750
750
|
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
751
751
|
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
752
752
|
*/
|
|
753
|
-
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(
|
|
754
|
-
`:"",
|
|
753
|
+
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${l.map(w=>JSON.stringify(w)).join(", ")}]);
|
|
754
|
+
`:"",k=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
|
|
755
755
|
`:"",P=y.length>0?`
|
|
756
756
|
/**
|
|
757
757
|
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
@@ -766,7 +766,7 @@ ${M.implementation}
|
|
|
766
766
|
`:"",Z=ze(M.types),V=Z.length>0?`import type { ${Z.join(", ")} } from "./dataModel.js";
|
|
767
767
|
`:"",D=c?"context":"_context",ee=c?`${hr}
|
|
768
768
|
|
|
769
|
-
`:"";return Rt(`${S}${g}${R.importLine}${x.importLine}${
|
|
769
|
+
`:"";return Rt(`${S}${g}${R.importLine}${x.importLine}${k}${H}import { LunoraError } from "${d.server}";
|
|
770
770
|
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
771
771
|
${V}
|
|
772
772
|
/**
|
|
@@ -792,11 +792,12 @@ export interface RegisteredLunoraFunction {
|
|
|
792
792
|
handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
|
|
793
793
|
/**
|
|
794
794
|
* The lifecycle moment a hook fires on, when this registration came from
|
|
795
|
-
* \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`.
|
|
796
|
-
* dispatch to decide whether the function runs system-trusted:
|
|
797
|
-
* \`reactor\` have no caller identity, so RLS has no user to scope
|
|
795
|
+
* \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`/\`onWhisper\`.
|
|
796
|
+
* Read at dispatch to decide whether the function runs system-trusted:
|
|
797
|
+
* \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
|
|
798
|
+
* to. \`whisper\` does have one — it runs under the asking socket's identity.
|
|
798
799
|
*/
|
|
799
|
-
lifecycle?: "connect" | "disconnect" | "init" | "reactor";
|
|
800
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper";
|
|
800
801
|
/**
|
|
801
802
|
* Hoisted by the builder when the \`.use()\` chain carries a step with a
|
|
802
803
|
* per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
|
|
@@ -823,17 +824,25 @@ ${P}${O}${C}
|
|
|
823
824
|
/**
|
|
824
825
|
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
825
826
|
* client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
|
|
826
|
-
* per Durable Object instance before any handler runs (\`init\`),
|
|
827
|
-
* write flush when a watched read's result changed (\`reactor\`)
|
|
828
|
-
*
|
|
829
|
-
*
|
|
830
|
-
*
|
|
827
|
+
* per Durable Object instance before any handler runs (\`init\`), after a
|
|
828
|
+
* write flush when a watched read's result changed (\`reactor\`), and before a
|
|
829
|
+
* socket joins or broadcasts to a whisper topic (\`whisper\`). Each path also
|
|
830
|
+
* resolves through {@link LUNORA_FUNCTIONS}. The socket-scoped moments run under
|
|
831
|
+
* the socket's verified identity; \`init\` and \`reactor\` have no caller, so they
|
|
832
|
+
* run anonymous — all via system dispatch.
|
|
831
833
|
*/
|
|
832
|
-
export const LUNORA_LIFECYCLE_HOOKS: {
|
|
833
|
-
connect: [
|
|
834
|
-
disconnect: [
|
|
835
|
-
init: [
|
|
836
|
-
reactor: [
|
|
834
|
+
export const LUNORA_LIFECYCLE_HOOKS: {
|
|
835
|
+
connect: readonly string[];
|
|
836
|
+
disconnect: readonly string[];
|
|
837
|
+
init: readonly string[];
|
|
838
|
+
reactor: readonly string[];
|
|
839
|
+
whisper: readonly string[];
|
|
840
|
+
} = {
|
|
841
|
+
connect: [${T.connect.map(w=>JSON.stringify(w)).join(", ")}],
|
|
842
|
+
disconnect: [${T.disconnect.map(w=>JSON.stringify(w)).join(", ")}],
|
|
843
|
+
init: [${T.init.map(w=>JSON.stringify(w)).join(", ")}],
|
|
844
|
+
reactor: [${T.reactor.map(w=>JSON.stringify(w)).join(", ")}],
|
|
845
|
+
whisper: [${T.whisper.map(w=>JSON.stringify(w)).join(", ")}],
|
|
837
846
|
};
|
|
838
847
|
|
|
839
848
|
/**
|
|
@@ -1209,10 +1218,10 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
|
|
|
1209
1218
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1210
1219
|
: x402Stub;
|
|
1211
1220
|
`,configField:`
|
|
1212
|
-
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Hr=(e,t,n,r,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],ka=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:$=!1,maskMetadata:
|
|
1221
|
+
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Hr=(e,t,n,r,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],ka=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:$=!1,maskMetadata:T,mutators:H=[],queues:O=[],rlsMetadata:C,schema:k,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const D=oe(Z),ee=H.length>0,w=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
|
|
1213
1222
|
/** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
|
|
1214
1223
|
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Tn(P))}, json: ${JSON.stringify(Ae)} };
|
|
1215
|
-
`,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=$r(s),ue=Ir(i),G=Tr(u),_=Nr(h,D.flags),J=Cr(o,h,D.flags),te=Ar(l),he=Or(a),z=Dr(c),j=Lr(y),W=Er(g),U=_r(d),B=Pr(x),ne=Mr(R),{build:De,contextField:ve,importLines:Se,specs:pe}=qr(O),{build:Le,contextField:Ee,importLines:Re,specs:me}=Fr(r,
|
|
1224
|
+
`,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=$r(s),ue=Ir(i),G=Tr(u),_=Nr(h,D.flags),J=Cr(o,h,D.flags),te=Ar(l),he=Or(a),z=Dr(c),j=Lr(y),W=Er(g),U=_r(d),B=Pr(x),ne=Mr(R),{build:De,contextField:ve,importLines:Se,specs:pe}=qr(O),{build:Le,contextField:Ee,importLines:Re,specs:me}=Fr(r,k.jurisdiction),{build:_e,contextField:Pe,importLines:$e,specs:Me}=Br(V),{build:Fe,contextField:ge,importLines:fe,specs:Be}=jr(n),{build:qe,configField:je,contextField:be,imports:ye,stub:Ze}=Kr(b),{build:p,configField:We,imports:Te,stub:re}=Qr($),Ot=e,It=t,et=C??{policies:[],roles:[]},Ct=T??{columns:[]},Dt=ie??{rules:[]},Lt=le??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Et,override:_t}=Wr(V),{constant:Pt,override:Mt}=Ur(O),K=v&&k.vectorIndexes.length>0,tt=new Set(k.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&k.vectorIndexes.some(m=>tt.has(m.table)),we=k.tables.some(m=>m.shardMode==="global"),Ue=k.tables.some(m=>Nn(m)),nt=k.tables.some(m=>An(m)),ae=k.tables.some(m=>m.externalSource!==void 0),rt=k.tables.some(m=>m.memory===!0),Ke=k.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(nt&&Ue)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=k.tables.length>0,Ft=br(k),Bt=wr(k),qt=Sr(k),jt=yr(k),at=kr(k),ot=Hr(K,V.length>0,O.length>0,h,Ke);w&&ot.push("WhereInput");const st=Rr(we),Wt=w?`
|
|
1216
1225
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
1217
1226
|
const shape = LUNORA_SHAPES[name];
|
|
1218
1227
|
|
|
@@ -1276,20 +1285,20 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1276
1285
|
|
|
1277
1286
|
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
1278
1287
|
}
|
|
1279
|
-
`:"",it=
|
|
1288
|
+
`:"",it=w?[...new Set(et.policies.filter(m=>m.on==="read"&&m.table!=="").map(m=>m.table))].toSorted((m,Rn)=>m.localeCompare(Rn)):[],lt=it.length>0?`
|
|
1280
1289
|
/** Refuses to boot a shape that would replicate around the read policies its table is governed by (\`defineShape({ use })\` is how a shape opts in; \`use: []\` acknowledges an ungoverned one). */
|
|
1281
1290
|
assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(it)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
|
|
1282
1291
|
`:"",Ut=ee?`
|
|
1283
1292
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1284
1293
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1285
1294
|
}
|
|
1286
|
-
`:"",Kt=
|
|
1295
|
+
`:"",Kt=w?"assertShapeShardable, ":"",Qt=lt===""?"":"assertShapesDeclareReadPolicies, ",ke=[`import type { ${ot.join(", ")} } from "${D.do}";`,`import { applyCdcChanges, ${Ke?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${rt?"clearMemoryTables, ":""}${Kt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${ae?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Ne?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${st.importFragment}ShardDO as ShardDOBase } from "${D.do}";`,...ae?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${D.do}";`]:[],w?`import { asBucketStorage, ${Qt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${D.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${D.server}";`];Qe&&ke.push(`import { bindOrm, bindTableFacade } from "${D.server}";`),K&&ke.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&ke.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ke.push(...ue.importLines,...G.importLines,..._.importLines,...te.importLines,...he.importLines,...z.importLines,...j.importLines,...W.importLines,...U.importLines,...B.importLines,...ne.importLines,...Re,...$e,...Se,...fe,...ye,...Te,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ee?["LUNORA_MUTATOR_PATHS"]:[],...w?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ht=K?`
|
|
1287
1296
|
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Vt=nt?`
|
|
1288
1297
|
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Gt=Ue?`
|
|
1289
1298
|
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Jt=ae?`
|
|
1290
1299
|
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",zt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Yt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Xt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Zt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',en=we?I("globalDbStub: DatabaseWriterLike",zt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",tn=K?I("vectorsStub: VectorSearchLike",Yt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",nn=Ne?`
|
|
1291
1300
|
const vectorShardKey = this.currentShardKey();
|
|
1292
|
-
`:"",rn=Ne?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",an=Ne?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${
|
|
1301
|
+
`:"",rn=Ne?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",an=Ne?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${k.vectorIndexes.filter(m=>tt.has(m.table)).map(m=>JSON.stringify(m.name)).join(", ")}] }`:"",on=K?`
|
|
1293
1302
|
let vectors: VectorSearchLike;
|
|
1294
1303
|
let onWrite: WriteHook | undefined;
|
|
1295
1304
|
|
|
@@ -1397,7 +1406,7 @@ ${nn}
|
|
|
1397
1406
|
vectors,`:"",dn=Qe?`
|
|
1398
1407
|
orm: bindOrm(facade),`:"",He=Ue?"config.hyperdriveGlobal":"config.d1",un=we?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
|
|
1399
1408
|
const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
|
|
1400
|
-
`:"",hn=
|
|
1409
|
+
`:"",hn=w&&we?`
|
|
1401
1410
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1402
1411
|
const env = this.env as Record<string, unknown>;
|
|
1403
1412
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1652,7 +1661,7 @@ ${ae?`
|
|
|
1652
1661
|
}
|
|
1653
1662
|
`,yn=Qe?`
|
|
1654
1663
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1655
|
-
${
|
|
1664
|
+
${k.tables.map(m=>` facade[${JSON.stringify(m.name)}] = bindTableFacade(db, ${JSON.stringify(m.name)});`).join(`
|
|
1656
1665
|
`)}
|
|
1657
1666
|
`:"",wn=`${ue.build}${G.build}${_.build}${z.build}${he.build}
|
|
1658
1667
|
const secrets = createSecrets(env);
|
|
@@ -2033,7 +2042,7 @@ ${st.override}
|
|
|
2033
2042
|
};
|
|
2034
2043
|
}
|
|
2035
2044
|
${Ut}${Wt}${hn}${gn}
|
|
2036
|
-
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor"): readonly string[] {
|
|
2045
|
+
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
2037
2046
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
2038
2047
|
}
|
|
2039
2048
|
${mn}
|
|
@@ -2554,7 +2563,7 @@ ${Sn}${vn}
|
|
|
2554
2563
|
return ctx;
|
|
2555
2564
|
}
|
|
2556
2565
|
};
|
|
2557
|
-
`},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:
|
|
2566
|
+
`},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:N(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:N(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Xe(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},At=(e,t)=>{const n=se(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Vr=(e,t,n)=>{f(e,"drizzle column name");const r=Xe(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const i=At(t,n);return i!==void 0&&(o+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(o+=".notNull()"),o},Gr=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(f(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${Y(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},Jr=(e,t)=>{f(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([a,o])=>` ${a}: ${Vr(a,o,t)},`)].join(`
|
|
2558
2567
|
`),r=e.indexes.length>0?`, (t) => ({
|
|
2559
2568
|
${e.indexes.map(a=>Gr(a)).join(`
|
|
2560
2569
|
`)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as w,G as k}from"./emit-
|
|
1
|
+
import{A as w,G as k}from"./emit-CTDEkEXh.mjs";const y=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[y(t),e.method,e.configKey,e.doc]),m=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],g=e=>(e.emailAgents?.length??0)>0,C=e=>g(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>g(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,d)=>c.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},L=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],N=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
2
2
|
public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${a}"]>>): this {
|
|
3
3
|
this.shardExtras.${a} = factory as NonNullable<ShardConfig["${a}"]>;
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-
|
|
1
|
+
import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-BIlyTUBD.mjs";const f=s=>{const i=[];for(const r of s.getVariableStatements())if(r.isExported())for(const t of r.getDeclarations()){const e=t.getInitializer(),o=e&&a.isCallExpression(e)?n(e):void 0;o?.receiver&&i.push({name:t.getName(),receiver:o.receiver})}return i};export{f as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as m,tablesAccessedIn as d}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{w as g,c as p}from"./classify-procedure-call-
|
|
1
|
+
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as m,tablesAccessedIn as d}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{w as g,c as p}from"./classify-procedure-call-BIlyTUBD.mjs";const u=e=>{if(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e))return;const t=e.getNameNode();return r.isStringLiteral(t)?t.getLiteralValue():e.getName()},h=e=>g(e,"use","mask"),x=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();if(t&&r.isStringLiteral(t)){const s=t.getLiteralText();if(s==="redact"||s==="hash")return s}}return"custom"},k=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const i of t.getProperties()){const n=u(i);if(n===void 0||!r.isPropertyAssignment(i))continue;const o=i.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=u(a);c!==void 0&&s.push({column:c,table:n})}}return s},v=e=>{const t=h(e);return{maskColumns:t.flatMap(s=>k(s)),usesMask:t.length>0}},P=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),C=new Set(["delete","insert","patch","replace"]),M=(e,t)=>{if(!r.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const i=p(s);if(!i)return;const n=i.receiver?v(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:o,tablesWritten:a}=d(e,P,C);return{exportName:e.getName(),file:t,maskColumns:n.maskColumns,tablesRead:o,tablesWritten:a,usesMask:n.usesMask,visibility:i.visibility}},E=(e,t)=>{const s=[];for(const i of f(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i),o=m(t,i);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=M(c,o);l&&s.push(l)}}return s};export{u as a,E as d,h as m,x as s};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.192",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.141",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.119",
|
|
51
51
|
"@lunora/container": "1.0.0-alpha.52",
|
|
52
52
|
"@lunora/errors": "1.0.0-alpha.39",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.32",
|
|
54
54
|
"@lunora/queue": "1.0.0-alpha.59",
|
|
55
55
|
"@lunora/scheduler": "1.0.0-alpha.76",
|
|
56
56
|
"@lunora/values": "1.0.0-alpha.49",
|
|
57
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
57
|
+
"@lunora/workflow": "1.0.0-alpha.56",
|
|
58
58
|
"jiti": "^2.7.0",
|
|
59
59
|
"quicktype-core": "^26.0.0",
|
|
60
60
|
"ts-morph": "^28.0.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{w as a}from"./classify-procedure-call-C8jbo0IJ.mjs";const l=s=>a(s,"use","rls");export{l as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{unwrapExpression as a}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{a as u}from"./module-specifiers-WF8iAydP.mjs";const T=t=>o.isIdentifier(t)?t.getText():o.isPropertyAccessExpression(t)?t.getName():void 0,y=(t,i)=>{const e=new Set;for(const r of t.getImportDeclarations())if(u(r.getModuleSpecifierValue()))for(const n of r.getNamedImports())n.getNameNode().getText()===i&&e.add(n.getAliasNode()?.getText()??n.getName());return e},x=(t,i)=>{if(o.isPropertyAccessExpression(t))return t.getName()===i;if(!o.isIdentifier(t))return!1;const e=t.getText();return e===i||y(t.getSourceFile(),i).has(e)},d=t=>{const i=t.getSymbol();if(!i)return t.getText();for(const e of i.getDeclarations())if(o.isImportSpecifier(e))return u(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText():void 0},p=t=>{const i=[];let e=a(t);for(;e&&o.isCallExpression(e);){const r=a(e.getExpression());if(!r||!o.isPropertyAccessExpression(r))return{root:void 0,steps:i};i.push({call:e,name:r.getName()}),e=a(r.getExpression())}return{root:e,steps:i}},f=t=>p(t).steps,N=(t,i,e)=>f(t).filter(r=>r.name===i).map(r=>r.call.getArguments()[0]).filter(r=>r!==void 0&&o.isCallExpression(r)&&x(r.getExpression(),e)),A=(t,i)=>f(t).some(e=>e.name===i),w=(t,i,e)=>N(t,i,e).length>0,l=new Set(["action","mutation","query","stream"]),m={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},I={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init"},C=t=>{const{root:i}=p(t);return i&&o.isIdentifier(i)?i:void 0},g=(t,i=!1)=>{const e=C(t);if(!e)return;const r=d(e);if(r===void 0){if(i)return;const n=e.getSymbol()?.getValueDeclaration();if(n&&o.isVariableDeclaration(n)){const s=n.getInitializer();return s?g(s,!0):void 0}return}return l.has(r)?"public":m[r]?"internal":void 0},E=t=>{const i=t.getName();if(!l.has(i))return;const e=t.getExpression(),r=a(e)??e,n=e===r?[r]:[e,r];if(n.some(c=>c.getType().getProperty("__lunoraProcedure"))){const c=n.some(v=>v.getType().getProperty("__lunoraVisibility"));return{kind:i,receiver:r,visibility:c?"internal":"public"}}const s=g(r);if(s)return{kind:i,receiver:r,visibility:s}},P=t=>{const i=t.getExpression();if(o.isPropertyAccessExpression(i))return E(i);if(!o.isIdentifier(i))return;const e=d(i);if(!e)return;if(l.has(e))return{kind:e,visibility:"public"};const r=m[e];if(r)return{kind:r,visibility:"internal"};const n=I[e];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}};export{T as a,f as b,P as c,w as d,A as e,N as w};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as o}from"./context-property-calls-Ce9xGl_o.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as r}from"./context-property-calls-Ce9xGl_o.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|