@lunora/codegen 1.0.0-alpha.406 → 1.0.0-alpha.407
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 +24 -1
- package/dist/index.d.ts +24 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-DPxI0EHQ.mjs → ALL_NOTIFY_CHANNELS-D1LVGz6_.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DslD_cFq.mjs +54 -0
- package/dist/packem_shared/{SHAPES_FILENAME-CH0KrAdb.mjs → SHAPES_FILENAME-BYnZ1Xw-.mjs} +1 -1
- package/dist/packem_shared/chain-CONXUmWW.mjs +1 -0
- package/dist/packem_shared/{classify-procedure-call-BZ164dkJ.mjs → classify-procedure-call-n9urVsqb.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-Ggrmu3UL.mjs → context-property-calls-DXzNVV1P.mjs} +1 -1
- package/dist/packem_shared/{context-root-DnvrQxae.mjs → context-root-DP9WbBI_.mjs} +1 -1
- package/dist/packem_shared/{database-calls-BRI5W-Mp.mjs → database-calls-Do0YbPCL.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-CeHY4_ii.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-W96s1VgA.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-DmSa4WKU.mjs → discoverInserts-BtyJbg8A.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-BFm9rkZ7.mjs +1 -0
- package/dist/packem_shared/{discoverNondeterministicCalls-BoF6ob-B.mjs → discoverNondeterministicCalls-DR0S5Xb4.mjs} +1 -1
- package/dist/packem_shared/{discoverQueries-spxu-wHR.mjs → discoverQueries-BLyL2qzX.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-Cb4AmcY8.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-Cc0zA-gZ.mjs → discoverRlsMetadata-Cf4gZvxW.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-mjiA0I4S.mjs → discoverRlsProcedures-_Dh3Xb9Z.mjs} +1 -1
- package/dist/packem_shared/{discoverStorageRulesMetadata-CtE5trUR.mjs → discoverStorageRulesMetadata-ZKW6DInk.mjs} +1 -1
- package/dist/packem_shared/{emitApp-BsXqg0CQ.mjs → emitApp-BSeuQrKr.mjs} +65 -64
- package/dist/packem_shared/{emitServer-DsSAaZaT.mjs → emitServer-CbcZN_Ug.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-h8Y7xDjq.mjs → exported-procedure-chains-DomRzs5_.mjs} +1 -1
- package/dist/packem_shared/{index-jtzAVdUp.mjs → index-BH3e-J44.mjs} +1 -1
- package/dist/packem_shared/{index-mFEIaT45.mjs → index-D03C6Kao.mjs} +1 -1
- package/dist/packem_shared/{ip-reads-BPDWkzEu.mjs → ip-reads-ByzaRhd2.mjs} +1 -1
- package/dist/packem_shared/{server-CRFaUMKQ.mjs → server-5ph4hltf.mjs} +63 -55
- package/package.json +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DfLhJQrR.mjs +0 -54
- package/dist/packem_shared/chain-CXiqZFUk.mjs +0 -1
- package/dist/packem_shared/discoverFunctions-mAWlAiuj.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-CyjXtZgc.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as o}from"./context-property-calls-DXzNVV1P.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-DRIdZaij.mjs";import{c as a}from"./attribution-BhGR_h0Z.mjs";import{i as c}from"./database-calls-
|
|
1
|
+
import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-DRIdZaij.mjs";import{c as a}from"./attribution-BhGR_h0Z.mjs";import{i as c}from"./database-calls-Do0YbPCL.mjs";const l=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return c(r)},g=t=>{if(!i.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const s of r)if(i.isVariableDeclaration(s)){const o=s.getInitializer();if(o&&i.isStringLiteral(o))return o.getLiteralText()}},f=t=>{const e=t.getArguments()[0];return e?i.isStringLiteral(e)?e.getLiteralText():g(e)??"":""},d=(t,e)=>n(t,e,(r,s)=>l(r)?{file:s,line:r.getStartLineNumber(),scope:a(r),table:f(r)}:void 0);export{d as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./isTestPath-DRIdZaij.mjs";import"./attribution-BhGR_h0Z.mjs";import"./database-calls-Do0YbPCL.mjs";import"./classify-procedure-call-n9urVsqb.mjs";import{d as a}from"./index-D03C6Kao.mjs";export{a as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as d}from"ts-morph";import{listLunoraSourceFiles as m,lunoraRelativePath as g,handlerOf as u,descendantsOfKind as l}from"./isTestPath-DRIdZaij.mjs";import{j as N,h as x}from"./attribution-BhGR_h0Z.mjs";import{c as p}from"./classify-procedure-call-
|
|
1
|
+
import{Node as s,SyntaxKind as d}from"ts-morph";import{listLunoraSourceFiles as m,lunoraRelativePath as g,handlerOf as u,descendantsOfKind as l}from"./isTestPath-DRIdZaij.mjs";import{j as N,h as x}from"./attribution-BhGR_h0Z.mjs";import{c as p}from"./classify-procedure-call-n9urVsqb.mjs";const h={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},E=new Set(["globalThis","self"]),v=new Set(["globalThis","self","window"]),I=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&v.has(t.getText()))return e.getName()}},S=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=I(t.getExpression());if(i!==void 0)return n==="fetch"&&E.has(i)?"fetch":h[`${i}.${n}`]},T=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"},y=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=p(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=u(t,n.receiver);return i?{exportName:x(e)??e.getName(),handler:i,kind:n.kind}:void 0},L=e=>{const t=new Set(["ctx"]),n=r=>{if(s.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getNameNode().getText(),f=a.getNameNode();c==="ctx"&&s.isIdentifier(f)&&t.add(f.getText())}},[i]=s.isParametered(e)?e.getParameters():[],o=i!==void 0&&s.isIdentifier(i.getNameNode())?i.getNameNode().getText():void 0;if(i!==void 0){const r=i.getNameNode();s.isIdentifier(r)?t.add(r.getText()):n(r)}for(const r of l(e,d.VariableDeclaration)){const a=r.getInitializer();o!==void 0&&a!==void 0&&s.isIdentifier(a)&&a.getText()===o&&n(r.getNameNode())}return t},P=(e,t,n)=>{const i=e.getExpression();if(!s.isPropertyAccessExpression(i)||i.getName()!=="random")return!1;const o=i.getExpression();return!s.isIdentifier(o)||!t.has(o.getText())?!1:o.getSymbol()?.getDeclarations()[0]?.getFirstAncestor(c=>s.isFunctionLikeDeclaration(c))===n},w=(e,t)=>{const n=[],i=L(e.handler);for(const o of l(e.handler,d.CallExpression)){const r=e.kind==="query"&&P(o,i,e.handler)?"ctx.random":S(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}for(const o of l(e.handler,d.NewExpression)){const r=T(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}return n},O=(e,t)=>{const n=[];for(const i of N(e)){const o=y(i);o&&n.push(...w(o,t))}return n},A=(e,t)=>{const n=[];for(const i of m(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...O(o,g(t,i)))}return n};export{A as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i,SyntaxKind as u}from"ts-morph";import{collectCallRows as x}from"./isTestPath-DRIdZaij.mjs";import{w as E,c as h}from"./attribution-BhGR_h0Z.mjs";import{i as v}from"./database-calls-
|
|
1
|
+
import{Node as i,SyntaxKind as u}from"ts-morph";import{collectCallRows as x}from"./isTestPath-DRIdZaij.mjs";import{w as E,c as h}from"./attribution-BhGR_h0Z.mjs";import{i as v}from"./database-calls-Do0YbPCL.mjs";const A=new Set(["withGeoIndex","withIndex","withSearchIndex"]),S=new Set(["collect","collectWithScores","first","paginate","take","unique"]),w=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="query")return!1;const n=e.getExpression();return v(n)},y=t=>{const e=[];let n=t;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;e.push(r),n=r}return e},l=t=>{const e=t.getExpression();return i.isPropertyAccessExpression(e)?e.getName():""},m=t=>{if(t===void 0||!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getParameters()[0]?.getNameNode();return e!==void 0&&i.isIdentifier(e)?e.getText():void 0},O=t=>{let e=t;for(;i.isCallExpression(e)||i.isPropertyAccessExpression(e);)e=e.getExpression();return e},P=(t,e)=>{const n=new Set,s=[t,...t.getDescendantsOfKind(u.CallExpression)].filter(r=>i.isCallExpression(r));for(const r of s){const c=r.getExpression();if(i.isPropertyAccessExpression(c)){const o=O(c);i.isIdentifier(o)&&o.getText()===e&&n.add(c.getName())}}return n},f=(t,e)=>{if(i.isParenthesizedExpression(t))return f(t.getExpression(),e);if(i.isConditionalExpression(t)){const n=f(t.getWhenFalse(),e);return new Set([...f(t.getWhenTrue(),e)].filter(s=>n.has(s)))}return P(t,e)},C=t=>{if(!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getBody();if(!i.isBlock(e))return i.isExpression(e)?[e]:void 0;const n=e.getDescendantsOfKind(u.ReturnStatement).filter(s=>s.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r))?.compilerNode===t.compilerNode).map(s=>s.getExpression()).filter(s=>s!==void 0);return n.length===0?void 0:n},F=(t,e)=>{const n=C(t);if(n===void 0)return;const[s,...r]=n.map(o=>f(o,e));return[...s??new Set].filter(o=>r.every(d=>d.has(o))).toSorted((o,d)=>o.localeCompare(d))},I=(t,e)=>{const n=new Set;for(const s of t.getDescendantsOfKind(u.PropertyAccessExpression)){const r=s.getExpression();i.isIdentifier(r)&&r.getText()===e&&n.add(s.getName())}for(const s of t.getDescendantsOfKind(u.ElementAccessExpression)){const r=s.getExpression(),c=s.getArgumentExpression();i.isIdentifier(r)&&r.getText()===e&&c!==void 0&&i.isStringLiteral(c)&&n.add(c.getLiteralText())}return[...n]},N=t=>{if(t===void 0)return;const[e,n]=t.getArguments(),s=m(n),r=e!==void 0&&i.isStringLiteral(e)?e.getLiteralText():void 0;return n===void 0?{bounds:[],name:r}:{bounds:s===void 0?void 0:F(n,s),name:r}},T=t=>{const e=t.flatMap(n=>{const s=n.getArguments()[0],r=m(s);return s===void 0||r===void 0?[]:I(s,r)});if(e.length!==0)return[...new Set(e)].toSorted((n,s)=>n.localeCompare(s))},b=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,D=t=>t.some(e=>l(e)==="filter"&&b.test(e.getArguments()[0]?.getText()??"")),L=t=>{const e=t.getArguments()[0];return e&&i.isStringLiteral(e)?e.getLiteralText():""},k=(t,e,n=[])=>{const s=x(t,e,(r,c)=>{if(!w(r))return;const o=y(r),d=o.map(a=>l(a)),p=o.filter(a=>l(a)==="filter"),g=p.length>0;return{file:c,filterFields:g?T(p):void 0,filtersPrimaryKey:g&&D(o),hasFilter:g,hasIndex:d.some(a=>A.has(a)),index:N(o.find(a=>l(a)==="withIndex")),line:r.getStartLineNumber(),scope:h(r),table:L(r),terminal:d.findLast(a=>S.has(a))}});return E(s,n)};export{k as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as r}from"./context-property-calls-DXzNVV1P.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|
package/dist/packem_shared/{discoverRlsMetadata-Cc0zA-gZ.mjs → discoverRlsMetadata-Cf4gZvxW.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./isTestPath-DRIdZaij.mjs";import{e as A}from"./exported-procedure-chains-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./isTestPath-DRIdZaij.mjs";import{e as A}from"./exported-procedure-chains-DomRzs5_.mjs";import{r as L}from"./chain-CONXUmWW.mjs";const E=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||!E.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=m(e,"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},v=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"))}},y=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const i=m(t,"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=v(n);a&&s.push(a)}return s},O=(e,t,i)=>{const r=L(e);return{policies:r.flatMap(s=>P(s,t,i)),roles:r.flatMap(s=>y(s))}},I=(e,t)=>{const i=[],r=new Map;for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=h(t,s);for(const{name:g,receiver:d}of A(n)){const p=O(d,a,g);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{I as default};
|
package/dist/packem_shared/{discoverRlsProcedures-mjiA0I4S.mjs → discoverRlsProcedures-_Dh3Xb9Z.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-DRIdZaij.mjs";import{j as p,h as m}from"./attribution-BhGR_h0Z.mjs";import{t as d}from"./database-calls-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-DRIdZaij.mjs";import{j as p,h as m}from"./attribution-BhGR_h0Z.mjs";import{t as d}from"./database-calls-Do0YbPCL.mjs";import{c as b}from"./classify-procedure-call-n9urVsqb.mjs";import{r as h}from"./chain-CONXUmWW.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const r=[];for(const s of t.getElements()){if(!o.isObjectLiteralExpression(s))continue;const i=u(s,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}return r},y=e=>{const t=h(e);return{rlsTables:t.flatMap(r=>g(r)),usesRls:t.length>0}},v=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),x=new Set(["delete","deleteMany","insert","insertMany","patch","patchIf","patchMany","replace"]),P=(e,t)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const s=b(r);if(!s)return;const i=s.receiver?y(s.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:a}=d(e,v,x);return{exportName:m(e)??e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:a,usesRls:i.usesRls,visibility:s.visibility}},M=(e,t)=>{const r=[];for(const s of c(t)){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=f(t,s);for(const a of p(i)){const l=P(a,n);l&&r.push(l)}}return r};export{M as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-DRIdZaij.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"./isTestPath-DRIdZaij.mjs";import{w as d}from"./classify-procedure-call-n9urVsqb.mjs";import{e as m}from"./exported-procedure-chains-DomRzs5_.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,11 +1,11 @@
|
|
|
1
|
-
import{APP_METHOD_CAPABILITIES as
|
|
1
|
+
import{APP_METHOD_CAPABILITIES as N}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{i as I}from"./schema-BgM8A3XV.mjs";import{a as L,I as j,G as y}from"./shared-Cn7dMQ_u.mjs";const $={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...N.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[$]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(t=>I(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,P=e=>e.hasScheduler?`
|
|
2
2
|
/** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
|
|
3
3
|
private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
|
|
4
4
|
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
5
5
|
|
|
6
6
|
return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
|
|
7
7
|
}
|
|
8
|
-
`:"",
|
|
8
|
+
`:"",G=e=>e?`
|
|
9
9
|
/**
|
|
10
10
|
* One bucket's \`Storage\`, signing under the name it is registered as.
|
|
11
11
|
*
|
|
@@ -114,7 +114,7 @@ import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";impor
|
|
|
114
114
|
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
115
115
|
};
|
|
116
116
|
}
|
|
117
|
-
`:"",
|
|
117
|
+
`:"",_=e=>e?`
|
|
118
118
|
/**
|
|
119
119
|
* Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
|
|
120
120
|
*
|
|
@@ -382,12 +382,12 @@ const buildGlobalCdcApplier =
|
|
|
382
382
|
|
|
383
383
|
return request.changes.length;
|
|
384
384
|
};
|
|
385
|
-
`:"",
|
|
386
|
-
public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${
|
|
387
|
-
this.shardExtras.${
|
|
385
|
+
`:"",M=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. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\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(async () => (await import("postgres")).default(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\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}']:[]],W=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[],...e.hasAdminRevocations===!1?[]:[" private adminRevocationsSelector?: Selector<Env, ShardNamespaceLike>;"]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," 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>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...c(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],B=e=>f(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
|
|
386
|
+
public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
|
|
387
|
+
this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
|
|
388
388
|
|
|
389
389
|
return this;
|
|
390
|
-
}`),
|
|
390
|
+
}`),H=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
|
|
391
391
|
public admin(selector: Selector<Env, string>): this {
|
|
392
392
|
this.adminToken = selector;
|
|
393
393
|
|
|
@@ -446,7 +446,7 @@ const buildGlobalCdcApplier =
|
|
|
446
446
|
this.adminRevocationsSelector = selector;
|
|
447
447
|
|
|
448
448
|
return this;
|
|
449
|
-
}`],...
|
|
449
|
+
}`],...c(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
|
|
450
450
|
public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
|
|
451
451
|
this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
|
|
452
452
|
|
|
@@ -456,8 +456,8 @@ const buildGlobalCdcApplier =
|
|
|
456
456
|
this.storageDeclaration = declaration;
|
|
457
457
|
|
|
458
458
|
return this;
|
|
459
|
-
}`]:[],...
|
|
460
|
-
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",
|
|
459
|
+
}`]:[],...B(e)],U=e=>{const t=a=>e.hasScheduler?`
|
|
460
|
+
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",r=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
|
|
461
461
|
? {
|
|
462
462
|
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null | undefined }) => {
|
|
463
463
|
const env = rawEnv as Env;
|
|
@@ -481,7 +481,7 @@ const buildGlobalCdcApplier =
|
|
|
481
481
|
: undefined;
|
|
482
482
|
|
|
483
483
|
return createD1CtxDb({
|
|
484
|
-
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${
|
|
484
|
+
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("D1CtxDbOptions")}
|
|
485
485
|
...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
|
|
486
486
|
// Getters, like the cross-shard identity above: reading the
|
|
487
487
|
// request's caller marks the live query as caller-dependent, so
|
|
@@ -533,7 +533,7 @@ const buildGlobalCdcApplier =
|
|
|
533
533
|
: undefined;
|
|
534
534
|
|
|
535
535
|
return createHyperdriveGlobalCtxDb({
|
|
536
|
-
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${
|
|
536
|
+
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
|
|
537
537
|
...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
|
|
538
538
|
// Getters, like the cross-shard identity above: reading the
|
|
539
539
|
// request's caller marks the live query as caller-dependent, so
|
|
@@ -564,29 +564,30 @@ const buildGlobalCdcApplier =
|
|
|
564
564
|
? {
|
|
565
565
|
scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
|
|
566
566
|
}
|
|
567
|
-
: {}),`]:[],...
|
|
568
|
-
${
|
|
567
|
+
: {}),`]:[],...c(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
|
|
568
|
+
${r.join(`
|
|
569
569
|
`)}
|
|
570
|
-
`:""},
|
|
570
|
+
`:""},F=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],z=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],Q=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],J=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],K=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, applySqlMigrationFiles, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],V=e=>e?['import notifyConfig from "../notify.js";']:[],Y=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],X=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Z=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,i=n?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","SecurityOptions","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],l=[...r||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${l} } from "${i}";`]},ee=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:n,hasQueue:i,hasScheduler:d,hasStorage:l,hasWorkflow:o}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...z(t,r),...K(a),...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...Q(n),...J(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...l?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...Y(e),...Z(e),"",...F(e.identity),...X(e),...a||s?['import schema from "../schema.js";']:[],...V(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";',...e.lazyFunctions===!0?[]:['import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']]:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},S=e=>e.authClaims===void 0||e.authClaims.length===0?void 0:JSON.stringify(e.authClaims),te=e=>{const t=S(e);return t===void 0?"":`, ${t}`},re=e=>{const t=S(e);return t===void 0?"":`
|
|
571
|
+
claims: ${t},`},ae=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
|
|
571
572
|
// The schema's jurisdiction pins the auth object like every other DO.
|
|
572
|
-
jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",
|
|
573
|
-
${e.tables.map(
|
|
573
|
+
jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",se=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,ne=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
|
|
574
|
+
${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${se(t.shardMode)}],`).join(`
|
|
574
575
|
`)}
|
|
575
576
|
]);
|
|
576
577
|
|
|
577
578
|
options.listSchemaTables = () => [...tableSharding.keys()];
|
|
578
|
-
options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...
|
|
579
|
+
options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...c(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
|
|
579
580
|
|
|
580
581
|
if (shardRegistry) {
|
|
581
582
|
options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
|
|
582
|
-
}`]:[]],
|
|
583
|
+
}`]:[]],oe=[` const adminRevocations = this.adminRevocationsSelector?.(env);
|
|
583
584
|
|
|
584
585
|
if (adminRevocations) {
|
|
585
586
|
options.adminRevocations = adminRevocations;
|
|
586
|
-
}`],
|
|
587
|
-
${
|
|
587
|
+
}`],E=e=>(e.liveStreamDeclarations??[]).map(t=>{if(L(t.exportName,"live stream export name"),!j.test(t.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(t.filePath)}`);return` { id: ${JSON.stringify(t.id)}, load: () => import("../${t.filePath}.js").then((m) => m.${t.exportName}) },`}),ie=e=>p(e)?[" httpRouter: liveStreamRouter([",...E(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],le=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],ce=e=>p(e)?`liveStreamRouter([
|
|
588
|
+
${E(e).join(`
|
|
588
589
|
`)}
|
|
589
|
-
], host)`:"host",
|
|
590
|
+
], host)`:"host",de=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],he=e=>[...ne(e),...e.hasAdminRevocations===!1?[]:oe,...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
590
591
|
options.schedulerDO = this.schedulerDeclaration.namespace(env);
|
|
591
592
|
}`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
|
|
592
593
|
const source = workflowEnv as Record<string, unknown>;
|
|
@@ -718,7 +719,7 @@ ${S(e).join(`
|
|
|
718
719
|
// Memoised on the declaration: each worker built for a new \`env\` runs
|
|
719
720
|
// these options again, and \`options(env)\` rebuilds every plugin.
|
|
720
721
|
discoveryPaths,
|
|
721
|
-
internalSecret,${
|
|
722
|
+
internalSecret,${ae(e)}${re(e)}
|
|
722
723
|
namespace,
|
|
723
724
|
...(objectName === undefined ? {} : { objectName }),
|
|
724
725
|
});
|
|
@@ -760,7 +761,7 @@ ${S(e).join(`
|
|
|
760
761
|
// the same claims (role, expiry, profile, and the active organization and
|
|
761
762
|
// team checked against membership) on the identity, and it is unit-tested
|
|
762
763
|
// where this template cannot be.
|
|
763
|
-
return resolveSessionIdentity(auth, (request as Request).headers);
|
|
764
|
+
return resolveSessionIdentity(auth, (request as Request).headers${te(e)});
|
|
764
765
|
};
|
|
765
766
|
const authInstance = getAuth();
|
|
766
767
|
|
|
@@ -857,16 +858,16 @@ ${S(e).join(`
|
|
|
857
858
|
options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
|
|
858
859
|
}`:` if (this.accessSelector) {
|
|
859
860
|
options.resolveIdentity = createAccessResolver(this.accessSelector(env));
|
|
860
|
-
}`]:[],...
|
|
861
|
-
${e.voiceAgents.map(
|
|
861
|
+
}`]:[],...de(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
862
|
+
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
862
863
|
`)}
|
|
863
|
-
};`]:[]],
|
|
864
|
+
};`]:[]],ue=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`,` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"LUNORA_QUEUE_REGISTRY"}, {`," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],pe=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...ue(e),...ie(e),...le(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),",...e.spaAssetsBindings===void 0||e.spaAssetsBindings.length===0?[]:[` spaAssets: (${e.spaAssetsBindings.map(t=>`(env as Record<string, unknown>)[${JSON.stringify(t)}]`).join(" ?? ")}) as WorkerOptions["spaAssets"],`]],me=e=>e?`
|
|
864
865
|
/** The identity memo per \`env\` object, owned by one assembled worker. */
|
|
865
866
|
type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
|
|
866
|
-
`:"",
|
|
867
|
+
`:"",R=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,be=e=>{if(!R(e))return"";const r=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,s,n])=>[a,s,n]);return`
|
|
867
868
|
/** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
|
|
868
869
|
interface DeferredModules {
|
|
869
|
-
${
|
|
870
|
+
${r.map(([a,s])=>` ${a}: ${s};`).join(`
|
|
870
871
|
`)}
|
|
871
872
|
}
|
|
872
873
|
|
|
@@ -876,19 +877,19 @@ let deferredModules: Promise<DeferredModules> | undefined;
|
|
|
876
877
|
const loadDeferredModules = (): Promise<DeferredModules> =>
|
|
877
878
|
(deferredModules ??= (async (): Promise<DeferredModules> => {
|
|
878
879
|
return {
|
|
879
|
-
${
|
|
880
|
+
${r.map(([a,,s])=>` ${a}: ${s},`).join(`
|
|
880
881
|
`)}
|
|
881
882
|
};
|
|
882
883
|
})());
|
|
883
|
-
`},
|
|
884
|
+
`},ge=(e,t)=>{const r=`buildWorker(rawEnv as Env${t})`,a=e?`
|
|
884
885
|
await ensureAuth(env);`:"",s=e?`
|
|
885
886
|
await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"target",eventWorkerLine:`
|
|
886
|
-
const target = (await authReady(rawEnv as Env)) ? (worker ??= ${
|
|
887
|
-
worker ??= ${
|
|
888
|
-
const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},
|
|
889
|
-
`:"",
|
|
887
|
+
const target = (await authReady(rawEnv as Env)) ? (worker ??= ${r}) : ${r};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
|
|
888
|
+
worker ??= ${r};`}},ve=e=>R(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
|
|
889
|
+
const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},Re=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
|
|
890
|
+
`:"",ye=e=>{const t=e.emailAgents??[];if(t.length===0)return"";const r=a=>t.map(s=>`${a}{ agent: lunoraAgentDefinitions.${s.exportName}, className: ${JSON.stringify(s.className)} },`).join(`
|
|
890
891
|
`);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
|
|
891
|
-
${
|
|
892
|
+
${r(" ")}
|
|
892
893
|
]);
|
|
893
894
|
|
|
894
895
|
`:` let agentEmail: ReturnType<typeof dispatchAgentEmail> | undefined;
|
|
@@ -898,21 +899,21 @@ ${t(" ")}
|
|
|
898
899
|
const [{ dispatchAgentEmail: dispatch }, lunoraAgentDefinitions] = await Promise.all([import("@lunora/agent/inbound"), import("../agents.js")]);
|
|
899
900
|
|
|
900
901
|
agentEmail ??= dispatch([
|
|
901
|
-
${
|
|
902
|
+
${r(" ")}
|
|
902
903
|
]);
|
|
903
904
|
}
|
|
904
905
|
|
|
905
906
|
return agentEmail(message, rawEnv, context);
|
|
906
907
|
};
|
|
907
908
|
|
|
908
|
-
`},
|
|
909
|
+
`},fe=e=>e.securityHeaders===void 0?"":`
|
|
909
910
|
/**
|
|
910
911
|
* \`security.headers\` from \`lunora.config\`: the baseline security headers the Worker sends, and the same values
|
|
911
912
|
* the build writes into the static assets' \`_headers\`. An app that calls \`createWorker\` itself passes it as
|
|
912
913
|
* \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
|
|
913
914
|
*/
|
|
914
915
|
const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
|
|
915
|
-
`,
|
|
916
|
+
`,we=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),De=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,s=M(r),n=he(r),i=a?` let auth: LunoraAuth | null = null;
|
|
916
917
|
let authInit: Promise<void> | null = null;
|
|
917
918
|
// One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
|
|
918
919
|
// \`assemble()\` has its own auth closure and must not share.
|
|
@@ -983,11 +984,11 @@ const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.s
|
|
|
983
984
|
return false;
|
|
984
985
|
},
|
|
985
986
|
);
|
|
986
|
-
`:"",{asyncIfDeferred:
|
|
987
|
-
host ? withFrameworkWorker(${
|
|
987
|
+
`:"",{asyncIfDeferred:l,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=ve(r),{ensureAuthCall:D,ensureRawAuthCall:A,eventWorker:m,eventWorkerLine:b}=ge(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,x=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,C=r.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
|
|
988
|
+
host ? withFrameworkWorker(${ce(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,O=r.hasFramework?"host?: FrameworkHostHandler":"",q=ye(r),T=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
988
989
|
public build(): ComposedApp {
|
|
989
990
|
return this.assemble();
|
|
990
|
-
}${
|
|
991
|
+
}${r.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${ee(r).join(`
|
|
991
992
|
`)}
|
|
992
993
|
|
|
993
994
|
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
@@ -995,11 +996,11 @@ type Selector<Env, T> = (env: Env) => T | undefined;
|
|
|
995
996
|
|
|
996
997
|
/** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
|
|
997
998
|
type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
|
|
998
|
-
${
|
|
999
|
+
${fe(r)}${me(a)}${be(r)}${r.jurisdiction?`
|
|
999
1000
|
// Module scope, so every isolate loading this script (the worker and each Durable
|
|
1000
1001
|
// Object class it exports) knows the schema's jurisdiction before a request runs.
|
|
1001
1002
|
// \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
|
|
1002
|
-
declareAppJurisdiction(${JSON.stringify(
|
|
1003
|
+
declareAppJurisdiction(${JSON.stringify(r.jurisdiction)});
|
|
1003
1004
|
`:""}
|
|
1004
1005
|
${s.join(`
|
|
1005
1006
|
|
|
@@ -1020,32 +1021,32 @@ interface ComposedApp extends LunoraWorker {
|
|
|
1020
1021
|
* first request so per-isolate singletons are built once.
|
|
1021
1022
|
*/
|
|
1022
1023
|
class AppBuilder<Env extends object> {
|
|
1023
|
-
${
|
|
1024
|
+
${W(r).join(`
|
|
1024
1025
|
`)}
|
|
1025
1026
|
|
|
1026
1027
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
1027
1028
|
|
|
1028
|
-
${
|
|
1029
|
+
${H(r).join(`
|
|
1029
1030
|
|
|
1030
1031
|
`)}
|
|
1031
1032
|
|
|
1032
|
-
${
|
|
1033
|
+
${T}
|
|
1033
1034
|
|
|
1034
1035
|
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
1035
|
-
private assemble(${
|
|
1036
|
-
const ShardDO = createShardDO({${
|
|
1036
|
+
private assemble(${O}): ComposedApp {
|
|
1037
|
+
const ShardDO = createShardDO({${U(r)}});
|
|
1037
1038
|
|
|
1038
1039
|
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
1039
1040
|
// build, so the first request constructs them and every later request on
|
|
1040
1041
|
// the same isolate reuses them.
|
|
1041
1042
|
let worker: LunoraWorker | null = null;
|
|
1042
1043
|
${i}${d}
|
|
1043
|
-
${
|
|
1044
|
+
${C}
|
|
1044
1045
|
|
|
1045
1046
|
const composed: ComposedApp = {
|
|
1046
1047
|
ShardDO,
|
|
1047
1048
|
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
1048
|
-
const env = rawEnv as Env;${h}${
|
|
1049
|
+
const env = rawEnv as Env;${h}${D}
|
|
1049
1050
|
worker ??= buildWorker(env${o});
|
|
1050
1051
|
|
|
1051
1052
|
return worker.fetch(request, rawEnv, context);
|
|
@@ -1054,29 +1055,29 @@ ${x}
|
|
|
1054
1055
|
|
|
1055
1056
|
return ${m}.scheduled(controller, rawEnv, context);
|
|
1056
1057
|
},
|
|
1057
|
-
serverQuery: ${
|
|
1058
|
+
serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${A}
|
|
1058
1059
|
worker ??= buildWorker(rawEnv as Env${o});
|
|
1059
1060
|
|
|
1060
1061
|
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
1061
|
-
},${
|
|
1062
|
+
},${r.hasQueue||r.hasFramework?`
|
|
1062
1063
|
queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}${b}
|
|
1063
1064
|
|
|
1064
1065
|
return ${m}.queue?.(batch, rawEnv, context);
|
|
1065
1066
|
},`:""}
|
|
1066
1067
|
};
|
|
1067
1068
|
|
|
1068
|
-
${
|
|
1069
|
+
${q} if (this.emailHandler) {
|
|
1069
1070
|
const handler = this.emailHandler;
|
|
1070
1071
|
|
|
1071
1072
|
composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
|
|
1072
1073
|
}
|
|
1073
|
-
${
|
|
1074
|
+
${r.hasFramework?`
|
|
1074
1075
|
// A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
|
|
1075
1076
|
// does). Nothing in Lunora serves one, so when the app registered no handler
|
|
1076
1077
|
// of its own the host's is the only one there is — forward to it rather than
|
|
1077
1078
|
// dropping the entry.
|
|
1078
1079
|
if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
|
|
1079
|
-
composed.email = ${
|
|
1080
|
+
composed.email = ${l}(message, rawEnv, context) => {${h}${b}
|
|
1080
1081
|
|
|
1081
1082
|
return ${m}.email?.(message, rawEnv, context) ?? Promise.resolve();
|
|
1082
1083
|
};
|
|
@@ -1084,11 +1085,11 @@ ${t.hasFramework?`
|
|
|
1084
1085
|
`:""}
|
|
1085
1086
|
return composed;
|
|
1086
1087
|
}
|
|
1087
|
-
${
|
|
1088
|
+
${P(r)}${G(r.hasStorage)}
|
|
1088
1089
|
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
1089
|
-
private buildWorkerOptions(env: Env, ${
|
|
1090
|
+
private buildWorkerOptions(env: Env, ${x}): WorkerOptions {
|
|
1090
1091
|
const options: WorkerOptions = {
|
|
1091
|
-
${
|
|
1092
|
+
${pe(r).join(`
|
|
1092
1093
|
`)}
|
|
1093
1094
|
};
|
|
1094
1095
|
|
|
@@ -1105,11 +1106,11 @@ ${n.join(`
|
|
|
1105
1106
|
`:""} for (const fn of this.extendFns) {
|
|
1106
1107
|
Object.assign(options, fn(env, { ...options }));
|
|
1107
1108
|
}
|
|
1108
|
-
${
|
|
1109
|
+
${r.securityHeaders===void 0?"":"\n // `security.headers` from lunora.config, unless code set its own. After `.extend()`, whose shallow\n // assign would otherwise drop it when an extension sets only `security.cors`.\n if (options.security?.headers === undefined) {\n options.security = { ...options.security, headers: LUNORA_SECURITY_HEADERS };\n }\n"}
|
|
1109
1110
|
return options;
|
|
1110
1111
|
}
|
|
1111
1112
|
}
|
|
1112
|
-
${
|
|
1113
|
+
${_(r.hasGlobal)}
|
|
1113
1114
|
/**
|
|
1114
1115
|
* Shape of the project's root \`lunora.config.*\`.
|
|
1115
1116
|
*
|
|
@@ -1151,6 +1152,6 @@ interface LunoraConfig<Env extends object = object> {
|
|
|
1151
1152
|
*/
|
|
1152
1153
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
1153
1154
|
|
|
1154
|
-
export { AppBuilder, defineApp${
|
|
1155
|
-
export type { ${
|
|
1156
|
-
`};export{
|
|
1155
|
+
export { AppBuilder, defineApp${r.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
|
|
1156
|
+
export type { ${we(r)} };
|
|
1157
|
+
`};export{De as emitApp,Re as emitAuthModule};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{e}from"./server-
|
|
1
|
+
import"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{e}from"./server-5ph4hltf.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-BhGR_h0Z.mjs";import{c as n}from"./classify-procedure-call-
|
|
1
|
+
import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-BhGR_h0Z.mjs";import{c as n}from"./classify-procedure-call-n9urVsqb.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};
|