@lunora/codegen 1.0.0-alpha.405 → 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.
Files changed (36) hide show
  1. package/dist/index.d.mts +24 -1
  2. package/dist/index.d.ts +24 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-DPxI0EHQ.mjs → ALL_NOTIFY_CHANNELS-D1LVGz6_.mjs} +1 -1
  5. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DslD_cFq.mjs +54 -0
  6. package/dist/packem_shared/{SHAPES_FILENAME-CH0KrAdb.mjs → SHAPES_FILENAME-BYnZ1Xw-.mjs} +1 -1
  7. package/dist/packem_shared/{SchemaSnapshotParseError-DnAuFdpl.mjs → SchemaSnapshotParseError-CV7mmuPi.mjs} +1 -1
  8. package/dist/packem_shared/chain-CONXUmWW.mjs +1 -0
  9. package/dist/packem_shared/{classify-procedure-call-BZ164dkJ.mjs → classify-procedure-call-n9urVsqb.mjs} +1 -1
  10. package/dist/packem_shared/{context-property-calls-Ggrmu3UL.mjs → context-property-calls-DXzNVV1P.mjs} +1 -1
  11. package/dist/packem_shared/{context-root-DnvrQxae.mjs → context-root-DP9WbBI_.mjs} +1 -1
  12. package/dist/packem_shared/{database-calls-BRI5W-Mp.mjs → database-calls-Do0YbPCL.mjs} +1 -1
  13. package/dist/packem_shared/discoverFunctions-CeHY4_ii.mjs +1 -0
  14. package/dist/packem_shared/discoverHyperdriveCalls-W96s1VgA.mjs +1 -0
  15. package/dist/packem_shared/{discoverInserts-DmSa4WKU.mjs → discoverInserts-BtyJbg8A.mjs} +1 -1
  16. package/dist/packem_shared/discoverMaskProcedures-BFm9rkZ7.mjs +1 -0
  17. package/dist/packem_shared/{discoverNondeterministicCalls-BoF6ob-B.mjs → discoverNondeterministicCalls-DR0S5Xb4.mjs} +1 -1
  18. package/dist/packem_shared/{discoverQueries-spxu-wHR.mjs → discoverQueries-BLyL2qzX.mjs} +1 -1
  19. package/dist/packem_shared/discoverR2sqlCalls-Cb4AmcY8.mjs +1 -0
  20. package/dist/packem_shared/{discoverRlsMetadata-Cc0zA-gZ.mjs → discoverRlsMetadata-Cf4gZvxW.mjs} +1 -1
  21. package/dist/packem_shared/{discoverRlsProcedures-mjiA0I4S.mjs → discoverRlsProcedures-_Dh3Xb9Z.mjs} +1 -1
  22. package/dist/packem_shared/{discoverStorageRulesMetadata-CtE5trUR.mjs → discoverStorageRulesMetadata-ZKW6DInk.mjs} +1 -1
  23. package/dist/packem_shared/{emitApp-C3IUdkkt.mjs → emitApp-BSeuQrKr.mjs} +69 -63
  24. package/dist/packem_shared/{emitServer-DsSAaZaT.mjs → emitServer-CbcZN_Ug.mjs} +1 -1
  25. package/dist/packem_shared/{exported-procedure-chains-h8Y7xDjq.mjs → exported-procedure-chains-DomRzs5_.mjs} +1 -1
  26. package/dist/packem_shared/{index-jtzAVdUp.mjs → index-BH3e-J44.mjs} +1 -1
  27. package/dist/packem_shared/{index-mFEIaT45.mjs → index-D03C6Kao.mjs} +1 -1
  28. package/dist/packem_shared/{ip-reads-BPDWkzEu.mjs → ip-reads-ByzaRhd2.mjs} +1 -1
  29. package/dist/packem_shared/{server-CRFaUMKQ.mjs → server-5ph4hltf.mjs} +63 -55
  30. package/package.json +2 -2
  31. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CKRhpYzL.mjs +0 -54
  32. package/dist/packem_shared/chain-CXiqZFUk.mjs +0 -1
  33. package/dist/packem_shared/discoverFunctions-mAWlAiuj.mjs +0 -1
  34. package/dist/packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs +0 -1
  35. package/dist/packem_shared/discoverMaskProcedures-CyjXtZgc.mjs +0 -1
  36. package/dist/packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs +0 -1
@@ -1 +1 @@
1
- import{Node as r,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as C,descendantsOfKind as p,bindingKeyName as I,findObjectProperty as E,isConstDeclaration as D,walkChain as M}from"./isTestPath-DRIdZaij.mjs";import{d as v,b as S,f as F}from"./attribution-BhGR_h0Z.mjs";import{c as b}from"./classify-procedure-call-BZ164dkJ.mjs";import{isDefineMutatorCallee as w}from"./MUTATORS_FILENAME-C3OImAxC.mjs";const x=8,N=t=>{if(r.isMethodDeclaration(t))return t;const e=r.isPropertyAssignment(t)?l(t.getInitializer()):void 0,o=r.isShorthandPropertyAssignment(t)?t.getNameNode():e;if(r.isArrowFunction(o)||r.isFunctionExpression(o))return o;const i=r.isIdentifier(o)?v(o):void 0;if(r.isFunctionDeclaration(i))return i;const n=D(i)?l(i.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},T=t=>{const e=l(t.getArguments()[0]),o=r.isObjectLiteralExpression(e)?e:void 0,i=E(o,"server"),n=E(o,"handler"),s=i!==void 0&&w(t.getExpression()),a=n===void 0?void 0:b(t),u=a!==void 0&&a.receiver===void 0;return[s?N(i):void 0,u?N(n):void 0].filter(f=>f!==void 0)},P=new WeakMap,O=t=>{const e=t.getSourceFile(),o=P.get(e.compilerNode);if(o!==void 0)return o;const i=new Set(e.getDescendantsOfKind(d.CallExpression).flatMap(n=>T(n)).map(n=>n.compilerNode));return P.set(e.compilerNode,i),i},A=t=>{const e=t.getParent();return(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e))&&e.getParameters()[0]===t&&O(t).has(e.compilerNode)},Q=t=>{const e=t.getParent();return(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e))&&e.getParameters()[1]===t&&O(t).has(e.compilerNode)},B=t=>t.getNameNode().getDescendantsOfKind(d.BindingElement).some(e=>e.getParent().getParent()===t&&["args","ctx"].includes(I(e))),g=(t,e,o)=>{const i=t.getParent().getParent(),n=I(t);if(t.getDotDotDotToken()!==void 0||e==="trust"&&S(t))return;let s;if(r.isParameterDeclaration(i)){if(!A(i)||B(i))return n==="ctx"?[]:void 0;s=[]}else r.isBindingElement(i)?s=g(i,e,o):r.isVariableDeclaration(i)&&o>0&&(s=c(i.getInitializer(),e,o-1));return s===void 0?void 0:[...s,n]},c=(t,e="discover",o=x)=>{const i=l(t),n=C(i);if(n!==void 0){const s=c(n.object,e,o);return s===void 0?void 0:[...s,n.member]}return r.isIdentifier(i)?H(i,e,o):void 0},H=(t,e,o)=>{const i=t.getText()==="ctx",n=e==="trust"||!i?v(t):void 0;return i&&!r.isVariableDeclaration(n)?r.isBindingElement(n)?g(n,e,o):[]:r.isParameterDeclaration(n)?r.isIdentifier(n.getNameNode())&&A(n)?[]:void 0:r.isBindingElement(n)?g(n,e,o):!(r.isVariableDeclaration(n)&&r.isIdentifier(n.getNameNode())&&o>0)||e==="trust"&&S(n)?void 0:c(n.getInitializer(),e,o-1)},q=t=>c(t,"discover"),K=t=>{const e=c(t);return e===void 0?void 0:["ctx",...e].join(".")},J=(t,e)=>{if(e(t.getText()))return!0;const o=K(t);return o!==void 0&&e(o)},Y=(t,e)=>{const o=l(t),i=C(o);if(i!==void 0&&i.member!==e.at(-1))return!1;const n=o===void 0?void 0:c(o);return n?.length===e.length&&n.every((s,a)=>s===e[a])},Z=(t,e)=>y(t).get(e)??[],U=t=>{const e=new Map;for(const i of p(t,d.BindingElement)){const n=r.isIdentifier(i.getNameNode())?g(i,"discover",x):void 0;n?.length===1&&n[0]!==void 0&&e.set(i.compilerNode,n[0])}const o=new Set([...e.keys()].map(i=>i.name.getText()));return p(t,d.Identifier).flatMap(i=>{const s=o.has(i.getText())&&!r.isBindingElement(i.getParent())?v(i):void 0,a=s===void 0?void 0:e.get(s.compilerNode);return a===void 0?[]:[[a,i]]})},h=new WeakMap,y=t=>{const e=h.get(t.compilerNode);if(e!==void 0)return e;const o=new Map;for(const[n,s]of[...z(t),...U(t)])o.set(n,[...o.get(n)??[],s]);const i=new Map([...o].map(([n,s])=>[n,s.toSorted((a,u)=>a.getPos()-u.getPos())]));return h.set(t.compilerNode,i),i},z=t=>t.getDescendantsOfKind(d.PropertyAccessExpression).flatMap(e=>_(e.getExpression())?[[e.getName(),e]]:[]),_=t=>r.isIdentifier(t)&&c(t)?.length===0,$=t=>{const e=c(t);return e?.length===1&&e[0]==="db"},R=new Set(["asId","createMultipartUpload","fetch","generateUploadUrl","getPresignedUrl","getSignedUrl","getUrl","normalizeId","resumeMultipartUpload","runAction","runMutation","runQuery","store","upload"]),k=new Set(["catch","flatMap","map","reduce","reduceRight","then"]),L=(t,e=x)=>{const o=M(t,u=>{const f=l(u.getExpression()),m=r.isPropertyAccessExpression(f)?f.getName():void 0;return m!==void 0&&(R.has(m)||k.has(m))?!1:void 0}),i=o.root;if(o.verdict!==void 0||!r.isIdentifier(i))return o.verdict??!1;if(c(i,"trust")!==void 0)return!0;const n=v(i),s=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n,a=D(s)&&e>0?s.getInitializer():void 0;return a!==void 0&&L(a,e-1)},ee=t=>(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(o=>F(o)&&c(o,"trust")!==void 0);export{k as C,R as E,Y as a,Q as b,Z as c,$ as d,K as e,q as f,L as g,_ as i,J as m,ee as r};
1
+ import{Node as r,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as C,descendantsOfKind as p,bindingKeyName as I,findObjectProperty as E,isConstDeclaration as D,walkChain as M}from"./isTestPath-DRIdZaij.mjs";import{d as v,b as S,f as F}from"./attribution-BhGR_h0Z.mjs";import{c as b}from"./classify-procedure-call-n9urVsqb.mjs";import{isDefineMutatorCallee as w}from"./MUTATORS_FILENAME-C3OImAxC.mjs";const x=8,N=t=>{if(r.isMethodDeclaration(t))return t;const e=r.isPropertyAssignment(t)?l(t.getInitializer()):void 0,o=r.isShorthandPropertyAssignment(t)?t.getNameNode():e;if(r.isArrowFunction(o)||r.isFunctionExpression(o))return o;const i=r.isIdentifier(o)?v(o):void 0;if(r.isFunctionDeclaration(i))return i;const n=D(i)?l(i.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},T=t=>{const e=l(t.getArguments()[0]),o=r.isObjectLiteralExpression(e)?e:void 0,i=E(o,"server"),n=E(o,"handler"),s=i!==void 0&&w(t.getExpression()),a=n===void 0?void 0:b(t),u=a!==void 0&&a.receiver===void 0;return[s?N(i):void 0,u?N(n):void 0].filter(f=>f!==void 0)},P=new WeakMap,O=t=>{const e=t.getSourceFile(),o=P.get(e.compilerNode);if(o!==void 0)return o;const i=new Set(e.getDescendantsOfKind(d.CallExpression).flatMap(n=>T(n)).map(n=>n.compilerNode));return P.set(e.compilerNode,i),i},A=t=>{const e=t.getParent();return(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e))&&e.getParameters()[0]===t&&O(t).has(e.compilerNode)},Q=t=>{const e=t.getParent();return(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e))&&e.getParameters()[1]===t&&O(t).has(e.compilerNode)},B=t=>t.getNameNode().getDescendantsOfKind(d.BindingElement).some(e=>e.getParent().getParent()===t&&["args","ctx"].includes(I(e))),g=(t,e,o)=>{const i=t.getParent().getParent(),n=I(t);if(t.getDotDotDotToken()!==void 0||e==="trust"&&S(t))return;let s;if(r.isParameterDeclaration(i)){if(!A(i)||B(i))return n==="ctx"?[]:void 0;s=[]}else r.isBindingElement(i)?s=g(i,e,o):r.isVariableDeclaration(i)&&o>0&&(s=c(i.getInitializer(),e,o-1));return s===void 0?void 0:[...s,n]},c=(t,e="discover",o=x)=>{const i=l(t),n=C(i);if(n!==void 0){const s=c(n.object,e,o);return s===void 0?void 0:[...s,n.member]}return r.isIdentifier(i)?H(i,e,o):void 0},H=(t,e,o)=>{const i=t.getText()==="ctx",n=e==="trust"||!i?v(t):void 0;return i&&!r.isVariableDeclaration(n)?r.isBindingElement(n)?g(n,e,o):[]:r.isParameterDeclaration(n)?r.isIdentifier(n.getNameNode())&&A(n)?[]:void 0:r.isBindingElement(n)?g(n,e,o):!(r.isVariableDeclaration(n)&&r.isIdentifier(n.getNameNode())&&o>0)||e==="trust"&&S(n)?void 0:c(n.getInitializer(),e,o-1)},q=t=>c(t,"discover"),K=t=>{const e=c(t);return e===void 0?void 0:["ctx",...e].join(".")},J=(t,e)=>{if(e(t.getText()))return!0;const o=K(t);return o!==void 0&&e(o)},Y=(t,e)=>{const o=l(t),i=C(o);if(i!==void 0&&i.member!==e.at(-1))return!1;const n=o===void 0?void 0:c(o);return n?.length===e.length&&n.every((s,a)=>s===e[a])},Z=(t,e)=>y(t).get(e)??[],U=t=>{const e=new Map;for(const i of p(t,d.BindingElement)){const n=r.isIdentifier(i.getNameNode())?g(i,"discover",x):void 0;n?.length===1&&n[0]!==void 0&&e.set(i.compilerNode,n[0])}const o=new Set([...e.keys()].map(i=>i.name.getText()));return p(t,d.Identifier).flatMap(i=>{const s=o.has(i.getText())&&!r.isBindingElement(i.getParent())?v(i):void 0,a=s===void 0?void 0:e.get(s.compilerNode);return a===void 0?[]:[[a,i]]})},h=new WeakMap,y=t=>{const e=h.get(t.compilerNode);if(e!==void 0)return e;const o=new Map;for(const[n,s]of[...z(t),...U(t)])o.set(n,[...o.get(n)??[],s]);const i=new Map([...o].map(([n,s])=>[n,s.toSorted((a,u)=>a.getPos()-u.getPos())]));return h.set(t.compilerNode,i),i},z=t=>t.getDescendantsOfKind(d.PropertyAccessExpression).flatMap(e=>_(e.getExpression())?[[e.getName(),e]]:[]),_=t=>r.isIdentifier(t)&&c(t)?.length===0,$=t=>{const e=c(t);return e?.length===1&&e[0]==="db"},R=new Set(["asId","createMultipartUpload","fetch","generateUploadUrl","getPresignedUrl","getSignedUrl","getUrl","normalizeId","resumeMultipartUpload","runAction","runMutation","runQuery","store","upload"]),k=new Set(["catch","flatMap","map","reduce","reduceRight","then"]),L=(t,e=x)=>{const o=M(t,u=>{const f=l(u.getExpression()),m=r.isPropertyAccessExpression(f)?f.getName():void 0;return m!==void 0&&(R.has(m)||k.has(m))?!1:void 0}),i=o.root;if(o.verdict!==void 0||!r.isIdentifier(i))return o.verdict??!1;if(c(i,"trust")!==void 0)return!0;const n=v(i),s=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n,a=D(s)&&e>0?s.getInitializer():void 0;return a!==void 0&&L(a,e-1)},ee=t=>(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(o=>F(o)&&c(o,"trust")!==void 0);export{k as C,R as E,Y as a,Q as b,Z as c,$ as d,K as e,q as f,L as g,_ as i,J as m,ee as r};
@@ -1 +1 @@
1
- import{SyntaxKind as g,Node as n}from"ts-morph";import{descendantsOfKind as p}from"./isTestPath-DRIdZaij.mjs";import{d as l}from"./context-root-DnvrQxae.mjs";const c=e=>n.isPropertyAccessExpression(e)&&e.getName()==="db"||n.isIdentifier(e)&&e.getText()==="db"||l(e),b=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),E=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t)||!b.has(t.getName()))return;const s=t.getExpression();if(c(s))return{options:e.getArguments()[1],table:d(e)};if(n.isPropertyAccessExpression(s)){const o=s.getExpression();if(c(o))return{options:e.getArguments()[0],table:s.getName()}}},f=(e,t)=>{const s=e.getExpression();return!n.isPropertyAccessExpression(s)||!t.has(s.getName())?!1:c(s.getExpression())},d=e=>{const t=e.getArguments()[0];return t&&n.isStringLiteral(t)?t.getLiteralText():""},A=(e,t,s)=>{const o=new Set,i=new Set;for(const a of p(e,g.CallExpression))if(f(a,t)){const r=d(a);r!==""&&o.add(r)}else if(f(a,s)){const r=d(a);r!==""&&i.add(r)}return{tablesRead:[...o],tablesWritten:[...i]}};export{c as i,E as r,A as t};
1
+ import{SyntaxKind as g,Node as n}from"ts-morph";import{descendantsOfKind as p}from"./isTestPath-DRIdZaij.mjs";import{d as l}from"./context-root-DP9WbBI_.mjs";const c=e=>n.isPropertyAccessExpression(e)&&e.getName()==="db"||n.isIdentifier(e)&&e.getText()==="db"||l(e),b=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),E=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t)||!b.has(t.getName()))return;const s=t.getExpression();if(c(s))return{options:e.getArguments()[1],table:d(e)};if(n.isPropertyAccessExpression(s)){const o=s.getExpression();if(c(o))return{options:e.getArguments()[0],table:s.getName()}}},f=(e,t)=>{const s=e.getExpression();return!n.isPropertyAccessExpression(s)||!t.has(s.getName())?!1:c(s.getExpression())},d=e=>{const t=e.getArguments()[0];return t&&n.isStringLiteral(t)?t.getLiteralText():""},A=(e,t,s)=>{const o=new Set,i=new Set;for(const a of p(e,g.CallExpression))if(f(a,t)){const r=d(a);r!==""&&o.add(r)}else if(f(a,s)){const r=d(a);r!==""&&i.add(r)}return{tablesRead:[...o],tablesWritten:[...i]}};export{c as i,E as r,A as t};
@@ -0,0 +1 @@
1
+ import"./declared-output-Iaar469J.mjs";import"./isTestPath-DRIdZaij.mjs";import"./attribution-BhGR_h0Z.mjs";import"./unwrap-handler-return-DUzluwPj.mjs";import"./ip-reads-ByzaRhd2.mjs";import"./classify-procedure-call-n9urVsqb.mjs";import{d as f}from"./index-BH3e-J44.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
@@ -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-BRI5W-Mp.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};
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-BZ164dkJ.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
+ 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-BRI5W-Mp.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};
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};
@@ -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-h8Y7xDjq.mjs";import{r as L}from"./chain-CXiqZFUk.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};
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};
@@ -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-BRI5W-Mp.mjs";import{c as b}from"./classify-procedure-call-BZ164dkJ.mjs";import{r as h}from"./chain-CXiqZFUk.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
+ 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-BZ164dkJ.mjs";import{e as m}from"./exported-procedure-chains-h8Y7xDjq.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
1
+ import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-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 N}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{i as q}from"./schema-BgM8A3XV.mjs";import{a as I,I as L,G as y}from"./shared-Cn7dMQ_u.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...N.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(r=>q(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=e=>e.hasScheduler?`
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
- `:"",P=e=>e?`
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 N}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
- `:"",G=e=>e?`
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
- `:"",_=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}']:[]],M=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> = {};"]:[],...l(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>;"]:[]],W=e=>f(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
386
- public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
387
- this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
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
- }`),B=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. */
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
- }`],...l(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. */
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
- }`]:[],...W(e)],H=e=>{const r=a=>e.hasScheduler?`
460
- ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" 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
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 } : {}),${r("D1CtxDbOptions")}
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 } : {}),${r("SqlCtxDbOptions")}
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
- : {}),`]:[],...l(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 t.length>0?`
568
- ${t.join(`
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
- `:""},U=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],F=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],z=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],J=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],K=e=>e?['import notifyConfig from "../notify.js";']:[],V=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],Y=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],X=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,i=n?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","SecurityOptions","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],c=[...t||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},Z=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:n,hasQueue:i,hasScheduler:d,hasStorage:c,hasWorkflow:o}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...F(r,t),...J(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";']:[],...z(n),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...V(e),...X(e),"",...U(e.identity),...Y(e),...a||s?['import schema from "../schema.js";']:[],...K(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";']:[]]},ee=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
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)},`:"",te=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,re=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
573
- ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`).join(`
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);`]:[],...l(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
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
- }`]:[]],ae=[` const adminRevocations = this.adminRevocationsSelector?.(env);
583
+ }`]:[]],oe=[` const adminRevocations = this.adminRevocationsSelector?.(env);
583
584
 
584
585
  if (adminRevocations) {
585
586
  options.adminRevocations = adminRevocations;
586
- }`],S=e=>(e.liveStreamDeclarations??[]).map(r=>{if(I(r.exportName,"live stream export name"),!L.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),se=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ne=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],oe=e=>p(e)?`liveStreamRouter([
587
- ${S(e).join(`
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",ie=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],ce=e=>[...re(e),...e.hasAdminRevocations===!1?[]:ae,...e.hasScheduler?[` if (this.schedulerDeclaration) {
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>;
@@ -622,6 +623,11 @@ ${S(e).join(`
622
623
  options.exportGlobals = buildGlobalExporter(database);
623
624
  options.syncGlobals = buildGlobalCdcSync(database);
624
625
  options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
626
+ // \`lunora migrate apply\` runs the generated SQL files against this binding, recording each in
627
+ // \`__lunora_sql_migrations\`. A file runs once per stage, and nothing else runs it. The schema lets a
628
+ // column a file adds be filled the way the runtime fills it, so its rows never read NULL.
629
+ options.applySqlMigrations = (request) =>
630
+ applySqlMigrationFiles(database, request.files, { ...request, schema: schema as unknown as D1CtxDbOptions["schema"] });
625
631
  }
626
632
  }`]:[],...e.hasHyperdriveGlobal?[` const hyperdriveDeclaration = this.hyperdriveGlobalDeclaration;
627
633
 
@@ -713,7 +719,7 @@ ${S(e).join(`
713
719
  // Memoised on the declaration: each worker built for a new \`env\` runs
714
720
  // these options again, and \`options(env)\` rebuilds every plugin.
715
721
  discoveryPaths,
716
- internalSecret,${ee(e)}
722
+ internalSecret,${ae(e)}${re(e)}
717
723
  namespace,
718
724
  ...(objectName === undefined ? {} : { objectName }),
719
725
  });
@@ -755,7 +761,7 @@ ${S(e).join(`
755
761
  // the same claims (role, expiry, profile, and the active organization and
756
762
  // team checked against membership) on the identity, and it is unit-tested
757
763
  // where this template cannot be.
758
- return resolveSessionIdentity(auth, (request as Request).headers);
764
+ return resolveSessionIdentity(auth, (request as Request).headers${te(e)});
759
765
  };
760
766
  const authInstance = getAuth();
761
767
 
@@ -852,16 +858,16 @@ ${S(e).join(`
852
858
  options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
853
859
  }`:` if (this.accessSelector) {
854
860
  options.resolveIdentity = createAccessResolver(this.accessSelector(env));
855
- }`]:[],...ie(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
856
- ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
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(`
857
863
  `)}
858
- };`]:[]],le=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,"]:[]," }),"]:[],de=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,"]:[],...le(e),...se(e),...ne(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(r=>`(env as Record<string, unknown>)[${JSON.stringify(r)}]`).join(" ?? ")}) as WorkerOptions["spaAssets"],`]],he=e=>e?`
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?`
859
865
  /** The identity memo per \`env\` object, owned by one assembled worker. */
860
866
  type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
861
- `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ue=e=>{if(!E(e))return"";const t=[[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
+ `:"",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`
862
868
  /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
863
869
  interface DeferredModules {
864
- ${t.map(([a,s])=>` ${a}: ${s};`).join(`
870
+ ${r.map(([a,s])=>` ${a}: ${s};`).join(`
865
871
  `)}
866
872
  }
867
873
 
@@ -871,19 +877,19 @@ let deferredModules: Promise<DeferredModules> | undefined;
871
877
  const loadDeferredModules = (): Promise<DeferredModules> =>
872
878
  (deferredModules ??= (async (): Promise<DeferredModules> => {
873
879
  return {
874
- ${t.map(([a,,s])=>` ${a}: ${s},`).join(`
880
+ ${r.map(([a,,s])=>` ${a}: ${s},`).join(`
875
881
  `)}
876
882
  };
877
883
  })());
878
- `},pe=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
884
+ `},ge=(e,t)=>{const r=`buildWorker(rawEnv as Env${t})`,a=e?`
879
885
  await ensureAuth(env);`:"",s=e?`
880
886
  await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"target",eventWorkerLine:`
881
- const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
882
- worker ??= ${t};`}},me=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
883
- const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},ke=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
884
- `:"",be=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(s=>`${a}{ agent: lunoraAgentDefinitions.${s.exportName}, className: ${JSON.stringify(s.className)} },`).join(`
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(`
885
891
  `);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
886
- ${t(" ")}
892
+ ${r(" ")}
887
893
  ]);
888
894
 
889
895
  `:` let agentEmail: ReturnType<typeof dispatchAgentEmail> | undefined;
@@ -893,21 +899,21 @@ ${t(" ")}
893
899
  const [{ dispatchAgentEmail: dispatch }, lunoraAgentDefinitions] = await Promise.all([import("@lunora/agent/inbound"), import("../agents.js")]);
894
900
 
895
901
  agentEmail ??= dispatch([
896
- ${t(" ")}
902
+ ${r(" ")}
897
903
  ]);
898
904
  }
899
905
 
900
906
  return agentEmail(message, rawEnv, context);
901
907
  };
902
908
 
903
- `},ge=e=>e.securityHeaders===void 0?"":`
909
+ `},fe=e=>e.securityHeaders===void 0?"":`
904
910
  /**
905
911
  * \`security.headers\` from \`lunora.config\`: the baseline security headers the Worker sends, and the same values
906
912
  * the build writes into the static assets' \`_headers\`. An app that calls \`createWorker\` itself passes it as
907
913
  * \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
908
914
  */
909
915
  const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
910
- `,ve=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),Se=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,s=_(t),n=ce(t),i=a?` let auth: LunoraAuth | null = null;
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;
911
917
  let authInit: Promise<void> | null = null;
912
918
  // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
913
919
  // \`assemble()\` has its own auth closure and must not share.
@@ -978,11 +984,11 @@ const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.s
978
984
  return false;
979
985
  },
980
986
  );
981
- `:"",{asyncIfDeferred:c,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=me(t),{ensureAuthCall:R,ensureRawAuthCall:D,eventWorker:m,eventWorkerLine:b}=pe(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,A=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,x=t.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
982
- host ? withFrameworkWorker(${oe(t)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,C=t.hasFramework?"host?: FrameworkHostHandler":"",O=be(t),T=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
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. */
983
989
  public build(): ComposedApp {
984
990
  return this.assemble();
985
- }${t.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}${Z(t).join(`
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(`
986
992
  `)}
987
993
 
988
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). */
@@ -990,11 +996,11 @@ type Selector<Env, T> = (env: Env) => T | undefined;
990
996
 
991
997
  /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
992
998
  type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
993
- ${ge(t)}${he(a)}${ue(t)}${t.jurisdiction?`
999
+ ${fe(r)}${me(a)}${be(r)}${r.jurisdiction?`
994
1000
  // Module scope, so every isolate loading this script (the worker and each Durable
995
1001
  // Object class it exports) knows the schema's jurisdiction before a request runs.
996
1002
  // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
997
- declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
1003
+ declareAppJurisdiction(${JSON.stringify(r.jurisdiction)});
998
1004
  `:""}
999
1005
  ${s.join(`
1000
1006
 
@@ -1015,32 +1021,32 @@ interface ComposedApp extends LunoraWorker {
1015
1021
  * first request so per-isolate singletons are built once.
1016
1022
  */
1017
1023
  class AppBuilder<Env extends object> {
1018
- ${M(t).join(`
1024
+ ${W(r).join(`
1019
1025
  `)}
1020
1026
 
1021
1027
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
1022
1028
 
1023
- ${B(t).join(`
1029
+ ${H(r).join(`
1024
1030
 
1025
1031
  `)}
1026
1032
 
1027
1033
  ${T}
1028
1034
 
1029
1035
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
1030
- private assemble(${C}): ComposedApp {
1031
- const ShardDO = createShardDO({${H(t)}});
1036
+ private assemble(${O}): ComposedApp {
1037
+ const ShardDO = createShardDO({${U(r)}});
1032
1038
 
1033
1039
  // Per-isolate singletons: the worker (and auth instance) are expensive to
1034
1040
  // build, so the first request constructs them and every later request on
1035
1041
  // the same isolate reuses them.
1036
1042
  let worker: LunoraWorker | null = null;
1037
1043
  ${i}${d}
1038
- ${x}
1044
+ ${C}
1039
1045
 
1040
1046
  const composed: ComposedApp = {
1041
1047
  ShardDO,
1042
1048
  fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
1043
- const env = rawEnv as Env;${h}${R}
1049
+ const env = rawEnv as Env;${h}${D}
1044
1050
  worker ??= buildWorker(env${o});
1045
1051
 
1046
1052
  return worker.fetch(request, rawEnv, context);
@@ -1049,29 +1055,29 @@ ${x}
1049
1055
 
1050
1056
  return ${m}.scheduled(controller, rawEnv, context);
1051
1057
  },
1052
- serverQuery: ${c}(request, rawEnv, reference, args, options) => {${h}${D}
1058
+ serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${A}
1053
1059
  worker ??= buildWorker(rawEnv as Env${o});
1054
1060
 
1055
1061
  return worker.serverQuery(request, rawEnv, reference, args, options);
1056
- },${t.hasQueue||t.hasFramework?`
1062
+ },${r.hasQueue||r.hasFramework?`
1057
1063
  queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}${b}
1058
1064
 
1059
1065
  return ${m}.queue?.(batch, rawEnv, context);
1060
1066
  },`:""}
1061
1067
  };
1062
1068
 
1063
- ${O} if (this.emailHandler) {
1069
+ ${q} if (this.emailHandler) {
1064
1070
  const handler = this.emailHandler;
1065
1071
 
1066
1072
  composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
1067
1073
  }
1068
- ${t.hasFramework?`
1074
+ ${r.hasFramework?`
1069
1075
  // A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
1070
1076
  // does). Nothing in Lunora serves one, so when the app registered no handler
1071
1077
  // of its own the host's is the only one there is — forward to it rather than
1072
1078
  // dropping the entry.
1073
1079
  if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
1074
- composed.email = ${c}(message, rawEnv, context) => {${h}${b}
1080
+ composed.email = ${l}(message, rawEnv, context) => {${h}${b}
1075
1081
 
1076
1082
  return ${m}.email?.(message, rawEnv, context) ?? Promise.resolve();
1077
1083
  };
@@ -1079,11 +1085,11 @@ ${t.hasFramework?`
1079
1085
  `:""}
1080
1086
  return composed;
1081
1087
  }
1082
- ${$(t)}${P(t.hasStorage)}
1088
+ ${P(r)}${G(r.hasStorage)}
1083
1089
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
1084
- private buildWorkerOptions(env: Env, ${A}): WorkerOptions {
1090
+ private buildWorkerOptions(env: Env, ${x}): WorkerOptions {
1085
1091
  const options: WorkerOptions = {
1086
- ${de(t).join(`
1092
+ ${pe(r).join(`
1087
1093
  `)}
1088
1094
  };
1089
1095
 
@@ -1100,11 +1106,11 @@ ${n.join(`
1100
1106
  `:""} for (const fn of this.extendFns) {
1101
1107
  Object.assign(options, fn(env, { ...options }));
1102
1108
  }
1103
- ${t.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
+ ${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"}
1104
1110
  return options;
1105
1111
  }
1106
1112
  }
1107
- ${G(t.hasGlobal)}
1113
+ ${_(r.hasGlobal)}
1108
1114
  /**
1109
1115
  * Shape of the project's root \`lunora.config.*\`.
1110
1116
  *
@@ -1146,6 +1152,6 @@ interface LunoraConfig<Env extends object = object> {
1146
1152
  */
1147
1153
  const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
1148
1154
 
1149
- export { AppBuilder, defineApp${t.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
1150
- export type { ${ve(t)} };
1151
- `};export{Se as emitApp,ke as emitAuthModule};
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-CRFaUMKQ.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
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};