@lunora/codegen 1.0.0-alpha.243 → 1.0.0-alpha.245
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +132 -4
- package/dist/index.d.ts +132 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AGENTS_FILENAME-Bb2jxbOa.mjs → AGENTS_FILENAME-D8SgT3OR.mjs} +1 -1
- package/dist/packem_shared/{CONTAINERS_FILENAME-CGB4bqUr.mjs → CONTAINERS_FILENAME-CBCG6g9n.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-D-zkySYF.mjs +1 -0
- package/dist/packem_shared/{FLAGS_FILENAME-BedPDCsR.mjs → FLAGS_FILENAME-W5XQz_Po.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-B6cKrN_m.mjs → MUTATORS_FILENAME-DqWOgC5Z.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-Cri3NT5U.mjs → NOTIFY_FILENAME-C1J_47et.mjs} +1 -1
- package/dist/packem_shared/OPENRPC_VERSION-Cr7Zzp6s.mjs +3 -0
- package/dist/packem_shared/{QUEUES_FILENAME-BzOl92QK.mjs → QUEUES_FILENAME-RGwht3Xu.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-KDyLA-v5.mjs +11 -0
- package/dist/packem_shared/{SHAPES_FILENAME-zJgzynXR.mjs → SHAPES_FILENAME-DRUFomCj.mjs} +1 -1
- package/dist/packem_shared/{WORKFLOWS_FILENAME-DNaUHGS8.mjs → WORKFLOWS_FILENAME-4-ib4HH-.mjs} +1 -1
- package/dist/packem_shared/buildOpenApiDocument-SxfElVzK.mjs +3 -0
- package/dist/packem_shared/chain-mte5djRJ.mjs +1 -0
- package/dist/packem_shared/{classify-procedure-call-BztLe76A.mjs → classify-procedure-call-CmcShAze.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-CjDzLU8p.mjs → context-property-calls-CWf9-6G5.mjs} +1 -1
- package/dist/packem_shared/{discoverAuthApiCalls-FxrdBeVt.mjs → discoverAuthApiCalls-DoSN_yc3.mjs} +1 -1
- package/dist/packem_shared/{discoverCrons-0lNudk0S.mjs → discoverCrons-BEALHx1S.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-BsmX-sEq.mjs → discoverFunctions-BcBzcG5x.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-BcXI9CNt.mjs → discoverHttpRoutes-CJHS4llq.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-Bkbh4tG7.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-CFJ3IVeI.mjs → discoverInserts-DpuLYPPd.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-B0w8gM0S.mjs +1 -0
- package/dist/packem_shared/{discoverMigrations-DbrHwcGE.mjs → discoverMigrations-Dt7ywfZv.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-CSQ_GDcA.mjs → discoverNondeterministicCalls-CNJV2BiP.mjs} +1 -1
- package/dist/packem_shared/discoverQueries-BcdqjYky.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-30Wtbc0P.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-CPmAGL0W.mjs → discoverRlsMetadata-mXBmPOGj.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-BO4qC77y.mjs → discoverRlsProcedures-F4Cy-kSi.mjs} +1 -1
- package/dist/packem_shared/{discoverSandboxUsage-CrjZ6yNg.mjs → discoverSandboxUsage-DkbwwFvO.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-D5R60b4F.mjs +1 -0
- package/dist/packem_shared/{discoverStorageRulesMetadata-D8VYflWt.mjs → discoverStorageRulesMetadata-D3Ot9g5f.mjs} +1 -1
- package/dist/packem_shared/emitAgents-CnQEPybh.mjs +1 -0
- package/dist/packem_shared/{emitApp-D_9NVcvv.mjs → emitApp-DsMk4tpo.mjs} +4 -2
- package/dist/packem_shared/{emitServer-pF_fhA82.mjs → emitServer-nvzMxk3d.mjs} +59 -50
- package/dist/packem_shared/{emitShard-DID_s1FK.mjs → emitShard-BiKPSgNP.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-CmCDiPBV.mjs → exported-procedure-chains-D48EXUVQ.mjs} +1 -1
- package/dist/packem_shared/{fingerprintSchemaSources-L3nGKDQt.mjs → fingerprintSchemaSources-Cl1CJFeh.mjs} +1 -1
- package/dist/packem_shared/{index-BoaHhVtM.mjs → index-D7dKfGPh.mjs} +1 -1
- package/dist/packem_shared/listLunoraSourceFiles-CSlcBYlo.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-6Zk3abcc.mjs +1 -0
- package/dist/packem_shared/modules-DyCocr1e.mjs +1 -0
- package/dist/packem_shared/{parse-validator-C94Yiabo.mjs → parse-validator-C6fHL7OS.mjs} +1 -1
- package/dist/packem_shared/readServiceBindings-D9Wi_qGU.mjs +1 -0
- package/dist/packem_shared/{shard-BVzXMtWg.mjs → shard-D6EZdlSg.mjs} +61 -61
- package/dist/packem_shared/{shard-runtime-oIXHEMU7.mjs → shard-runtime-D9GRosnD.mjs} +14 -6
- package/dist/packem_shared/{unwrap-handler-return-CoV_GK33.mjs → unwrap-handler-return-DVY_kFF7.mjs} +1 -1
- package/package.json +6 -6
- package/dist/packem_shared/DEFAULT_TARGET-wK6-Tado.mjs +0 -1
- package/dist/packem_shared/OPENRPC_VERSION-Cl6P9WGv.mjs +0 -3
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DX6sZtLG.mjs +0 -9
- package/dist/packem_shared/buildOpenApiDocument-nYvBhjxu.mjs +0 -3
- package/dist/packem_shared/chain-H2N_uKgj.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-D9qXqTq3.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-CV_Cc2_g.mjs +0 -1
- package/dist/packem_shared/discoverQueries-C7y8i_Ga.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-fu7fC0i_.mjs +0 -1
- package/dist/packem_shared/discoverSchema-D8DBDHEg.mjs +0 -1
- package/dist/packem_shared/emitAgents-C3ygr0M8.mjs +0 -1
- package/dist/packem_shared/listLunoraSourceFiles-DP-5e-RE.mjs +0 -1
- package/dist/packem_shared/loadProjectConfig-CKsFNgn3.mjs +0 -1
- package/dist/packem_shared/queries-B-f4jO-x.mjs +0 -1
package/dist/packem_shared/{discoverFunctions-BsmX-sEq.mjs → discoverFunctions-BcBzcG5x.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as P}from"./declared-output-Iaar469J.mjs";import{s as b}from"./paths-C-9fwEgQ.mjs";import{findObjectProperty as c,bindingKeyName as A,listLunoraSourceFiles as F,lunoraRelativePath as N}from"./listLunoraSourceFiles-
|
|
1
|
+
import{d as P}from"./declared-output-Iaar469J.mjs";import{s as b}from"./paths-C-9fwEgQ.mjs";import{findObjectProperty as c,bindingKeyName as A,listLunoraSourceFiles as F,lunoraRelativePath as N}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{u as y,p as O,c as m,r as z}from"./unwrap-handler-return-DVY_kFF7.mjs";import{b as d,c as C}from"./classify-procedure-call-CmcShAze.mjs";import{Node as n,SyntaxKind as S}from"ts-morph";import{r as h,p as x,a as L}from"./parse-validator-C6fHL7OS.mjs";const k=i=>{const t=i.getArguments()[0];if(!t||!n.isObjectLiteralExpression(t))return"unknown";const e=c(t,"handler");if(!e||!n.isPropertyAssignment(e))return"unknown";const r=e.getInitializer();return!r||!(n.isArrowFunction(r)||n.isFunctionExpression(r))?"unknown":y(r)},I=i=>{const t=i.getArguments()[0];return!t||!(n.isArrowFunction(t)||n.isFunctionExpression(t))?"unknown":y(t)},T=i=>{let t={};for(const e of d(i)){if(e.name!=="input")continue;const r=e.call.getArguments()[0],s=r!==void 0&&n.isExpression(r)?h(r):void 0;s!==void 0&&(t={...x(s),...t})}return t},V=i=>{const t=d(i).find(r=>r.name==="output");if(!t)return;const e=t.call.getArguments()[0];return e&&n.isExpression(e)?O(t.call,()=>L(e)):void 0},p=(i,t)=>{const e=c(i,t);if(e===void 0||!n.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&n.isStringLiteral(r)?r.getLiteralValue():void 0},v=(i,t)=>{const e=c(i,t);if(e===void 0||!n.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&n.isNumericLiteral(r)?r.getLiteralValue():void 0},w=i=>{const t=c(i,"cache");if(t===void 0||!n.isPropertyAssignment(t))return;const e=t.getInitializer();if(e===void 0||!n.isObjectLiteralExpression(e))return;const r=p(e,"scope"),s=v(e,"maxAge"),o=v(e,"staleWhileRevalidate"),a=p(e,"tag"),l=p(e,"vary"),g={...s===void 0?{}:{maxAge:s},...r==="private"||r==="public"?{scope:r}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(g).length===0?void 0:g},D=i=>{if(i===void 0||!n.isObjectLiteralExpression(i))return{};const t=w(i),e=c(i,"rest");return e!==void 0&&n.isPropertyAssignment(e)?{...t===void 0?{}:{cache:t},rest:e.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},j=i=>{const t=d(i).find(e=>e.name==="expose");return t?D(t.call.getArguments()[0]):void 0},R=i=>{const t=i.getArguments()[0];if(!t||!n.isObjectLiteralExpression(t))return{};const e=c(t,"args");if(!e||!n.isPropertyAssignment(e))return{};const r=e.getInitializer(),s=r===void 0?void 0:h(r);return s===void 0?{}:x(s)},B=8,u=(i,t=0)=>{if(t>B)return;if(n.isCallExpression(i))return i;if(n.isParenthesizedExpression(i)||n.isAsExpression(i)||n.isSatisfiesExpression(i)||n.isNonNullExpression(i))return u(i.getExpression(),t+1);if(!n.isIdentifier(i)&&!n.isPropertyAccessExpression(i))return;const e=i.getSymbol()?.getValueDeclaration();return e?f(e,t+1):void 0},f=(i,t)=>{if(n.isVariableDeclaration(i)||n.isPropertyAssignment(i)){const e=i.getInitializer();return e?u(e,t):void 0}if(n.isShorthandPropertyAssignment(i)){const e=i.getValueSymbol()?.getValueDeclaration();return e?f(e,t+1):void 0}if(n.isBindingElement(i)){const e=A(i),o=i.getFirstAncestorByKind(S.VariableDeclaration)?.getInitializer()?.getType().getProperty(e)?.getValueDeclaration();return o?f(o,t+1):void 0}},$=i=>{const t=i.getNameNode();if(n.isObjectBindingPattern(t)){const s=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&s.push([o.getName(),a])}return s}const e=i.getInitializer(),r=e&&(n.isCallExpression(e)?e:u(e));return r?[[i.getName(),r]]:[]},W=i=>{const t=C(i);if(!t)return;const{receiver:e}=t;if(e){const r=j(e),s=m(()=>V(e)),o=m(()=>I(i)),a=P({kind:t.kind,output:s.value});return z(a?s.erased:o.erased),{args:T(e),...r?{expose:r}:{},kind:t.kind,...s.value?{output:s.value}:{},returnType:o.value,visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:R(i),kind:t.kind,returnType:k(i),visibility:t.visibility}},E=(i,t,e)=>{const r=W(i);if(r)return{args:r.args,exportName:t,filePath:e,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},visibility:r.visibility,...r.expose?{expose:r.expose}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{}}},_=(i,t)=>{const e=[];for(const r of i.getExportAssignments()){if(r.isExportEquals())continue;const s=u(r.getExpression()),o=s?E(s,"default",t):void 0;o&&e.push(o)}return e},H=(i,t)=>{const e=[];for(const r of i.getVariableStatements())if(r.isExported())for(const s of r.getDeclarations())for(const[o,a]of $(s)){const l=E(a,o,t);l&&e.push(l)}return e.push(..._(i,t)),e},K=i=>{const t=new Map;for(const e of i){const r=b(e.filePath),s=t.get(r);if(s&&s!==e.filePath)throw Object.assign(new Error(`Namespace collision: "${s}" and "${e.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[s,e.filePath],status:500});t.set(r,e.filePath)}},Y=(i,t)=>{const e=F(t),r=[];for(const s of e){const o=i.getSourceFile(s)??i.addSourceFileAtPath(s),a=N(t,s);r.push(...H(o,a))}return r.sort((s,o)=>`${s.filePath}:${s.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),K(r),r};export{Y as default};
|
package/dist/packem_shared/{discoverHttpRoutes-BcXI9CNt.mjs → discoverHttpRoutes-CJHS4llq.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{a as m,p as l}from"./parse-validator-
|
|
1
|
+
import{Node as i}from"ts-morph";import{a as m,p as l}from"./parse-validator-C6fHL7OS.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{u as f}from"./unwrap-handler-return-DVY_kFF7.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),g=new Set(["body","params","searchParams"]),E=new Set(["handler","stream"]),v=r=>{const e=r.getArguments()[0];if(e&&i.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&i.isObjectLiteralExpression(e)?l(e):{}},P=r=>{if(!i.isCallExpression(r))return;const e=r.getExpression();if(!i.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!i.isIdentifier(n)||n.getText()!=="httpRoute")return;const s=v(r);return s===void 0?void 0:{method:o.toUpperCase(),path:s}},S=(r,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},n=r.getExpression();if(!i.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;i.isCallExpression(s);){const a=s.getExpression();if(!i.isPropertyAccessExpression(a))break;const c=a.getName();if(u.has(c))break;if(g.has(c)){const p=x(s);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=s.getArguments()[0];p&&i.isExpression(p)&&(o.output=m(p))}s=a.getExpression()}const t=P(s);if(t)return o.method=t.method,o.path=t.path,o},A=r=>{const e=r.getArguments()[0];return!e||!(i.isArrowFunction(e)||i.isFunctionExpression(e))?"unknown":f(e)},T=(r,e,o,n)=>{const s=e.getName();if(!E.has(s))return;const t=S(r,s);if(!(t?.method===void 0||t.path===void 0))return{body:t.body,exportName:o,filePath:n,method:t.method,params:t.params,path:t.path,searchParams:t.searchParams,stream:t.stream,...t.stream?{chunkType:A(r)}:{},...t.output?{output:t.output}:{}}},b=(r,e)=>{const o=[];for(const n of r.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const t=s.getInitializer();if(!t||!i.isCallExpression(t))continue;const a=t.getExpression();if(!i.isPropertyAccessExpression(a))continue;const c=T(t,a,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=d(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),a=h(e,s);n.push(...b(t,a))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as o}from"./context-property-calls-CWf9-6G5.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SyntaxKind as c,Node as n}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,enclosingExportName as g,isDatabaseAccessor as d}from"./listLunoraSourceFiles-
|
|
1
|
+
import{SyntaxKind as c,Node as n}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,enclosingExportName as g,isDatabaseAccessor as d}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const m=t=>{const e=t.getExpression();if(!n.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return d(r)},p=t=>{if(!n.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const i of r)if(n.isVariableDeclaration(i)){const s=i.getInitializer();if(s&&n.isStringLiteral(s))return s.getLiteralText()}},x=t=>{const e=t.getArguments()[0];return e?n.isStringLiteral(e)?e.getLiteralText():p(e)??"":""},v=(t,e)=>{const r=[];for(const i of f(e)){const s=t.getSourceFile(i)??t.addSourceFileAtPath(i),l=u(e,i);for(const o of s.getDescendantsOfKind(c.CallExpression)){if(!m(o))continue;const a=g(o);a!==""&&r.push({exportName:a,file:l,line:o.getStartLineNumber(),table:x(o)})}}return r};export{v as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./listLunoraSourceFiles-CSlcBYlo.mjs";import"./classify-procedure-call-CmcShAze.mjs";import{d as p}from"./index-D7dKfGPh.mjs";export{p as default};
|
package/dist/packem_shared/{discoverMigrations-DbrHwcGE.mjs → discoverMigrations-Dt7ywfZv.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SyntaxKind as g,Node as s}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as m}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,lunoraRelativePath as h,findObjectProperty as I}from"./listLunoraSourceFiles-
|
|
1
|
+
import{SyntaxKind as g,Node as s}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as m}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,lunoraRelativePath as h,findObjectProperty as I}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const P=r=>{const i=r.getSymbol();if(!i)return r.getText()==="defineMigration";for(const t of i.getDeclarations())if(s.isImportSpecifier(t))return m(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMigration":!1;return!1},d=(r,i)=>{const t=I(r,i);if(!t||!s.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&s.isStringLiteral(e)?e.getLiteralValue():void 0},b=(r,i)=>{const t=r.getInitializer();if(t?.getKind()!==g.CallExpression)return;const e=t.getExpression();if(!s.isIdentifier(e)||!P(e))return;const o=t.getArguments()[0];if(!o||!s.isObjectLiteralExpression(o))return;const n=d(o,"id"),a=r.getName();if(n===void 0||n.trim()==="")throw u(o,`Migration "${a}" in "${i}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});return{exportName:a,filePath:i,id:n,table:d(o,"table")??""}},M=r=>{const i=new Map;for(const t of r){const e=i.get(t.id);if(e!==void 0)throw Object.assign(new Error(`Duplicate migration id "${t.id}": declared in both "${e}" and "${t.filePath}". Migration ids must be unique across the project.`),{code:"DUPLICATE_MIGRATION_ID",id:t.id,name:"LunoraError",paths:[e,t.filePath],status:500});i.set(t.id,t.filePath)}},A=(r,i)=>{const t=p(i),e=[];for(const o of t){const n=r.getSourceFile(o)??r.addSourceFileAtPath(o),a=h(i,o);for(const c of n.getVariableStatements())if(c.isExported())for(const f of c.getDeclarations()){const l=b(f,a);l&&e.push(l)}}return e.sort((o,n)=>o.id.localeCompare(n.id)),M(e),e};export{A as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as l,handlerOf as d}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as l,handlerOf as d}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{c as f}from"./classify-procedure-call-CmcShAze.mjs";const u={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},m=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),p=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},h=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=p(t.getExpression());if(i!==void 0)return n==="fetch"&&m.has(i)?"fetch":u[`${i}.${n}`]},x=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},N=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=f(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=d(t,n.receiver);return i?{exportName:e.getName(),handler:i,kind:n.kind}:void 0},E=(e,t)=>{const n=[];for(const i of e.handler.getDescendantsOfKind(a.CallExpression)){const o=h(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}for(const i of e.handler.getDescendantsOfKind(a.NewExpression)){const o=x(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}return n},S=(e,t)=>{const n=[];for(const i of e.getVariableStatements())if(i.isExported())for(const o of i.getDeclarations()){const r=N(o);r&&n.push(...E(r,t))}return n},w=(e,t)=>{const n=[];for(const i of c(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,l(t,i)))}return n};export{w as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SyntaxKind as u,Node as i}from"ts-morph";import{listLunoraSourceFiles as d,lunoraRelativePath as g,enclosingExportName as p,isDatabaseAccessor as h}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const m=new Set(["withGeoIndex","withIndex","withSearchIndex"]),x=new Set(["collect","collectWithScores","first","paginate","take","unique"]),E=r=>{const e=r.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="query")return!1;const s=e.getExpression();return h(s)},P=r=>{const e=[];let s=r;for(;;){const t=s.getParent();if(!t||!i.isPropertyAccessExpression(t))break;const n=t.getParent();if(!n||!i.isCallExpression(n))break;e.push(t.getName()),s=n}return e},S=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,A=r=>{let e=r;for(;;){const s=e.getParent();if(!s||!i.isPropertyAccessExpression(s))return!1;const t=s.getParent();if(!t||!i.isCallExpression(t))return!1;if(s.getName()==="filter"){const n=t.getArguments()[0];if(n&&S.test(n.getText()))return!0}e=t}},y=r=>{const e=r.getArguments()[0];return e&&i.isStringLiteral(e)?e.getLiteralText():""},I=(r,e)=>{const s=[];for(const t of d(e)){const n=r.getSourceFile(t)??r.addSourceFileAtPath(t),f=g(e,t);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!E(a))continue;const o=P(a),l=o.includes("filter");s.push({exportName:p(a),file:f,filtersPrimaryKey:l&&A(a),hasFilter:l,hasIndex:o.some(c=>m.has(c)),line:a.getStartLineNumber(),table:y(a),terminal:o.findLast(c=>x.has(c))})}}return s};export{I as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as r}from"./context-property-calls-CWf9-6G5.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|
package/dist/packem_shared/{discoverRlsMetadata-CPmAGL0W.mjs → discoverRlsMetadata-mXBmPOGj.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{e as A}from"./exported-procedure-chains-D48EXUVQ.mjs";import{r as L}from"./chain-mte5djRJ.mjs";const E=new Set(["delete","insert","read","update"]),P=(e,t,i)=>{const r=e.getArguments()[0];if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){if(!o.isObjectLiteralExpression(n))continue;const a=c(n,"on");a===void 0||!E.has(a)||s.push({file:t,on:a,procedure:i,table:c(n,"table")??""})}return s},u=e=>{if(!o.isObjectLiteralExpression(e))return[];const t=m(e,"permissions");if(!t||!o.isPropertyAssignment(t))return[];const i=t.getInitializer();if(!i||!o.isArrayLiteralExpression(i))return[];const r=[];for(const s of i.getElements()){if(o.isStringLiteral(s)){r.push(s.getLiteralText());continue}if(o.isCallExpression(s)){const n=s.getArguments()[0];n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}}return r},f=(e,t)=>t===void 0?e:{...e,description:t},v=e=>{if(o.isCallExpression(e)){const t=e.getArguments()[0];if(!t||!o.isStringLiteral(t))return;const i=e.getArguments()[1],r=i?c(i,"description"):void 0,s=i?u(i):[];return f({name:t.getLiteralText(),permissions:s},r)}if(o.isObjectLiteralExpression(e)){const t=c(e,"name");return t===void 0?void 0:f({name:t,permissions:u(e)},c(e,"description"))}},y=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const i=m(t,"roles");if(!i||!o.isPropertyAssignment(i))return[];const r=i.getInitializer();if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){const a=v(n);a&&s.push(a)}return s},O=(e,t,i)=>{const r=L(e);return{policies:r.flatMap(s=>P(s,t,i)),roles:r.flatMap(s=>y(s))}},I=(e,t)=>{const i=[],r=new Map;for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=h(t,s);for(const{name:g,receiver:d}of A(n)){const p=O(d,a,g);i.push(...p.policies);for(const l of p.roles)r.has(l.name)||r.set(l.name,l)}}return{policies:i,roles:[...r.values()]}};export{I as default};
|
package/dist/packem_shared/{discoverRlsProcedures-BO4qC77y.mjs → discoverRlsProcedures-F4Cy-kSi.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,tablesAccessedIn as d,findObjectProperty as p}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,tablesAccessedIn as d,findObjectProperty as p}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{c as m}from"./classify-procedure-call-CmcShAze.mjs";import{r as b}from"./chain-mte5djRJ.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const s=[];for(const r of t.getElements()){if(!o.isObjectLiteralExpression(r))continue;const i=p(r,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&s.push(n.getLiteralText())}return s},h=e=>{const t=b(e);return{rlsTables:t.flatMap(s=>g(s)),usesRls:t.length>0}},y=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),v=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),P=(e,t)=>{if(!o.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=m(s);if(!r)return;const i=r.receiver?h(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:l}=d(e,y,v);return{exportName:e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:l,usesRls:i.usesRls,visibility:r.visibility}},x=(e,t)=>{const s=[];for(const r of f(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=u(t,r);for(const l of i.getVariableStatements())if(l.isExported())for(const c of l.getDeclarations()){const a=P(c,n);a&&s.push(a)}}return s};export{x as default};
|
package/dist/packem_shared/{discoverSandboxUsage-CrjZ6yNg.mjs → discoverSandboxUsage-DkbwwFvO.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{listLunoraSourceFiles as f}from"./listLunoraSourceFiles-
|
|
1
|
+
import{listLunoraSourceFiles as f}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const d=new Set(["@lunora/agent","@lunora/agent/sandbox"]),t={browserTool:"usesSandboxBrowser",containerTool:"usesSandboxContainer",fsTool:"usesSandboxFs",jsCodeTool:"usesSandboxLoader"},u=()=>({usesSandboxBrowser:!1,usesSandboxContainer:!1,usesSandboxFs:!1,usesSandboxLoader:!1}),i=o=>{const s=u();if(!d.has(o.getModuleSpecifierValue())||o.isTypeOnly())return s;for(const e of o.getNamedImports()){if(e.isTypeOnly())continue;const n=t[e.getNameNode().getText()];n!==void 0&&(s[n]=!0)}return s},b=(o,s)=>{const e=u();for(const n of f(s)){const c=o.getSourceFile(n)??o.addSourceFileAtPath(n);for(const a of c.getImportDeclarations()){const l=i(a);for(const r of Object.values(t))e[r]||=l[r]}if(Object.values(t).every(a=>e[a]))break}return e};export{b as discoverSandboxUsage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as R}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as F}from"node:module";import{join as C}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{r as B,p as V}from"./parse-validator-C6fHL7OS.mjs";const q=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,J=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},U=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:U(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=J(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>G(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},X=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},H=e=>{const t=X(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},Q=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},Y=(e,t)=>{const n=H(e);if(n)try{const s=F(C(t,"noop.cjs")),r=s.resolve(n.moduleSpecifier),o=s(r),a=Q(o,n);return typeof a!="object"||a===null?void 0:W(a)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},L=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},O=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},A=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ne=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,re=/^(?:sqlite_|_cf_|__)/u,se=/__(?:agg|rank|geo|fts)_/u,ie=e=>re.test(e)||se.test(e),oe=new Set(["cascade","restrict","set null"]),ae=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),le=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),N=/^[A-Za-z_$][\w$]*$/u,w=(e,t)=>{if(ae.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(le.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!N.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(ie(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ce=e=>e&&oe.has(e)?e:void 0,de=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},fe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?ce(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ue=e=>{const t=de(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=fe(s);r&&n.push(r)}return n},pe=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ge=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},me=e=>{const[t,n,s]=e,r=ge(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)pe(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},be=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=L(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},xe=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},he=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},ye=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},ve=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ye(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Ee=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:O(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Ie=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Se=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:te(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},ke=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(xe(n));break}case"global":{e.shardMode="global",e.globalBackend=Ie(n);break}case"index":{e.indexes.push(me(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ve(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ue(r));break}case"searchIndex":{e.searchIndexes.push(be(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Se(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=he(n);break}case"vectorize":{const r=Ee(n,s);r&&e.vectorIndexes.push(r);break}}},_=["__vocab","_config","_content","_data","_docsize","_idx"],Te=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of _){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${_.join(", ")}.`)}},_e=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ne(t))},P=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))ke(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Te(e,t,n.searchIndexes),_e(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=B(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(w(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(P(o,a))}}return t},Le=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Oe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:O(f(s,"metric")),name:o,table:Le(s)}},$=e=>{const t=[];for(const n of e.getProperties()){const s=Oe(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Ae=(e,t)=>{if(!N.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?S(t,e):e,Ne=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},Pe=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},je=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},$e=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ze=(e,t)=>{const n=Pe(e);if(n){if(i.isPropertyAccessExpression(t)){const s=De(n);return s?b(s,t.getName()):void 0}return n}},Me=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,je(t))return t;const s=$e(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ze(a,t)}},Re=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Fe=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);w(a,r.getNameNode()),s.push(P(o,a))}return s},Ce=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:$(n)},D=(e,t,n,s,r)=>{Ae(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>Ne(c,e,o,r)),l=n.map(c=>({...c,name:S(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},Be=(e,t,n)=>D(e,Fe(n),Ce(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ve=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Me(n);if(!s){if(t!==void 0){const o=Y(n,t);if(o){for(const a of o.bareTables)w(a.name,n);return D(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Re(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Be(r.key,r.keyNode,r.options)},qe=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Je=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of qe(e)){const a=Ve(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Ue=new Set(["eu","fedramp","us"]),Ke=e=>A(e,"jurisdiction","jurisdiction",Ue,'"eu", "us", or "fedramp"'),Ze=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&L(r,"pinAuth")===!0}t=s}},Ge=new Set(["required"]),We=e=>A(e,"rls","rls mode",Ge,'"required"'),rt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(R.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Je(r,a,n),k=[...a.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw d(r,q(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:a,vectorIndexes:k}};export{rt as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{w as d}from"./classify-procedure-call-CmcShAze.mjs";import{e as m}from"./exported-procedure-chains-D48EXUVQ.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{x as i,q as r,B as n,o,C as g,s as F,l as p,E as u,v as l,n as f,m as d,p as k,D as w,u as C,t as Q}from"./shard-runtime-D9GRosnD.mjs";import"./shared-DjUziztz.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,p as emitQueueFragments,u as emitQueues,l as emitQueuesMetadataFragments,f as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowFragments,w as emitWorkflows,C as emitWorkflowsMetadataFragments,Q as emitX402Fragments};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as w}from"./capabilities-DJJWVEtk.mjs";import{i as k}from"./ir-DBSvhNa-.mjs";import{G as S}from"./shared-DjUziztz.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,g=w.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>g.some(([t])=>e[t]),D=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],A=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],C=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],v=e=>(e.emailAgents?.length??0)>0,T=e=>v(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],N=e=>v(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],d=e=>e.tables.some(t=>k(t)),I=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],s=[...r||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,h)=>c.localeCompare(h)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},L=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:h,wantsOpenRpc:u}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...C(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(i),...A(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...T(e),...I(e),"",...D(e.identity),...N(e),...a||n?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...u?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},q=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(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],G=e=>g.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
|
|
1
|
+
import{A as w}from"./capabilities-DJJWVEtk.mjs";import{i as k}from"./ir-DBSvhNa-.mjs";import{G as S}from"./shared-DjUziztz.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,g=w.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>g.some(([t])=>e[t]),D=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],A=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],C=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],v=e=>(e.emailAgents?.length??0)>0,T=e=>v(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],N=e=>v(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],d=e=>e.tables.some(t=>k(t)),I=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],s=[...r||a?["createCrossShardRelationCapabilities"]:[],...d(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,h)=>c.localeCompare(h)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},L=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:h,wantsOpenRpc:u}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...C(a),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(i),...A(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...T(e),...I(e),"",...D(e.identity),...N(e),...a||n?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...e.wantsArchitecture?['import { architecture } from "./architecture.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...u?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},q=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(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...d(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],G=e=>g.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
|
|
2
2
|
public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
|
|
3
3
|
this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
|
|
4
4
|
|
|
@@ -289,7 +289,7 @@ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${_(t.shardMode)}],`)
|
|
|
289
289
|
}`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
290
290
|
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
291
291
|
`)}
|
|
292
|
-
};`]:[]],U=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], 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>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],F=e=>e.hasScheduler?`
|
|
292
|
+
};`]:[]],U=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture,"]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], 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>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],F=e=>e.hasScheduler?`
|
|
293
293
|
/** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
|
|
294
294
|
private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
|
|
295
295
|
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
@@ -823,6 +823,8 @@ interface LunoraConfig<Env extends object = object> {
|
|
|
823
823
|
app?: (app: AppBuilder<Env>) => AppBuilder<Env>;
|
|
824
824
|
/** Opt into remote-binding dev without \`--remote\` or \`LUNORA_REMOTE\` on every run. A literal, for the same reason as \`target\`. */
|
|
825
825
|
remote?: boolean;
|
|
826
|
+
/** Sibling Workers the app calls through service bindings — key → its folder and, for RPC, the exported \`WorkerEntrypoint\` class. Becomes \`ctx.services.<key>\` in actions, a wrangler \`services[]\` entry, one \`lunora dev\` session and a services-first \`lunora deploy\`. Literals, for the same reason as \`target\`. */
|
|
827
|
+
services?: Record<string, { dir: string; entrypoint?: string }>;
|
|
826
828
|
/** Deploy target id — \`lunora deploy\`/\`verify\` read it when no \`--target\` is passed. Must be a literal: \`runCodegen\` resolves it synchronously by PARSING this file, so a computed value is not seen — \`lunora verify\` reports \`platform_unreadable_target\` rather than defaulting in silence. */
|
|
827
829
|
target?: string;
|
|
828
830
|
}
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import{LunoraError as
|
|
2
|
-
`:"",
|
|
3
|
-
readonly ai: LunoraAi;`:"",
|
|
4
|
-
`:"",
|
|
5
|
-
readonly payments: LunoraPayment;`:"",
|
|
6
|
-
`:"",
|
|
7
|
-
readonly x402: X402Pay;`:"",
|
|
8
|
-
`:"",
|
|
1
|
+
import{relative as qe,isAbsolute as _e,sep as Ve}from"node:path";import{LunoraError as D}from"@lunora/errors";import{S as Ge}from"./capabilities-DJJWVEtk.mjs";import{p as He}from"./ir-DBSvhNa-.mjs";import{a as h,G as ze,u as Ue,d as Xe}from"./shared-DjUziztz.mjs";const Je=/\.([cm]?)tsx?$/u,Ke=(u,s=[])=>{const t=new Set;for(const a of u.tables)for(const o of Object.values(a.shape)){const i=Ue(o);i.kind==="storage"&&typeof i.bucket=="string"&&i.bucket!==""&&t.add(i.bucket)}for(const a of s)a!==""&&a!=="default"&&t.add(a);return["default",...[...t].toSorted((a,o)=>a.localeCompare(o))]},ot=({agents:u=[],containers:s=[],env:t,hasAccessFacade:a=!1,hasAi:o=!1,hasAnalytics:i=!1,hasBrowser:X=!1,hasVectors:J=!0,hasFlags:K=!1,hasHyperdrive:Y=!1,hasImages:Z=!1,hasKv:ee=!1,hasNotify:te=!1,hasPayments:M=!1,hasPipelines:ae=!1,hasR2sql:re=!1,hasX402:S=!1,identity:d,queues:F=[],schema:W,generatedDirectory:Q="",services:b=[],storageRuleBuckets:oe=[],topics:E=[],useUmbrella:ne=!1,workflows:P=[]}={})=>{const r=Xe(ne),se=Ke(W??{tables:[]},oe).map(e=>JSON.stringify(e)).join(" | "),ie=o?`import type { LunoraAi } from "@lunora/ai";
|
|
2
|
+
`:"",de=o?`
|
|
3
|
+
readonly ai: LunoraAi;`:"",le=M?`import type { LunoraPayment } from "@lunora/payment";
|
|
4
|
+
`:"",ce=M?`
|
|
5
|
+
readonly payments: LunoraPayment;`:"",ue=S?`import type { X402Pay } from "@lunora/x402/pay";
|
|
6
|
+
`:"",pe=S?`
|
|
7
|
+
readonly x402: X402Pay;`:"",ye=s.length>0?`import type { ContainerAccessor } from "@lunora/container";
|
|
8
|
+
`:"",me=s.length>0?`
|
|
9
9
|
readonly containers: {${s.map(e=>`
|
|
10
10
|
readonly ${e.exportName}: ContainerAccessor;`).join("")}
|
|
11
|
-
};`:"",
|
|
12
|
-
readonly ${e.bindingName}?: unknown;`)),...
|
|
11
|
+
};`:"",j=[...o?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...s.map(e=>(h(e.bindingName,`container binding "${e.bindingName}"`),` /** Durable Object namespace for the \`${e.exportName}\` container. */
|
|
12
|
+
readonly ${e.bindingName}?: unknown;`)),...F.map(e=>(h(e.bindingName,`queue binding "${e.bindingName}"`),` /** Queue producer binding for the \`${e.exportName}\` queue. */
|
|
13
13
|
readonly ${e.bindingName}?: unknown;`))].join(`
|
|
14
|
-
`),
|
|
14
|
+
`),he=`
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* This project's Cloudflare bindings, as far as codegen can discover them from
|
|
@@ -24,26 +24,26 @@ import{LunoraError as Ce}from"@lunora/errors";import{S as Ne}from"./capabilities
|
|
|
24
24
|
* surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
|
|
25
25
|
*/
|
|
26
26
|
export interface CloudflareBindings {
|
|
27
|
-
readonly [binding: string]: unknown;${
|
|
28
|
-
${
|
|
27
|
+
readonly [binding: string]: unknown;${j?`
|
|
28
|
+
${j}`:""}
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
32
|
-
export type Env = CloudflareBindings;`,n=(e,
|
|
33
|
-
readonly vectors: VectorSearch<VectorIndexName>;`:"",
|
|
34
|
-
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",
|
|
32
|
+
export type Env = CloudflareBindings;`,n=(e,l,c)=>{const m=Ge.get(e);if(m!==void 0&&m.tier!==c)throw new D("INTERNAL",`@lunora/codegen: capability "${e}" declares tier "${m.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${c}" context — update whichever is wrong.`);return l?m?.field??"":""},f=n("kv",ee,"every"),x=n("analytics",i,"every"),be=n("hyperdrive",Y,"action"),fe=n("browser",X,"action"),xe=n("images",Z,"action"),ge=n("pipelines",ae,"action"),Te=n("r2sql",re,"action"),p=J&&(W?.vectorIndexes.length??0)>0,g=p?' | "vectors"':"",L=p?`
|
|
33
|
+
readonly vectors: VectorSearch<VectorIndexName>;`:"",ve=p?`
|
|
34
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",ke=p?`import type { VectorSearch, VectorSearchReader } from "${r.server}";
|
|
35
35
|
import type { VectorIndexName } from "./dataModel.js";
|
|
36
|
-
`:"",
|
|
36
|
+
`:"",T=a?`
|
|
37
37
|
/** Verified Cloudflare Access identity — a synchronous facade over the resolved claims (email / groups / hasGroup / claims). Anonymous when no Access token is present. */
|
|
38
|
-
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",
|
|
38
|
+
readonly access: import("@lunora/cloudflare-access/context").AccessFacade;`:"",v=K?`
|
|
39
39
|
/** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
|
|
40
|
-
readonly flags: import("${r.flags}").LunoraFlags;`:"",
|
|
40
|
+
readonly flags: import("${r.flags}").LunoraFlags;`:"",k=te?`
|
|
41
41
|
/** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
|
|
42
42
|
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
43
43
|
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
44
|
-
readonly push: import("@lunora/notify").LunoraPush;`:"",
|
|
44
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",y=P.length>0,we=y?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
45
45
|
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
46
|
-
`:""
|
|
46
|
+
`:"",$e=y?`
|
|
47
47
|
|
|
48
48
|
/** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
|
|
49
49
|
type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
|
|
@@ -54,47 +54,56 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
54
54
|
|
|
55
55
|
/** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
|
|
56
56
|
export interface LunoraWorkflows {
|
|
57
|
-
${
|
|
57
|
+
${P.map(e=>` get(name: ${JSON.stringify(e.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${e.exportName}>>;`).join(`
|
|
58
58
|
`)}
|
|
59
|
-
}`:"",
|
|
60
|
-
readonly workflows: LunoraWorkflows;`:"",
|
|
59
|
+
}`:"",q=y?' | "workflows"':"",_=y?`
|
|
60
|
+
readonly workflows: LunoraWorkflows;`:"",V=He(F),w=V.length>0,$=E.length>0,I=[...w?["QueueProducer"]:[],...$?["TopicPublisher"]:[]],Ie=I.length>0?`import type { ${I.join(", ")} } from "@lunora/queue";
|
|
61
61
|
import type * as lunoraQueueDefinitions from "../queues.js";
|
|
62
|
-
`:"",
|
|
62
|
+
`:"",Re=I.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",Be=w?`
|
|
63
63
|
|
|
64
64
|
/** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
|
|
65
65
|
export interface LunoraQueues {
|
|
66
|
-
${
|
|
66
|
+
${V.map(e=>` readonly ${e.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${e.exportName}>>;`).join(`
|
|
67
67
|
`)}
|
|
68
|
-
}`:"",
|
|
68
|
+
}`:"",Oe=$?`
|
|
69
69
|
|
|
70
70
|
/** This project's declared topics, addressable from \`ctx.topics\` by their \`lunora/queues.ts\` export name. */
|
|
71
71
|
export interface LunoraTopics {
|
|
72
|
-
${
|
|
72
|
+
${E.map(e=>` readonly ${e.exportName}: TopicPublisher<QueueBodyOf<typeof lunoraQueueDefinitions.${e.exportName}>>;`).join(`
|
|
73
73
|
`)}
|
|
74
|
-
}`:"",
|
|
75
|
-
readonly queues: LunoraQueues;`:"",
|
|
76
|
-
readonly topics: LunoraTopics;`:"",
|
|
77
|
-
|
|
74
|
+
}`:"",Ae=`${Re}${Be}${Oe}`,G=w?`
|
|
75
|
+
readonly queues: LunoraQueues;`:"",H=$?`
|
|
76
|
+
readonly topics: LunoraTopics;`:"",R=b.length>0,Ne=e=>{if(Q==="")throw new D("INTERNAL","@lunora/codegen: emitServer needs `generatedDirectory` to import an RPC service's types");const l=qe(Q,e);if(_e(l))throw new D("INTERNAL",`@lunora/codegen: an RPC service's entry (${e}) must be on the same drive as the app`);const c=l.split(Ve).join("/").replace(Je,".$1js");return c.startsWith(".")?c:`./${c}`},z=b.filter(e=>e.entrypoint!==void 0),Ce=z.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",De=R?`import type { ${Ce} } from "${r.server}";
|
|
77
|
+
${z.map(e=>`import type * as lunoraService_${e.name} from ${JSON.stringify(Ne(e.main))};
|
|
78
|
+
`).join("")}`:"",Me=R?`
|
|
79
|
+
|
|
80
|
+
/** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
|
|
81
|
+
export interface LunoraServices {
|
|
82
|
+
${b.map(e=>{h(e.name,`service "${e.name}"`);const l=e.entrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${e.name}.${e.entrypoint}>`;return` readonly ${e.name}: ${l};`}).join(`
|
|
83
|
+
`)}
|
|
84
|
+
}`:"",Se=R?`
|
|
85
|
+
readonly services: LunoraServices;`:"",B=u.length>0,Fe=B?`import type { AgentHandle } from "@lunora/agent";
|
|
86
|
+
`:"",We=B?`
|
|
78
87
|
|
|
79
88
|
/** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
|
|
80
89
|
export interface LunoraAgents {
|
|
81
|
-
${
|
|
90
|
+
${u.map(e=>(h(e.exportName,`agent export "${e.exportName}"`),` readonly ${e.exportName}: AgentHandle;`)).join(`
|
|
82
91
|
`)}
|
|
83
|
-
}`:"",
|
|
84
|
-
readonly agents: LunoraAgents;`:"",
|
|
92
|
+
}`:"",U=B?`
|
|
93
|
+
readonly agents: LunoraAgents;`:"",Qe=d?`import type { InferIdentity } from "${r.server}";
|
|
85
94
|
import type * as lunoraIdentityContract from "../identity.js";
|
|
86
|
-
`:"",
|
|
95
|
+
`:"",Ee=d?`
|
|
87
96
|
|
|
88
97
|
/** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
|
|
89
98
|
export type Identity = InferIdentity<typeof lunoraIdentityContract.${d.exportName}>;
|
|
90
99
|
|
|
91
100
|
/** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
|
|
92
|
-
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",
|
|
93
|
-
readonly auth: NarrowedAuth;`:"",
|
|
94
|
-
`:"",
|
|
101
|
+
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",O=d?' | "auth"':"",A=d?`
|
|
102
|
+
readonly auth: NarrowedAuth;`:"",Pe=d?", Identity":"",je=t?`import type * as lunoraEnvContract from "../env.js";
|
|
103
|
+
`:"",Le=t?`
|
|
95
104
|
|
|
96
105
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
97
|
-
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${t.exportName}>;`:""
|
|
106
|
+
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${t.exportName}>;`:"",N=t?' | "env"':"",C=t?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${ze}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${r.server}";
|
|
98
107
|
import type {
|
|
99
108
|
ActionBuilder,
|
|
100
109
|
ActionCtx as ActionCtxBase,
|
|
@@ -151,7 +160,7 @@ export type {
|
|
|
151
160
|
} from "${r.serverDataModel}";
|
|
152
161
|
|
|
153
162
|
import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
|
|
154
|
-
${
|
|
163
|
+
${ke}${ie}${le}${ue}${ye}${we}${Ie}${De}${Fe}${Qe}${je}
|
|
155
164
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
156
165
|
|
|
157
166
|
/**
|
|
@@ -211,7 +220,7 @@ export interface OrmWriter extends OrmReader {
|
|
|
211
220
|
}
|
|
212
221
|
|
|
213
222
|
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
214
|
-
export type StorageBucketName = ${
|
|
223
|
+
export type StorageBucketName = ${se};${he}${$e}${Ae}${Me}${We}${Ee}${Le}
|
|
215
224
|
|
|
216
225
|
/**
|
|
217
226
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -274,22 +283,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
|
|
|
274
283
|
*/
|
|
275
284
|
type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
|
|
276
285
|
|
|
277
|
-
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${
|
|
286
|
+
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${g}${O}${N}> {
|
|
278
287
|
readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
279
288
|
readonly orm: OrmReader;
|
|
280
|
-
readonly storage: ReadOnlyStorage<StorageBucketName>;${
|
|
289
|
+
readonly storage: ReadOnlyStorage<StorageBucketName>;${ve}${T}${f}${v}${k}${x}${C}${A}
|
|
281
290
|
}
|
|
282
291
|
|
|
283
|
-
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${
|
|
292
|
+
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${g}${q}${O}${N}> {
|
|
284
293
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
285
294
|
readonly orm: OrmWriter;
|
|
286
|
-
readonly storage: MutationStorage<StorageBucketName>;${
|
|
295
|
+
readonly storage: MutationStorage<StorageBucketName>;${L}${T}${f}${v}${k}${x}${C}${_}${G}${H}${U}${A}
|
|
287
296
|
}
|
|
288
297
|
|
|
289
|
-
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${
|
|
298
|
+
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${g}${q}${O}${N}> {
|
|
290
299
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
291
300
|
readonly orm: OrmWriter;
|
|
292
|
-
readonly storage: StorageBase<StorageBucketName>;${
|
|
301
|
+
readonly storage: StorageBase<StorageBucketName>;${L}${T}${de}${ce}${pe}${me}${f}${v}${k}${be}${fe}${xe}${x}${ge}${Te}${Se}${C}${_}${G}${H}${U}${A}
|
|
293
302
|
}
|
|
294
303
|
|
|
295
304
|
/**
|
|
@@ -347,7 +356,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
|
|
|
347
356
|
* Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
|
|
348
357
|
* so the \`rls()\` chain discovers a policy authored either way the same.
|
|
349
358
|
*/
|
|
350
|
-
export const definePolicy = createPolicyDsl<DataModel, Relations${
|
|
359
|
+
export const definePolicy = createPolicyDsl<DataModel, Relations${Pe}>();
|
|
351
360
|
|
|
352
361
|
/**
|
|
353
362
|
* The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
|
|
@@ -364,4 +373,4 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Oe}>();
|
|
|
364
373
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
365
374
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
366
375
|
};
|
|
367
|
-
`};export{
|
|
376
|
+
`};export{ot as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as f}from"./shard-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as f}from"./shard-D6EZdlSg.mjs";import"./shard-runtime-D9GRosnD.mjs";import"./shared-DjUziztz.mjs";export{f as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-
|
|
1
|
+
import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-CmcShAze.mjs";const f=s=>{const i=[];for(const r of s.getVariableStatements())if(r.isExported())for(const t of r.getDeclarations()){const e=t.getInitializer(),o=e&&a.isCallExpression(e)?n(e):void 0;o?.receiver&&i.push({name:t.getName(),receiver:o.receiver})}return i};export{f as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as c}from"node:crypto";import{existsSync as s,readFileSync as i}from"node:fs";import{join as h}from"node:path";import{listLunoraSourceFiles as u}from"./listLunoraSourceFiles-
|
|
1
|
+
import{createHash as c}from"node:crypto";import{existsSync as s,readFileSync as i}from"node:fs";import{join as h}from"node:path";import{listLunoraSourceFiles as u}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const S=t=>{if(!s(t))return"unreadable";const e=u(t),o=h(t,"schema.ts");s(o)&&e.push(o);const r=c("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(i(a))}catch{}return r.digest("hex")};export{S as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r}from"ts-morph";import{propertyKeyName as f,listLunoraSourceFiles as m,lunoraRelativePath as p,tablesAccessedIn as d}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as r}from"ts-morph";import{propertyKeyName as f,listLunoraSourceFiles as m,lunoraRelativePath as p,tablesAccessedIn as d}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{w as g,c as h}from"./classify-procedure-call-CmcShAze.mjs";const u=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return f(e)},k=e=>g(e,"use","mask"),x=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();if(t&&r.isStringLiteral(t)){const s=t.getLiteralText();if(s==="redact"||s==="hash")return s}}return"custom"},v=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const i of t.getProperties()){const n=u(i);if(n===void 0||!r.isPropertyAssignment(i))continue;const o=i.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=u(a);c!==void 0&&s.push({column:c,table:n})}}return s},P=e=>{const t=k(e);return{maskColumns:t.flatMap(s=>v(s)),usesMask:t.length>0}},y=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),C=new Set(["delete","insert","patch","replace"]),M=(e,t)=>{if(!r.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const i=h(s);if(!i)return;const n=i.receiver?P(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:o,tablesWritten:a}=d(e,y,C);return{exportName:e.getName(),file:t,maskColumns:n.maskColumns,tablesRead:o,tablesWritten:a,usesMask:n.usesMask,visibility:i.visibility}},E=(e,t)=>{const s=[];for(const i of m(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i),o=p(t,i);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=M(c,o);l&&s.push(l)}}return s};export{u as a,E as d,k as m,x as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readdirSync as x,realpathSync as P,lstatSync as A,statSync as O}from"node:fs";import{dirname as N,join as f,relative as w,sep as T,extname as m}from"node:path";import{Node as s,VariableDeclarationKind as F,SyntaxKind as S}from"ts-morph";import{diagnosticAt as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findProjectConfigFile as I}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const D=/\.ts$/u,u=(t,e)=>w(t,e).split(T).join("/").replace(D,""),C=new Set(["_generated","node_modules"]),_=(t,e,i)=>t==="schema.ts"&&e===i,j=t=>{try{return O(t)}catch{console.warn(`@lunora/codegen: skipping ${t} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},y=(t,e,i,n)=>{let o,r;try{o=x(t),r=P(t)}catch{return e}if(n.has(r))return e;n.add(r);for(const a of o){const l=f(t,a),c=j(l);c!==void 0&&(c.isDirectory()?C.has(a)||y(l,e,i,n):c.isFile()&&m(a)===".ts"&&!_(a,t,i)&&e.push(l))}return e},b=t=>y(t,[],t,new Set),z=["src/server","src/index.ts","src/worker.ts"],V=new Set([".ts",".tsx"]),h=(t,e=[])=>{let i;try{i=A(t)}catch{return e}if(i.isFile())return V.has(m(t))&&e.push(t),e;if(!i.isDirectory())return e;for(const n of x(t))n==="_generated"||n==="node_modules"||h(f(t,n),e);return e},K=t=>{const e=N(t),i=b(t).map(r=>({displayPath:u(t,r),filePath:r})),n=new Set(i.map(r=>r.filePath)),o=I(e);for(const r of[...z.flatMap(a=>h(f(e,a))),...o===void 0?[]:[o]])n.has(r)||(n.add(r),i.push({displayPath:u(e,r),filePath:r}));return i},v=(t,e,i)=>{const n=[];for(const{displayPath:o,filePath:r}of e){const a=t.getSourceFile(r)??t.addSourceFileAtPath(r);for(const l of a.getDescendantsOfKind(S.CallExpression)){const c=i(l,o);c!==void 0&&n.push(c)}}return n},J=(t,e,i)=>v(t,b(e).map(n=>({displayPath:u(e,n),filePath:n})),i),Z=(t,e,i)=>v(t,K(e),i),tt=t=>{for(const e of t.getAncestors()){if(s.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0)return e.getName();if(s.isExportAssignment(e)&&!e.isExportEquals())return"default"}return""},L=t=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isNumericLiteral(t))return t.getLiteralText();if(s.isComputedPropertyName(t)){const e=t.getExpression();if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText()}return t.getText()},k=t=>L(t.getNameNode()),et=t=>L(t.getPropertyNameNode()??t.getNameNode()),p=(t,e)=>t?.getProperties().find(i=>!s.isSpreadAssignment(i)&&k(i)===e),it=(t,e)=>{if(e){const r=t.getArguments()[0];return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0}const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=p(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const o=n.getInitializer();return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0},st=(t,e)=>{if(!t||!s.isObjectLiteralExpression(t))return;const i=p(t,e);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},M=t=>{const e=t?.getDeclarations().find(o=>s.isVariableDeclaration(o));if(e===void 0||!s.isVariableDeclaration(e))return;const i=e.getParent();if(!s.isVariableDeclarationList(i)||i.getDeclarationKind()!==F.Const)return;const n=i.getParent();return s.isVariableStatement(n)&&s.isSourceFile(n.getParent())?e.getInitializer():void 0},$=t=>M(t.getSymbol()),nt=t=>{if(!t)return;if(s.isObjectLiteralExpression(t))return t;if(!s.isIdentifier(t))return;const e=$(t);return e!==void 0&&s.isObjectLiteralExpression(e)?e:void 0},g=t=>s.isPropertyAccessExpression(t)&&t.getName()==="db"||s.isIdentifier(t)&&t.getText()==="db",q=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),rt=t=>{const e=t.getExpression();if(!s.isPropertyAccessExpression(e)||!q.has(e.getName()))return;const i=e.getExpression();if(g(i)){const n=t.getArguments()[0];return{options:t.getArguments()[1],table:n&&s.isStringLiteral(n)?n.getLiteralText():""}}if(s.isPropertyAccessExpression(i)){const n=i.getExpression();if(g(n))return{options:t.getArguments()[0],table:i.getName()}}},d=(t,e)=>{const i=t.getExpression();return!s.isPropertyAccessExpression(i)||!e.has(i.getName())?!1:g(i.getExpression())},E=t=>{const e=t.getArguments()[0];return e&&s.isStringLiteral(e)?e.getLiteralText():""},ot=(t,e,i)=>{const n=new Set,o=new Set;for(const r of t.getDescendantsOfKind(S.CallExpression))if(d(r,e)){const a=E(r);a!==""&&n.add(a)}else if(d(r,i)){const a=E(r);a!==""&&o.add(a)}return{tablesRead:[...n],tablesWritten:[...o]}},B=t=>{let e=t;for(;e&&(s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isParenthesizedExpression(e)||s.isNonNullExpression(e));)e=e.getExpression();return e},at=t=>{const e=B(t);return e&&s.isCallExpression(e)?e:void 0},ct=t=>{const e=t.getExportAssignment(o=>!o.isExportEquals());if(!e)return;const i=e.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},lt=t=>{const e=t.getArguments()[1];return e&&s.isStringLiteral(e)?e.getLiteralValue():""},ut=(t,e)=>{if(!s.isObjectLiteralExpression(t))return;const i=p(t,e);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},U=t=>{const e=t.getStatements(),[i]=e;if(e.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},gt=t=>{if(s.isObjectLiteralExpression(t))return t;if(s.isParenthesizedExpression(t)){const e=t.getExpression();return s.isObjectLiteralExpression(e)?e:void 0}return s.isBlock(t)?U(t):void 0},ft=t=>s.isIdentifier(t)&&t.getText()==="ctx",pt=t=>(e,i,n)=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw R(e,`${t} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},W=new Set(["api","internal"]),dt=new Set(["run","runAction","runMutation","runQuery"]),Et=t=>{if(t===void 0||!s.isPropertyAccessExpression(t))return;const e=[];let i=t;for(;s.isPropertyAccessExpression(i);)e.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&W.has(i.getText())&&e.length>=2?e:void 0};export{dt as RUN_METHODS,D as TS_EXTENSION_RE,et as bindingKeyName,J as collectCallRows,Z as collectSecurityCallRows,ct as defaultExportExpression,tt as enclosingExportName,p as findObjectProperty,Et as functionReferenceSegments,it as handlerOf,ft as isContextIdentifier,g as isDatabaseAccessor,lt as limitNameOf,b as listLunoraSourceFiles,K as listSecurityScanFiles,u as lunoraRelativePath,gt as objectLiteralFromCallbackBody,nt as optionsObjectLiteral,st as propertyInitializer,k as propertyKeyName,L as propertyNameText,rt as readTargetOf,pt as stringPropertyFor,ut as stringPropertyOf,M as symbolConstInitializer,E as tableArgumentOf,ot as tablesAccessedIn,B as unwrapExpression,at as unwrapToCallExpression};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{statSync as b,readFileSync as E}from"node:fs";import{basename as y}from"node:path";import{createJiti as P}from"jiti";import{Project as x,Node as t}from"ts-morph";import{propertyKeyName as l}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{findProjectConfigFile as m}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{PROJECT_CONFIG_FILENAMES as k}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const p=new Map,D=async i=>{const r=m(i);if(r===void 0)return{};let e;try{const n=b(r);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=p.get(r);if(s?.key===e)return s.value;const a=(async()=>{try{const o=(await P(r,{interopDefault:!1,moduleCache:!1}).import(r))?.default;return{config:o!==null&&typeof o=="object"?o:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return p.set(r,{key:e,value:a}),a},S=i=>{let e=i.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e)||t.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&t.isIdentifier(e))for(e=i.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e));)e=e.getExpression();return e!==void 0&&t.isObjectLiteralExpression(e)?e:void 0},c=(i,r)=>t.isPropertyAssignment(i)?i.getInitializer():r.getVariableDeclaration(l(i))?.getInitializer(),d=i=>{let r=i;for(;r!==void 0&&(t.isSatisfiesExpression(r)||t.isAsExpression(r)||t.isParenthesizedExpression(r));)r=r.getExpression();return r},L=(i,r)=>{const e=d(i);if(e===void 0||!t.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),a=s.filter(u=>t.isPropertyAssignment(u)&&!t.isComputedPropertyName(u.getNameNode())||t.isShorthandPropertyAssignment(u));if(a.length!==s.length)return{advisor:{unreadable:!0}};const n=a.find(u=>l(u)==="minSeverity");if(n===void 0)return{advisor:{}};const o=c(n,r);return o!==void 0&&t.isStringLiteral(o)?{advisor:{minSeverity:o.getLiteralValue()}}:{advisor:{unreadable:!0}}},h=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),f=(i,r)=>{const e=i.getProperty(r);if(e===void 0)return;const s=t.isPropertyAssignment(e)?e.getInitializer():void 0;return s!==void 0&&(t.isStringLiteral(s)||t.isNoSubstitutionTemplateLiteral(s))?s.getLiteralValue():!1},A=i=>{const r=d(i);if(r===void 0||!t.isObjectLiteralExpression(r))return{services:{unreadable:!0}};const e={};for(const s of r.getProperties()){if(!t.isPropertyAssignment(s)||t.isComputedPropertyName(s.getNameNode()))return{services:{unreadable:!0}};const a=d(s.getInitializer());if(a===void 0||!t.isObjectLiteralExpression(a)||a.getProperties().some(u=>!t.isPropertyAssignment(u)))return{services:{unreadable:!0}};const n=f(a,"dir"),o=f(a,"entrypoint");if(typeof n!="string"||o===!1)return{services:{unreadable:!0}};e[l(s)]=o===void 0?{dir:n}:{dir:n,entrypoint:o}}return{services:{declared:e}}},j=(i,r)=>{if(t.isGetAccessorDeclaration(i)||t.isMethodDeclaration(i))return h.get(l(i))??{};if(!t.isPropertyAssignment(i)&&!t.isShorthandPropertyAssignment(i))return{};const e=l(i);if(e==="advisor")return L(c(i,r),r);if(e==="services")return A(c(i,r));if(e!=="target"&&e!=="remote")return{};const s=c(i,r);return s===void 0?{unreadable:!0}:e==="target"?t.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:t.isTrueLiteral(s)||t.isFalseLiteral(s)?{remote:s.getLiteralValue()}:t.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},M=i=>{const r=m(i);if(r===void 0)return{};let e;try{e=E(r,"utf8")}catch{return{unreadable:!0}}const a=new x({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(y(r),e,{overwrite:!0}),n=S(a);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(u=>t.isSpreadAssignment(u))){const u=v=>n.getProperties().some(g=>!t.isSpreadAssignment(g)&&l(g)===v);return{...u("advisor")?{advisor:{unreadable:!0}}:{},...u("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let o={};for(const u of n.getProperties())o={...o,...j(u,a)};return o};export{k as PROJECT_CONFIG_FILENAMES,m as findProjectConfigFile,D as loadProjectConfig,M as readProjectConfigLiterals};
|