@lunora/codegen 1.0.0-alpha.121 → 1.0.0-alpha.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (19) hide show
  1. package/dist/index.mjs +1 -1
  2. package/dist/packem_shared/{GENERATED_HEADER-B_KsWp7_.mjs → GENERATED_HEADER-BK_kEkwC.mjs} +1 -1
  3. package/dist/packem_shared/{MUTATORS_FILENAME-B2-W8Bm3.mjs → MUTATORS_FILENAME-DJerSBO-.mjs} +1 -1
  4. package/dist/packem_shared/{NOTIFY_FILENAME-IJXY4yHt.mjs → NOTIFY_FILENAME-CPg7zlsb.mjs} +1 -1
  5. package/dist/packem_shared/{OPENRPC_VERSION-CX52iE6f.mjs → OPENRPC_VERSION-DdUjeiyx.mjs} +1 -1
  6. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-DL1A739E.mjs → SCHEMA_SNAPSHOT_FILENAME-BPw55kMe.mjs} +1 -1
  7. package/dist/packem_shared/buildOpenApiDocument-yZ6y1ezD.mjs +3 -0
  8. package/dist/packem_shared/discoverFunctions-CYHtspcp.mjs +1 -0
  9. package/dist/packem_shared/{discoverHttpRoutes-BxF4FRZL.mjs → discoverHttpRoutes-BkwEwmK0.mjs} +1 -1
  10. package/dist/packem_shared/{discoverMaskProcedures-BCl3fNrQ.mjs → discoverMaskProcedures-DExWLcsu.mjs} +1 -1
  11. package/dist/packem_shared/{discoverNondeterministicCalls-BA91Z-vF.mjs → discoverNondeterministicCalls-xRw6-4OU.mjs} +1 -1
  12. package/dist/packem_shared/{discoverR2sqlCalls-M2ob41UX.mjs → discoverR2sqlCalls-Ciq0-bVB.mjs} +1 -1
  13. package/dist/packem_shared/{discoverRlsMetadata-Dwt2p8IK.mjs → discoverRlsMetadata-Bnn3zDlc.mjs} +1 -1
  14. package/dist/packem_shared/{discoverStorageRulesMetadata-69Y8wZb2.mjs → discoverStorageRulesMetadata-DYAgRSL6.mjs} +1 -1
  15. package/dist/packem_shared/{emit-CW4ceRjr.mjs → emit-BlC5DV56.mjs} +75 -75
  16. package/dist/packem_shared/{emitApp-BMm-xmNg.mjs → emitApp-OyeVRgKE.mjs} +1 -1
  17. package/package.json +6 -6
  18. package/dist/packem_shared/buildOpenApiDocument-VeBRFs54.mjs +0 -3
  19. package/dist/packem_shared/discoverFunctions-006teuNG.mjs +0 -1
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-006teuNG.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-BxF4FRZL.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-BCl3fNrQ.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-B2-W8Bm3.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-BA91Z-vF.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-IJXY4yHt.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/discover-queries-Dfj_0WJG.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-M2ob41UX.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Dwt2p8IK.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-gJ93Xjpx.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-69Y8wZb2.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs";import{G as Ne,e as ge,a as Oe,b as Re,c as Me,d as he,f as Ce,g as _e,h as Te,i as Ie,j as Le,k as Fe,l as De,m as Pe}from"./packem_shared/emit-CW4ceRjr.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-BMm-xmNg.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-VeBRFs54.mjs";import{OPENRPC_VERSION as je,buildOpenRpcDocument as Ke,emitOpenRpc as Ve,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-CX52iE6f.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as qe,readProjectTarget as Be,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-Dtmu39TP.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Xe,createCodegenProject as Ze,findTsconfig as $e,refreshCodegenProject as er,runCodegen as rr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-DL1A739E.mjs";import{SchemaSnapshotParseError as tr,buildSchemaSnapshot as sr,evaluateSchemaDrift as ar,parseSchemaSnapshot as ir}from"./packem_shared/SchemaSnapshotParseError-BoHDfCO3.mjs";import{schemaFromIr as dr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as cr}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as Sr,SDK_TARGETS as lr,generateSdk as Er}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ar,secretKindOf as ur}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Nr,findSolutionByMessage as gr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,R as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,T as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Nr as LUNORA_SOLUTION_RULES,j as MUTATORS_FILENAME,w as NOTIFY_FILENAME,je as OPENRPC_VERSION,ee as QUEUES_FILENAME,Xe as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Sr as SDK_LANGUAGES,lr as SDK_TARGETS,ne as SHAPES_FILENAME,tr as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,be as buildOpenApiDocument,Ke as buildOpenRpcDocument,sr as buildSchemaSnapshot,Ze as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,g as discoverAuthApiCalls,M as discoverContainers,C as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,b as discoverMaskProcedures,y as discoverMigrations,K as discoverMutators,z as discoverNondeterministicCalls,q as discoverNotifyCalls,B as discoverNotifyConfig,Z as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,pe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,ge as emitAgents,Oe as emitApi,Ge as emitApp,Re as emitCollections,Me as emitContainers,he as emitCrons,Ce as emitDataModel,_e as emitDrizzleSchema,Te as emitFunctions,ke as emitOpenApi,ye as emitOpenApiModule,Ve as emitOpenRpc,ze as emitOpenRpcModule,Ie as emitServer,Le as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,ar as evaluateSchemaDrift,gr as findLunoraSolution,$e as findTsconfig,m as formatAdvisories,Er as generateSdk,Rr as isTypedSchema,d as lintSchema,ir as parseSchemaSnapshot,qe as platformMatrixIds,Y as readPackageDependencies,Be as readProjectTarget,Ar as redact,er as refreshCodegenProject,Je as resolveCodegenTarget,rr as runCodegen,dr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,cr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-CYHtspcp.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-BkwEwmK0.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-DExWLcsu.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-DJerSBO-.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-xRw6-4OU.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-CPg7zlsb.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/discover-queries-Dfj_0WJG.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-Ciq0-bVB.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Bnn3zDlc.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-gJ93Xjpx.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-DYAgRSL6.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs";import{G as Ne,e as ge,a as Oe,b as Re,c as Me,d as he,f as Ce,g as _e,h as Te,i as Ie,j as Le,k as Fe,l as De,m as Pe}from"./packem_shared/emit-BlC5DV56.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-OyeVRgKE.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-yZ6y1ezD.mjs";import{OPENRPC_VERSION as je,buildOpenRpcDocument as Ke,emitOpenRpc as Ve,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-DdUjeiyx.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as qe,readProjectTarget as Be,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-Dtmu39TP.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Xe,createCodegenProject as Ze,findTsconfig as $e,refreshCodegenProject as er,runCodegen as rr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BPw55kMe.mjs";import{SchemaSnapshotParseError as tr,buildSchemaSnapshot as sr,evaluateSchemaDrift as ar,parseSchemaSnapshot as ir}from"./packem_shared/SchemaSnapshotParseError-BoHDfCO3.mjs";import{schemaFromIr as dr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as cr}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as Sr,SDK_TARGETS as lr,generateSdk as Er}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ar,secretKindOf as ur}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Nr,findSolutionByMessage as gr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,R as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,T as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Nr as LUNORA_SOLUTION_RULES,j as MUTATORS_FILENAME,w as NOTIFY_FILENAME,je as OPENRPC_VERSION,ee as QUEUES_FILENAME,Xe as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Sr as SDK_LANGUAGES,lr as SDK_TARGETS,ne as SHAPES_FILENAME,tr as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,be as buildOpenApiDocument,Ke as buildOpenRpcDocument,sr as buildSchemaSnapshot,Ze as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,g as discoverAuthApiCalls,M as discoverContainers,C as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,b as discoverMaskProcedures,y as discoverMigrations,K as discoverMutators,z as discoverNondeterministicCalls,q as discoverNotifyCalls,B as discoverNotifyConfig,Z as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,pe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,ge as emitAgents,Oe as emitApi,Ge as emitApp,Re as emitCollections,Me as emitContainers,he as emitCrons,Ce as emitDataModel,_e as emitDrizzleSchema,Te as emitFunctions,ke as emitOpenApi,ye as emitOpenApiModule,Ve as emitOpenRpc,ze as emitOpenRpcModule,Ie as emitServer,Le as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,ar as evaluateSchemaDrift,gr as findLunoraSolution,$e as findTsconfig,m as formatAdvisories,Er as generateSdk,Rr as isTypedSchema,d as lintSchema,ir as parseSchemaSnapshot,qe as platformMatrixIds,Y as readPackageDependencies,Be as readProjectTarget,Ar as redact,er as refreshCodegenProject,Je as resolveCodegenTarget,rr as runCodegen,dr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,cr as validatorIrToJsonSchema};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-CW4ceRjr.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-BlC5DV56.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
@@ -1 +1 @@
1
- import{existsSync as f}from"node:fs";import{join as p}from"node:path";import{Node as o,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapHandlerReturn as g}from"./discoverFunctions-006teuNG.mjs";import{a as d}from"./module-specifiers-WF8iAydP.mjs";import{a as x}from"./parse-validator-C5ycrhR3.mjs";const M="mutators.ts",m=d,y=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineMutator";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return m(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineMutator":!1;return!1},S=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(u.ImportDeclaration);return i!==void 0&&m(i.getModuleSpecifierValue())}return!1},N=r=>{if(o.isIdentifier(r))return y(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineMutator"&&o.isIdentifier(t)&&S(t)}return!1},I=r=>{const t=r.getArguments()[0];return t&&o.isObjectLiteralExpression(t)?t:void 0},b=r=>{const t=r?.getProperty("args");if(!t||!o.isPropertyAssignment(t))return{};const e=t.getInitializer();return e&&o.isObjectLiteralExpression(e)?x(e):{}},A=r=>{const t=r?.getProperty("server");if(!t||!o.isPropertyAssignment(t))return"unknown";const e=t.getInitializer();return!e||!(o.isArrowFunction(e)||o.isFunctionExpression(e))?"unknown":g(e)},E=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==u.CallExpression)continue;const n=i,a=n.getExpression();if(!N(a))continue;const s=e.getNameNode();if(!o.isIdentifier(s))throw l(s,"defineMutator exports must be plain named exports (no destructuring)");const c=I(n);t.push({args:b(c),exportName:s.getText(),filePath:"mutators",returnType:A(c)})}return t},w=(r,t)=>{const e=p(t,M);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=E(i);return n.sort((a,s)=>a.exportName.localeCompare(s.exportName)),n};export{M as MUTATORS_FILENAME,w as discoverMutators,N as isDefineMutatorCallee};
1
+ import{existsSync as f}from"node:fs";import{join as p}from"node:path";import{Node as o,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapHandlerReturn as g}from"./discoverFunctions-CYHtspcp.mjs";import{a as d}from"./module-specifiers-WF8iAydP.mjs";import{a as x}from"./parse-validator-C5ycrhR3.mjs";const M="mutators.ts",m=d,y=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineMutator";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return m(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineMutator":!1;return!1},S=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(u.ImportDeclaration);return i!==void 0&&m(i.getModuleSpecifierValue())}return!1},N=r=>{if(o.isIdentifier(r))return y(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineMutator"&&o.isIdentifier(t)&&S(t)}return!1},I=r=>{const t=r.getArguments()[0];return t&&o.isObjectLiteralExpression(t)?t:void 0},b=r=>{const t=r?.getProperty("args");if(!t||!o.isPropertyAssignment(t))return{};const e=t.getInitializer();return e&&o.isObjectLiteralExpression(e)?x(e):{}},A=r=>{const t=r?.getProperty("server");if(!t||!o.isPropertyAssignment(t))return"unknown";const e=t.getInitializer();return!e||!(o.isArrowFunction(e)||o.isFunctionExpression(e))?"unknown":g(e)},E=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==u.CallExpression)continue;const n=i,a=n.getExpression();if(!N(a))continue;const s=e.getNameNode();if(!o.isIdentifier(s))throw l(s,"defineMutator exports must be plain named exports (no destructuring)");const c=I(n);t.push({args:b(c),exportName:s.getText(),filePath:"mutators",returnType:A(c)})}return t},w=(r,t)=>{const e=p(t,M);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=E(i);return n.sort((a,s)=>a.exportName.localeCompare(s.exportName)),n};export{M as MUTATORS_FILENAME,w as discoverMutators,N as isDefineMutatorCallee};
@@ -1 +1 @@
1
- import{existsSync as m}from"node:fs";import{join as x}from"node:path";import{SyntaxKind as d,Node as c}from"ts-morph";import{l,a as g,d as P,h as E}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as S}from"./discoverFunctions-006teuNG.mjs";const y="notify.ts",v=new Set(["chat","inApp","send","webhook"]),p=new Set(["broadcast","send"]),N=e=>{const t=e.getInitializer();if(!t||!c.isCallExpression(t))return;const o=S(t);if(!o)return;const s=E(t,o.receiver);return s?{exportName:e.getName(),handler:s,kind:o.kind}:void 0},h=e=>{const t=[];for(const o of e.getVariableStatements())if(o.isExported())for(const s of o.getDeclarations()){const r=N(s);r&&t.push(r)}return t},f=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=e.getExpression();if((t==="notify"||t==="push")&&c.isIdentifier(o)&&o.getText()==="ctx")return t;if(t==="push"&&f(o)==="notify")return"push"},F=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=f(e.getExpression());if(o==="notify"&&v.has(t))return`ctx.notify.${t}`;if(o==="push"&&p.has(t))return`ctx.push.${t}`},A=e=>c.isPropertyAccessExpression(e)?f(e.getExpression())==="push"&&p.has(e.getName()):!1,T=(e,t)=>{const o=[];for(const s of l(t)){const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=g(t,s);for(const n of h(r))if(!(n.kind!=="query"&&n.kind!=="mutation"))for(const i of n.handler.getDescendantsOfKind(d.PropertyAccessExpression)){const u=F(i);u!==void 0&&o.push({callee:u,exportName:n.exportName,file:a,kind:n.kind,line:i.getStartLineNumber()})}}return o},O=(e,t)=>{for(const o of l(t)){const s=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const r of h(s))for(const a of r.handler.getDescendantsOfKind(d.PropertyAccessExpression))if(A(a))return!0}return!1},_=(e,t)=>{const o=x(t,y);if(!m(o))return;const s=e.getSourceFile(o)??e.addSourceFileAtPath(o),r=P(s);let a=!1,n=!1;if(r&&c.isCallExpression(r)){const i=r.getArguments()[0];i&&c.isObjectLiteralExpression(i)&&(a=i.getProperty("webPush")!==void 0,n=i.getProperty("fcm")!==void 0)}return{hasFcm:n,hasWebPush:a,usesPush:O(e,t)}};export{y as NOTIFY_FILENAME,T as discoverNotifyCalls,_ as discoverNotifyConfig};
1
+ import{existsSync as m}from"node:fs";import{join as x}from"node:path";import{SyntaxKind as d,Node as c}from"ts-morph";import{l,a as g,d as P,h as E}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as S}from"./discoverFunctions-CYHtspcp.mjs";const y="notify.ts",v=new Set(["chat","inApp","send","webhook"]),p=new Set(["broadcast","send"]),N=e=>{const t=e.getInitializer();if(!t||!c.isCallExpression(t))return;const o=S(t);if(!o)return;const s=E(t,o.receiver);return s?{exportName:e.getName(),handler:s,kind:o.kind}:void 0},h=e=>{const t=[];for(const o of e.getVariableStatements())if(o.isExported())for(const s of o.getDeclarations()){const r=N(s);r&&t.push(r)}return t},f=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=e.getExpression();if((t==="notify"||t==="push")&&c.isIdentifier(o)&&o.getText()==="ctx")return t;if(t==="push"&&f(o)==="notify")return"push"},F=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=f(e.getExpression());if(o==="notify"&&v.has(t))return`ctx.notify.${t}`;if(o==="push"&&p.has(t))return`ctx.push.${t}`},A=e=>c.isPropertyAccessExpression(e)?f(e.getExpression())==="push"&&p.has(e.getName()):!1,T=(e,t)=>{const o=[];for(const s of l(t)){const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=g(t,s);for(const n of h(r))if(!(n.kind!=="query"&&n.kind!=="mutation"))for(const i of n.handler.getDescendantsOfKind(d.PropertyAccessExpression)){const u=F(i);u!==void 0&&o.push({callee:u,exportName:n.exportName,file:a,kind:n.kind,line:i.getStartLineNumber()})}}return o},O=(e,t)=>{for(const o of l(t)){const s=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const r of h(s))for(const a of r.handler.getDescendantsOfKind(d.PropertyAccessExpression))if(A(a))return!0}return!1},_=(e,t)=>{const o=x(t,y);if(!m(o))return;const s=e.getSourceFile(o)??e.addSourceFileAtPath(o),r=P(s);let a=!1,n=!1;if(r&&c.isCallExpression(r)){const i=r.getArguments()[0];i&&c.isObjectLiteralExpression(i)&&(a=i.getProperty("webPush")!==void 0,n=i.getProperty("fcm")!==void 0)}return{hasFcm:n,hasWebPush:a,usesPush:O(e,t)}};export{y as NOTIFY_FILENAME,T as discoverNotifyCalls,_ as discoverNotifyConfig};
@@ -1,3 +1,3 @@
1
- import{G as c}from"./emit-CW4ceRjr.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
1
+ import{G as c}from"./emit-BlC5DV56.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
2
2
  `,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
@@ -1,4 +1,4 @@
1
- import{existsSync as N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{toAdvisorContext as Yt}from"./formatAdvisories-CkEu1eye.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ee}from"./module-specifiers-WF8iAydP.mjs";import{C as fe,i as Zt,f as Jt,n as es,a as ts,h as ss,j as ns,b as rs,c as is,l as os,e as as,o as cs,d as ls,k as us,g as ds,p as fs,m as ps}from"./emit-CW4ceRjr.mjs";import{l as h,a as E,c as y,p as S,f as xt,i as gs,r as Et,e as ms}from"./discover-ast-D33zP-NZ.mjs";import hs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as xs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as Es}from"./discoverSandboxUsage-L0lV17de.mjs";import vs from"./discoverStorageRulesMetadata-69Y8wZb2.mjs";import{discoverWorkflows as Ss}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as As,resolveCodegenTarget as Ns}from"./DEFAULT_TARGET-Dtmu39TP.mjs";import{i as T,a as F,e as x,c as I,r as ys,b as bs,s as te,f as Is,g as Ps,d as ws}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Ts,procedureHandler as vt,chainUsesWrappedCall as St,isDatabaseAccessor as K,chainHasStep as Cs,discoverFunctions as Rs,resolveStandardSchemaType as Os}from"./discoverFunctions-006teuNG.mjs";import Fs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Ls from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Ds}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import ks from"./discoverHttpRoutes-BxF4FRZL.mjs";import Ms from"./discoverInserts-YX8AmrzL.mjs";import Ks,{discoverMaskStrategies as _s,discoverMaskMetadata as zs,discoverMaskHasNonLiteralPolicy as Us}from"./discoverMaskProcedures-BCl3fNrQ.mjs";import Bs from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as qs,isDefineMutatorCallee as $s,discoverMutators as js}from"./MUTATORS_FILENAME-B2-W8Bm3.mjs";import Vs from"./discoverNondeterministicCalls-BA91Z-vF.mjs";import{discoverNotifyConfig as Ws,discoverNotifyCalls as Hs}from"./NOTIFY_FILENAME-IJXY4yHt.mjs";import Gs from"./discoverR2sqlCalls-M2ob41UX.mjs";import Ys,{discoverRlsMetadata as Qs}from"./discoverRlsMetadata-Dwt2p8IK.mjs";import Xs from"./discoverSchema-gJ93Xjpx.mjs";import{secretKindOf as Zs,redact as Js,isHeuristicSecretKind as en,isSecretishName as tn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as sn}from"./SHAPES_FILENAME-DTp6VI6K.mjs";import{emitApp as nn}from"./emitApp-BMm-xmNg.mjs";import{buildOpenApiDocument as rn,emitOpenApiModule as on}from"./buildOpenApiDocument-VeBRFs54.mjs";import{buildOpenRpcDocument as an,emitOpenRpcModule as cn}from"./OPENRPC_VERSION-CX52iE6f.mjs";import{s as ln}from"./parse-validator-C5ycrhR3.mjs";import{buildSchemaSnapshot as un}from"./SchemaSnapshotParseError-BoHDfCO3.mjs";const dn=e=>{const t=[],s=e.tables.filter(n=>n.shardMode==="global");return s.some(n=>n.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(n=>n.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},fn=(e,t)=>{if(t===void 0)return;const s=dn(e).filter(o=>!t.has(o.name));if(s.length===0)return;const n=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
1
+ import{existsSync as N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{toAdvisorContext as Yt}from"./formatAdvisories-CkEu1eye.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ee}from"./module-specifiers-WF8iAydP.mjs";import{C as fe,i as Zt,f as Jt,n as es,a as ts,h as ss,j as ns,b as rs,c as is,l as os,e as as,o as cs,d as ls,k as us,g as ds,p as fs,m as ps}from"./emit-BlC5DV56.mjs";import{l as h,a as E,c as y,p as S,f as xt,i as gs,r as Et,e as ms}from"./discover-ast-D33zP-NZ.mjs";import hs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as xs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as Es}from"./discoverSandboxUsage-L0lV17de.mjs";import vs from"./discoverStorageRulesMetadata-DYAgRSL6.mjs";import{discoverWorkflows as Ss}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as As,resolveCodegenTarget as Ns}from"./DEFAULT_TARGET-Dtmu39TP.mjs";import{i as T,a as F,e as x,c as I,r as ys,b as bs,s as te,f as Is,g as Ps,d as ws}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Ts,procedureHandler as vt,chainUsesWrappedCall as St,isDatabaseAccessor as K,chainHasStep as Cs,discoverFunctions as Rs,resolveStandardSchemaType as Os}from"./discoverFunctions-CYHtspcp.mjs";import Fs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Ls from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Ds}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import ks from"./discoverHttpRoutes-BkwEwmK0.mjs";import Ms from"./discoverInserts-YX8AmrzL.mjs";import Ks,{discoverMaskStrategies as _s,discoverMaskMetadata as zs,discoverMaskHasNonLiteralPolicy as Us}from"./discoverMaskProcedures-DExWLcsu.mjs";import Bs from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as qs,isDefineMutatorCallee as $s,discoverMutators as js}from"./MUTATORS_FILENAME-DJerSBO-.mjs";import Vs from"./discoverNondeterministicCalls-xRw6-4OU.mjs";import{discoverNotifyConfig as Ws,discoverNotifyCalls as Hs}from"./NOTIFY_FILENAME-CPg7zlsb.mjs";import Gs from"./discoverR2sqlCalls-Ciq0-bVB.mjs";import Ys,{discoverRlsMetadata as Qs}from"./discoverRlsMetadata-Bnn3zDlc.mjs";import Xs from"./discoverSchema-gJ93Xjpx.mjs";import{secretKindOf as Zs,redact as Js,isHeuristicSecretKind as en,isSecretishName as tn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as sn}from"./SHAPES_FILENAME-DTp6VI6K.mjs";import{emitApp as nn}from"./emitApp-OyeVRgKE.mjs";import{buildOpenApiDocument as rn,emitOpenApiModule as on}from"./buildOpenApiDocument-yZ6y1ezD.mjs";import{buildOpenRpcDocument as an,emitOpenRpcModule as cn}from"./OPENRPC_VERSION-DdUjeiyx.mjs";import{s as ln}from"./parse-validator-C5ycrhR3.mjs";import{buildSchemaSnapshot as un}from"./SchemaSnapshotParseError-BoHDfCO3.mjs";const dn=e=>{const t=[],s=e.tables.filter(n=>n.shardMode==="global");return s.some(n=>n.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(n=>n.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},fn=(e,t)=>{if(t===void 0)return;const s=dn(e).filter(o=>!t.has(o.name));if(s.length===0)return;const n=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
2
2
  `);throw new O("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
3
  ${n}
4
4
 
@@ -0,0 +1,3 @@
1
+ import{G as S}from"./emit-BlC5DV56.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
2
+ `,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
+ `;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as b}from"ts-morph";import{l as k,a as R}from"./discover-ast-D33zP-NZ.mjs";import{a as z}from"./module-specifiers-WF8iAydP.mjs";import{p as _,a as T}from"./parse-validator-C5ycrhR3.mjs";import{s as U}from"./paths-C-9fwEgQ.mjs";const m=new Set(["action","mutation","query","stream"]),N=/\bany\b(?!\s*(?:\?\s*)?:)/u,P=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,j=/^[A-Za-z_$][\w$]*$/u,$=e=>j.test(e)?e:JSON.stringify(e),S={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},M={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init"},V=z,h=e=>{const t=e.getSymbol();if(!t)return e.getText();const r=t.getDeclarations();for(const i of r){if(!s.isImportSpecifier(i))continue;const o=i.getImportDeclaration().getModuleSpecifierValue();return V(o)?i.getNameNode().getText():void 0}},I=(e,t=!1)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))return;r=n.getExpression()}if(!s.isIdentifier(r))return;const i=h(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?I(o,!0):void 0}return}return m.has(i)?"public":S[i]?"internal":void 0},d=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isStringLiteral(i)?i.getLiteralValue():void 0},E=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isNumericLiteral(i)?i.getLiteralValue():void 0},K=e=>{const t=e.getProperty("cache");if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();if(r===void 0||!s.isObjectLiteralExpression(r))return;const i=d(r,"scope"),n=E(r,"maxAge"),o=E(r,"staleWhileRevalidate"),a=d(r,"tag"),c=d(r,"vary"),l={...n===void 0?{}:{maxAge:n},...i==="private"||i==="public"?{scope:i}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},B=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const t=K(e),r=e.getProperty("rest");return r!==void 0&&s.isPropertyAssignment(r)?{...t===void 0?{}:{cache:t},rest:r.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},H=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="expose")return B(t.getArguments()[0]);t=r.getExpression()}},G=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const r=t.getProperty("args");if(!r||!s.isPropertyAssignment(r))return{};const i=r.getInitializer();return!i||!s.isObjectLiteralExpression(i)?{}:T(i)},q="/_generated/",Q=(e,t,r)=>e.getImportDeclarations().some(i=>i.getModuleSpecifierSourceFile()!==t?!1:i.getNamespaceImport()!==void 0||i.getNamedImports().some(n=>n.getName()===r)),C=(e,t,r)=>{const i=e.getSourceFile();if(i.isInNodeModules()||i.isDeclarationFile()||!s.isInterfaceDeclaration(e)&&!s.isTypeAliasDeclaration(e))return!1;const n=i.getFilePath();return n.includes(q)?!1:n===r||Q(t.getSourceFile(),i,e.getName())},W=(e,t,r)=>[e.getSymbol(),e.getAliasSymbol()].flatMap(i=>i?.getDeclarations()??[]).some(i=>C(i,t,r)),X=(e,t,r)=>{const i=s.isPropertySignature(e)||s.isPropertyDeclaration(e)?e.getTypeNode():void 0;return i===void 0?!1:[i,...i.getDescendantsOfKind(b.TypeReference)].filter(n=>s.isTypeReference(n)).flatMap(n=>{const o=n.getTypeName().getSymbol();return(o?.getAliasedSymbol()??o)?.getDeclarations()??[]}).some(n=>C(n,t,r))},Y=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},F=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,g=(e,t,r,i=new Set)=>i.has(e)?!1:(i.add(e),W(e,t,r)||Y(e).some(n=>g(n,t,r,i))?!0:F(e)?e.getProperties().some(n=>n.getDeclarations().some(o=>X(o,t,r))?!0:g(n.getTypeAtLocation(t),t,r,i)):!1),J=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(s.isPropertySignature(r)||s.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(i=>i.isUndefined())},Z=8,ee=(e,t,r,i,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,r,i,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},te=(e,t,r,i,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,r,i,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},re=(e,t,r,i,n,o)=>{if(!F(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),y=J(c,l),w=y&&l.isUnion()?l.getUnionTypes().filter(f=>!f.isUndefined()):[l],v=[];for(const f of w){const x=o(f,t,r,i+1,n);if(x===void 0)return;v.push(x)}a.push(`${$(c.getName())}${y?"?":""}: ${v.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},p=(e,t,r,i,n)=>{if(i>Z||n.has(e))return;if(!g(e,t,r))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?ee(e,t,r,i,o,p):e.isUnion()?te(e,t,r,i,o,p):re(e,t,r,i,o,p)},D=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const n=(r.getSymbol()??r.getAliasSymbol())?.getName();if(n==="Promise"||n==="AsyncIterable"||n==="AsyncIterableIterator"||n==="AsyncGenerator"){const c=r.getTypeArguments()[0];c&&(r=c)}const o=r.getText(e);if(!o||o==="any"||o==="never"||N.test(o.replaceAll(P,"")))return"unknown";const a=e.getSourceFile().getFilePath();return g(r,e,a)?p(r,e,a,0,new Set)??"unknown":o},Ae=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const r=t.getTypeAtLocation(e).getProperty("types");if(!r)return;const i=r.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!i)return;const n=i.getTypeAtLocation(e),o=n.getText(e);if(!o||o==="any"||o==="never"||N.test(o.replaceAll(P,"")))return;const a=e.getSourceFile().getFilePath();return g(n,e,a)?p(n,e,a,0,new Set):o},ie=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const r=t.getProperty("handler");if(!r||!s.isPropertyAssignment(r))return"unknown";const i=r.getInitializer();return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":D(i)},ne=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":D(t)},se=e=>{let t={},r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...T(n),...t})}r=i.getExpression()}return t},oe=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="output"){const i=t.getArguments()[0];return i&&s.isExpression(i)?_(i):void 0}t=r.getExpression()}},ae=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!m.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=I(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const r=h(t);if(!r)return;if(m.has(r))return{kind:r,visibility:"public"};const i=S[r];if(i)return{kind:i,visibility:"internal"};const n=M[r];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},A=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,be=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",Te=e=>{const t=e.getArguments()[0],r=A(t);if(r!==void 0)return r;if(t===void 0||!s.isObjectLiteralExpression(t))return;const i=t.getProperty("handler");return i!==void 0&&s.isPropertyAssignment(i)?A(i.getInitializer()):void 0},ce=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ne=(e,t)=>{let r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()===t)return!0;r=i.getExpression()}return!1},Pe=(e,t,r)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=i.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&ce(o.getExpression())===r)return!0;i=n.getExpression()}return!1},le=e=>{const t=ae(e);if(t){if(t.receiver){const r=H(t.receiver),i=oe(t.receiver);return{args:se(t.receiver),...r?{expose:r}:{},kind:t.kind,...i?{output:i}:{},returnType:ne(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:G(e),kind:t.kind,returnType:ie(e),visibility:t.visibility}}},ue=8,u=(e,t=0)=>{if(t>ue)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const r=e.getSymbol()?.getValueDeclaration();return r?O(r,t+1):void 0},O=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const r=e.getInitializer();return r?u(r,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const r=e.getPropertyNameNode()?.getText()??e.getName(),o=e.getFirstAncestorByKind(b.VariableDeclaration)?.getInitializer()?.getType().getProperty(r)?.getValueDeclaration();return o?O(o,t+1):void 0}},pe=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const r=e.getInitializer(),i=r&&(s.isCallExpression(r)?r:u(r));return i?[[e.getName(),i]]:[]},L=(e,t,r)=>{const i=le(e);if(i)return{args:i.args,exportName:t,filePath:r,kind:i.kind,returnType:i.returnType,...i.output?{output:i.output}:{},visibility:i.visibility,...i.expose?{expose:i.expose}:{},...i.lifecycle?{lifecycle:i.lifecycle}:{}}},ge=(e,t)=>{const r=[];for(const i of e.getExportAssignments()){if(i.isExportEquals())continue;const n=u(i.getExpression()),o=n?L(n,"default",t):void 0;o&&r.push(o)}return r},fe=(e,t)=>{const r=[];for(const i of e.getVariableStatements())if(i.isExported())for(const n of i.getDeclarations())for(const[o,a]of pe(n)){const c=L(a,o,t);c&&r.push(c)}return r.push(...ge(e,t)),r},de=e=>{const t=new Map;for(const r of e){const i=U(r.filePath),n=t.get(i);if(n&&n!==r.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${r.filePath}" both resolve to "${i}". 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:[n,r.filePath],status:500});t.set(i,r.filePath)}},Se=(e,t)=>{const r=k(t),i=[];for(const n of r){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=R(t,n);i.push(...fe(o,a))}return i.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),de(i),i};export{Ne as chainHasStep,Pe as chainUsesWrappedCall,ae as classifyProcedureCall,Se as discoverFunctions,A as inlineHandler,be as isDatabaseAccessor,k as listLunoraSourceFiles,R as lunoraRelativePath,Te as procedureHandler,Ae as resolveStandardSchemaType,D as unwrapHandlerReturn};
@@ -1 +1 @@
1
- import{Node as a}from"ts-morph";import{l,a as m}from"./discover-ast-D33zP-NZ.mjs";import{unwrapHandlerReturn as d}from"./discoverFunctions-006teuNG.mjs";import{p as h,a as f}from"./parse-validator-C5ycrhR3.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&&a.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&a.isObjectLiteralExpression(e)?f(e):{}},P=r=>{if(!a.isCallExpression(r))return;const e=r.getExpression();if(!a.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!a.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(!a.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;a.isCallExpression(s);){const i=s.getExpression();if(!a.isPropertyAccessExpression(i))break;const c=i.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&&a.isExpression(p)&&(o.output=h(p))}s=i.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||!(a.isArrowFunction(e)||a.isFunctionExpression(e))?"unknown":d(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||!a.isCallExpression(t))continue;const i=t.getExpression();if(!a.isPropertyAccessExpression(i))continue;const c=T(t,i,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=l(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),i=m(e,s);n.push(...b(t,i))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
1
+ import{Node as a}from"ts-morph";import{l,a as m}from"./discover-ast-D33zP-NZ.mjs";import{unwrapHandlerReturn as d}from"./discoverFunctions-CYHtspcp.mjs";import{p as h,a as f}from"./parse-validator-C5ycrhR3.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&&a.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&a.isObjectLiteralExpression(e)?f(e):{}},P=r=>{if(!a.isCallExpression(r))return;const e=r.getExpression();if(!a.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!a.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(!a.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;a.isCallExpression(s);){const i=s.getExpression();if(!a.isPropertyAccessExpression(i))break;const c=i.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&&a.isExpression(p)&&(o.output=h(p))}s=i.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||!(a.isArrowFunction(e)||a.isFunctionExpression(e))?"unknown":d(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||!a.isCallExpression(t))continue;const i=t.getExpression();if(!a.isPropertyAccessExpression(i))continue;const c=T(t,i,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=l(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),i=m(e,s);n.push(...b(t,i))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
@@ -1 +1 @@
1
- import{Node as i}from"ts-morph";import{l as f,a as P,t as x}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as p}from"./discoverFunctions-006teuNG.mjs";const A=e=>{if(!i.isCallExpression(e))return!1;const s=e.getExpression();return i.isIdentifier(s)?s.getText()==="mask":i.isPropertyAccessExpression(s)?s.getName()==="mask":!1},u=e=>{if(i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e))return e.getName()},k=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,table:o})}}return t},g=e=>{const s=[];let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const o=t.getArguments()[0];o&&A(o)&&s.push(o)}t=r.getExpression()}return s},E=e=>{const s=g(e);return{maskColumns:s.flatMap(t=>k(t)),usesMask:s.length>0}},M=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),S=new Set(["delete","insert","patch","replace"]),b=(e,s)=>{if(!i.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const r=p(t);if(!r)return;const o=r.receiver?E(r.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=x(e,M,S);return{exportName:e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:r.visibility}},w=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=b(c,n);l&&t.push(l)}}return t},h=e=>{if(i.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&i.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},C=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,strategy:h(a),table:o})}}return t},v=e=>{const s=[];for(const t of e.getVariableStatements())if(t.isExported())for(const r of t.getDeclarations()){const o=r.getInitializer(),n=o&&i.isCallExpression(o)?p(o):void 0;n?.receiver&&s.push(n.receiver)}return s},R=(e,s)=>{const t=new Map;for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of v(o))for(const a of g(n))for(const c of C(a)){const l=`${c.table}\0${c.column}`;t.has(l)||t.set(l,c)}}return{columns:[...t.values()]}},F=(e,s,t)=>{const r=e.getArguments()[0];if(!r||!i.isObjectLiteralExpression(r))return[];const o=[];for(const n of r.getProperties()){const a=u(n);if(a===void 0||!i.isPropertyAssignment(n))continue;const c=n.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const m=u(l);if(m===void 0)continue;const d=h(l);d!=="custom"&&o.push({column:m,exportName:s,file:t,line:l.getStartLineNumber(),strategy:d,table:a})}}return o},z=(e,s)=>{if(!i.isVariableDeclaration(e))return[];const t=e.getInitializer(),r=t&&i.isCallExpression(t)?p(t):void 0;return r?.receiver?g(r.receiver).flatMap(o=>F(o,e.getName(),s)):[]},T=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())t.push(...z(c,n))}return t},D=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,L=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?D(e):!0,y=(e,s=!1)=>{for(const t of e.getProperties()){if(L(t))return!0;if(s)continue;if(!i.isPropertyAssignment(t))return!0;const r=t.getInitializer();if(!r||!i.isObjectLiteralExpression(r)||y(r,!0))return!0}return!1},j=(e,s)=>{for(const t of f(s)){const r=e.getSourceFile(t)??e.addSourceFileAtPath(t);for(const o of v(r))for(const n of g(o)){const a=n.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||y(a)))return!0}}return!1};export{w as default,j as discoverMaskHasNonLiteralPolicy,R as discoverMaskMetadata,T as discoverMaskStrategies};
1
+ import{Node as i}from"ts-morph";import{l as f,a as P,t as x}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as p}from"./discoverFunctions-CYHtspcp.mjs";const A=e=>{if(!i.isCallExpression(e))return!1;const s=e.getExpression();return i.isIdentifier(s)?s.getText()==="mask":i.isPropertyAccessExpression(s)?s.getName()==="mask":!1},u=e=>{if(i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e))return e.getName()},k=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,table:o})}}return t},g=e=>{const s=[];let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const o=t.getArguments()[0];o&&A(o)&&s.push(o)}t=r.getExpression()}return s},E=e=>{const s=g(e);return{maskColumns:s.flatMap(t=>k(t)),usesMask:s.length>0}},M=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),S=new Set(["delete","insert","patch","replace"]),b=(e,s)=>{if(!i.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const r=p(t);if(!r)return;const o=r.receiver?E(r.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=x(e,M,S);return{exportName:e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:r.visibility}},w=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=b(c,n);l&&t.push(l)}}return t},h=e=>{if(i.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&i.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},C=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,strategy:h(a),table:o})}}return t},v=e=>{const s=[];for(const t of e.getVariableStatements())if(t.isExported())for(const r of t.getDeclarations()){const o=r.getInitializer(),n=o&&i.isCallExpression(o)?p(o):void 0;n?.receiver&&s.push(n.receiver)}return s},R=(e,s)=>{const t=new Map;for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of v(o))for(const a of g(n))for(const c of C(a)){const l=`${c.table}\0${c.column}`;t.has(l)||t.set(l,c)}}return{columns:[...t.values()]}},F=(e,s,t)=>{const r=e.getArguments()[0];if(!r||!i.isObjectLiteralExpression(r))return[];const o=[];for(const n of r.getProperties()){const a=u(n);if(a===void 0||!i.isPropertyAssignment(n))continue;const c=n.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const m=u(l);if(m===void 0)continue;const d=h(l);d!=="custom"&&o.push({column:m,exportName:s,file:t,line:l.getStartLineNumber(),strategy:d,table:a})}}return o},z=(e,s)=>{if(!i.isVariableDeclaration(e))return[];const t=e.getInitializer(),r=t&&i.isCallExpression(t)?p(t):void 0;return r?.receiver?g(r.receiver).flatMap(o=>F(o,e.getName(),s)):[]},T=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())t.push(...z(c,n))}return t},D=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,L=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?D(e):!0,y=(e,s=!1)=>{for(const t of e.getProperties()){if(L(t))return!0;if(s)continue;if(!i.isPropertyAssignment(t))return!0;const r=t.getInitializer();if(!r||!i.isObjectLiteralExpression(r)||y(r,!0))return!0}return!1},j=(e,s)=>{for(const t of f(s)){const r=e.getSourceFile(t)??e.addSourceFileAtPath(t);for(const o of v(r))for(const n of g(o)){const a=n.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||y(a)))return!0}}return!1};export{w as default,j as discoverMaskHasNonLiteralPolicy,R as discoverMaskMetadata,T as discoverMaskStrategies};
@@ -1 +1 @@
1
- import{Node as s,SyntaxKind as a}from"ts-morph";import{l,a as c,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-006teuNG.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 l(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,c(t,i)))}return n};export{w as default};
1
+ import{Node as s,SyntaxKind as a}from"ts-morph";import{l,a as c,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-CYHtspcp.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 l(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,c(t,i)))}return n};export{w as default};
@@ -1 +1 @@
1
- import{Node as o,SyntaxKind as a}from"ts-morph";import{l as c,a as l,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-006teuNG.mjs";const u=t=>{const r=t.getInitializer();if(!r||!o.isCallExpression(r))return;const e=f(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const n=d(r,e.receiver);return n?{exportName:t.getName(),handler:n,kind:e.kind}:void 0},p=t=>{if(!o.isPropertyAccessExpression(t)||t.getName()!=="r2sql")return;const r=t.getExpression();if(!o.isIdentifier(r)||r.getText()!=="ctx")return;const e=t.getParent();return e&&o.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.r2sql.${e.getName()}`:"ctx.r2sql"},x=(t,r)=>{const e=[];for(const n of t.handler.getDescendantsOfKind(a.PropertyAccessExpression)){const s=p(n);s!==void 0&&e.push({callee:s,exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()})}return e},m=(t,r)=>{const e=[];for(const n of t.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const i=u(s);i&&e.push(...x(i,r))}return e},P=(t,r)=>{const e=[];for(const n of c(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);e.push(...m(s,l(r,n)))}return e};export{P as default};
1
+ import{Node as o,SyntaxKind as a}from"ts-morph";import{l as c,a as l,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-CYHtspcp.mjs";const u=t=>{const r=t.getInitializer();if(!r||!o.isCallExpression(r))return;const e=f(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const n=d(r,e.receiver);return n?{exportName:t.getName(),handler:n,kind:e.kind}:void 0},p=t=>{if(!o.isPropertyAccessExpression(t)||t.getName()!=="r2sql")return;const r=t.getExpression();if(!o.isIdentifier(r)||r.getText()!=="ctx")return;const e=t.getParent();return e&&o.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.r2sql.${e.getName()}`:"ctx.r2sql"},x=(t,r)=>{const e=[];for(const n of t.handler.getDescendantsOfKind(a.PropertyAccessExpression)){const s=p(n);s!==void 0&&e.push({callee:s,exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()})}return e},m=(t,r)=>{const e=[];for(const n of t.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const i=u(s);i&&e.push(...x(i,r))}return e},P=(t,r)=>{const e=[];for(const n of c(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);e.push(...m(s,l(r,n)))}return e};export{P as default};
@@ -1 +1 @@
1
- import{Node as n}from"ts-morph";import{l as d,a as x,t as P,b as l}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as E}from"./discoverFunctions-006teuNG.mjs";const b=t=>{if(!n.isCallExpression(t))return!1;const e=t.getExpression();return n.isIdentifier(e)?e.getText()==="rls":n.isPropertyAccessExpression(e)?e.getName()==="rls":!1},v=t=>{const e=t.getArguments()[0];if(!e||!n.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements()){if(!n.isObjectLiteralExpression(r))continue;const i=r.getProperty("table");if(!i||!n.isPropertyAssignment(i))continue;const o=i.getInitializer();o&&n.isStringLiteral(o)&&s.push(o.getLiteralText())}return s},h=t=>{const e=[];let s=t;for(;n.isCallExpression(s);){const r=s.getExpression();if(!n.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const i=s.getArguments()[0];i&&b(i)&&e.push(i)}s=r.getExpression()}return e},y=t=>{const e=h(t);return{rlsTables:e.flatMap(s=>v(s)),usesRls:e.length>0}},A=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),L=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),S=(t,e)=>{if(!n.isVariableDeclaration(t))return;const s=t.getInitializer();if(!s||!n.isCallExpression(s))return;const r=E(s);if(!r)return;const i=r.receiver?y(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:o,tablesWritten:a}=P(t,A,L);return{exportName:t.getName(),file:e,rlsTables:i.rlsTables,tablesRead:o,tablesWritten:a,usesRls:i.usesRls,visibility:r.visibility}},w=(t,e)=>{const s=[];for(const r of d(e)){const i=t.getSourceFile(r)??t.addSourceFileAtPath(r),o=x(e,r);for(const a of i.getVariableStatements())if(a.isExported())for(const u of a.getDeclarations()){const c=S(u,o);c&&s.push(c)}}return s},C=new Set(["delete","insert","read","update"]),T=(t,e,s)=>{const r=t.getArguments()[0];if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){if(!n.isObjectLiteralExpression(o))continue;const a=l(o,"on");a===void 0||!C.has(a)||i.push({file:e,on:a,procedure:s,table:l(o,"table")??""})}return i},g=t=>{if(!n.isObjectLiteralExpression(t))return[];const e=t.getProperty("permissions");if(!e||!n.isPropertyAssignment(e))return[];const s=e.getInitializer();if(!s||!n.isArrayLiteralExpression(s))return[];const r=[];for(const i of s.getElements()){if(n.isStringLiteral(i)){r.push(i.getLiteralText());continue}if(n.isCallExpression(i)){const o=i.getArguments()[0];o&&n.isStringLiteral(o)&&r.push(o.getLiteralText())}}return r},m=(t,e)=>e===void 0?t:{...t,description:e},R=t=>{if(n.isCallExpression(t)){const e=t.getArguments()[0];if(!e||!n.isStringLiteral(e))return;const s=t.getArguments()[1],r=s?l(s,"description"):void 0,i=s?g(s):[];return m({name:e.getLiteralText(),permissions:i},r)}if(n.isObjectLiteralExpression(t)){const e=l(t,"name");return e===void 0?void 0:m({name:e,permissions:g(t)},l(t,"description"))}},F=t=>{const e=t.getArguments()[1];if(!e||!n.isObjectLiteralExpression(e))return[];const s=e.getProperty("roles");if(!s||!n.isPropertyAssignment(s))return[];const r=s.getInitializer();if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){const a=R(o);a&&i.push(a)}return i},I=(t,e,s)=>{const r=h(t);return{policies:r.flatMap(i=>T(i,e,s)),roles:r.flatMap(i=>F(i))}},M=t=>{const e=[];for(const s of t.getVariableStatements())if(s.isExported())for(const r of s.getDeclarations()){const i=r.getInitializer(),o=i&&n.isCallExpression(i)?E(i):void 0;o?.receiver&&e.push({name:r.getName(),receiver:o.receiver})}return e},D=(t,e)=>{const s=[],r=new Map;for(const i of d(e)){const o=t.getSourceFile(i)??t.addSourceFileAtPath(i),a=x(e,i);for(const{name:u,receiver:c}of M(o)){const p=I(c,a,u);s.push(...p.policies);for(const f of p.roles)r.has(f.name)||r.set(f.name,f)}}return{policies:s,roles:[...r.values()]}};export{w as default,D as discoverRlsMetadata};
1
+ import{Node as n}from"ts-morph";import{l as d,a as x,t as P,b as l}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as E}from"./discoverFunctions-CYHtspcp.mjs";const b=t=>{if(!n.isCallExpression(t))return!1;const e=t.getExpression();return n.isIdentifier(e)?e.getText()==="rls":n.isPropertyAccessExpression(e)?e.getName()==="rls":!1},v=t=>{const e=t.getArguments()[0];if(!e||!n.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements()){if(!n.isObjectLiteralExpression(r))continue;const i=r.getProperty("table");if(!i||!n.isPropertyAssignment(i))continue;const o=i.getInitializer();o&&n.isStringLiteral(o)&&s.push(o.getLiteralText())}return s},h=t=>{const e=[];let s=t;for(;n.isCallExpression(s);){const r=s.getExpression();if(!n.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const i=s.getArguments()[0];i&&b(i)&&e.push(i)}s=r.getExpression()}return e},y=t=>{const e=h(t);return{rlsTables:e.flatMap(s=>v(s)),usesRls:e.length>0}},A=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),L=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),S=(t,e)=>{if(!n.isVariableDeclaration(t))return;const s=t.getInitializer();if(!s||!n.isCallExpression(s))return;const r=E(s);if(!r)return;const i=r.receiver?y(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:o,tablesWritten:a}=P(t,A,L);return{exportName:t.getName(),file:e,rlsTables:i.rlsTables,tablesRead:o,tablesWritten:a,usesRls:i.usesRls,visibility:r.visibility}},w=(t,e)=>{const s=[];for(const r of d(e)){const i=t.getSourceFile(r)??t.addSourceFileAtPath(r),o=x(e,r);for(const a of i.getVariableStatements())if(a.isExported())for(const u of a.getDeclarations()){const c=S(u,o);c&&s.push(c)}}return s},C=new Set(["delete","insert","read","update"]),T=(t,e,s)=>{const r=t.getArguments()[0];if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){if(!n.isObjectLiteralExpression(o))continue;const a=l(o,"on");a===void 0||!C.has(a)||i.push({file:e,on:a,procedure:s,table:l(o,"table")??""})}return i},g=t=>{if(!n.isObjectLiteralExpression(t))return[];const e=t.getProperty("permissions");if(!e||!n.isPropertyAssignment(e))return[];const s=e.getInitializer();if(!s||!n.isArrayLiteralExpression(s))return[];const r=[];for(const i of s.getElements()){if(n.isStringLiteral(i)){r.push(i.getLiteralText());continue}if(n.isCallExpression(i)){const o=i.getArguments()[0];o&&n.isStringLiteral(o)&&r.push(o.getLiteralText())}}return r},m=(t,e)=>e===void 0?t:{...t,description:e},R=t=>{if(n.isCallExpression(t)){const e=t.getArguments()[0];if(!e||!n.isStringLiteral(e))return;const s=t.getArguments()[1],r=s?l(s,"description"):void 0,i=s?g(s):[];return m({name:e.getLiteralText(),permissions:i},r)}if(n.isObjectLiteralExpression(t)){const e=l(t,"name");return e===void 0?void 0:m({name:e,permissions:g(t)},l(t,"description"))}},F=t=>{const e=t.getArguments()[1];if(!e||!n.isObjectLiteralExpression(e))return[];const s=e.getProperty("roles");if(!s||!n.isPropertyAssignment(s))return[];const r=s.getInitializer();if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){const a=R(o);a&&i.push(a)}return i},I=(t,e,s)=>{const r=h(t);return{policies:r.flatMap(i=>T(i,e,s)),roles:r.flatMap(i=>F(i))}},M=t=>{const e=[];for(const s of t.getVariableStatements())if(s.isExported())for(const r of s.getDeclarations()){const i=r.getInitializer(),o=i&&n.isCallExpression(i)?E(i):void 0;o?.receiver&&e.push({name:r.getName(),receiver:o.receiver})}return e},D=(t,e)=>{const s=[],r=new Map;for(const i of d(e)){const o=t.getSourceFile(i)??t.addSourceFileAtPath(i),a=x(e,i);for(const{name:u,receiver:c}of M(o)){const p=I(c,a,u);s.push(...p.policies);for(const f of p.roles)r.has(f.name)||r.set(f.name,f)}}return{policies:s,roles:[...r.values()]}};export{w as default,D as discoverRlsMetadata};
@@ -1 +1 @@
1
- import{Node as n}from"ts-morph";import{l as f,a as p,b as u}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as g}from"./discoverFunctions-006teuNG.mjs";const m=new Set(["delete","list","read","write"]),d=o=>{if(!n.isCallExpression(o))return!1;const e=o.getExpression();return n.isIdentifier(e)?e.getText()==="storageRules":n.isPropertyAccessExpression(e)&&e.getName()==="storageRules"},x=o=>{const e=[];let s=o;for(;n.isCallExpression(s);){const t=s.getExpression();if(!n.isPropertyAccessExpression(t))break;if(t.getName()==="use"){const r=s.getArguments()[0];r&&d(r)&&e.push(r)}s=t.getExpression()}return e},h=(o,e,s)=>{const t=o.getArguments()[0];if(!t||!n.isArrayLiteralExpression(t))return[];const r=[];for(const i of t.getElements()){if(!n.isObjectLiteralExpression(i))continue;const a=u(i,"on");if(a===void 0||!m.has(a))continue;const c=u(i,"prefix"),l={bucket:u(i,"bucket")??"",file:e,on:a,procedure:s};c!==void 0&&(l.prefix=c),r.push(l)}return r},E=o=>{const e=[];for(const s of o.getVariableStatements())if(s.isExported())for(const t of s.getDeclarations()){const r=t.getInitializer(),i=r&&n.isCallExpression(r)?g(r):void 0;i?.receiver&&e.push({name:t.getName(),receiver:i.receiver})}return e},R=(o,e)=>{const s=[];for(const t of f(e)){const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),i=p(e,t);for(const{name:a,receiver:c}of E(r))for(const l of x(c))s.push(...h(l,i,a))}return{rules:s}};export{R as default};
1
+ import{Node as n}from"ts-morph";import{l as f,a as p,b as u}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as g}from"./discoverFunctions-CYHtspcp.mjs";const m=new Set(["delete","list","read","write"]),d=o=>{if(!n.isCallExpression(o))return!1;const e=o.getExpression();return n.isIdentifier(e)?e.getText()==="storageRules":n.isPropertyAccessExpression(e)&&e.getName()==="storageRules"},x=o=>{const e=[];let s=o;for(;n.isCallExpression(s);){const t=s.getExpression();if(!n.isPropertyAccessExpression(t))break;if(t.getName()==="use"){const r=s.getArguments()[0];r&&d(r)&&e.push(r)}s=t.getExpression()}return e},h=(o,e,s)=>{const t=o.getArguments()[0];if(!t||!n.isArrayLiteralExpression(t))return[];const r=[];for(const i of t.getElements()){if(!n.isObjectLiteralExpression(i))continue;const a=u(i,"on");if(a===void 0||!m.has(a))continue;const c=u(i,"prefix"),l={bucket:u(i,"bucket")??"",file:e,on:a,procedure:s};c!==void 0&&(l.prefix=c),r.push(l)}return r},E=o=>{const e=[];for(const s of o.getVariableStatements())if(s.isExported())for(const t of s.getDeclarations()){const r=t.getInitializer(),i=r&&n.isCallExpression(r)?g(r):void 0;i?.receiver&&e.push({name:t.getName(),receiver:i.receiver})}return e},R=(o,e)=>{const s=[];for(const t of f(e)){const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),i=p(e,t);for(const{name:a,receiver:c}of E(r))for(const l of x(c))s.push(...h(l,i,a))}return{rules:s}};export{R as default};
@@ -1,4 +1,4 @@
1
- import{agentComponent as at}from"@lunora/agent/component";import{LunoraError as te}from"@lunora/errors";import{serializeSchemaSnapshot as fn,hashSchemaSnapshot as yn}from"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";const st=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",serverCtxField:{field:`
1
+ import{agentComponent as at}from"@lunora/agent/component";import{LunoraError as te}from"@lunora/errors";import{serializeSchemaSnapshot as yn,hashSchemaSnapshot as bn}from"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";const st=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",serverCtxField:{field:`
2
2
  /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
3
3
  readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",serverCtxField:{field:`
4
4
  /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
@@ -15,35 +15,35 @@ import{agentComponent as at}from"@lunora/agent/component";import{LunoraError as
15
15
  /**
16
16
  * R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
17
17
  */
18
- readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],bn=st,kn=new Map(bn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Vr=st.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),it=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,wn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),lt=e=>e.column!==void 0,xn=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
18
+ readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],kn=st,wn=new Map(kn.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),Vr=st.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),it=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,xn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),lt=e=>e.column!==void 0,vn=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
19
19
  `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
20
20
  `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
21
21
  `;case"null":return`if (${t} !== null) return DEFER;
22
22
  `;default:return`if (typeof ${t} !== "string") return DEFER;
23
- `}},vn=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!it.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
24
- `}},We=(e,t,n)=>{if(!lt(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(wn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:xn(e.kind,t)};switch(e.kind){case"array":return $n(e,t,n);case"literal":return vn(e,t);case"object":return Nn(e,t,n);default:return}}},$n=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),s=`__arr${String(o)}`,i=`__i${String(o)}`,a=`__e${String(o)}`,c=We(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
23
+ `}},$n=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!it.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
24
+ `}},We=(e,t,n)=>{if(!lt(e)&&!(e.hasRefinement||e.sourceText!==void 0)){if(xn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:vn(e.kind,t)};switch(e.kind){case"array":return Rn(e,t,n);case"literal":return $n(e,t);case"object":return Tn(e,t,n);default:return}}},Rn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),s=`__arr${String(o)}`,i=`__i${String(o)}`,a=`__e${String(o)}`,c=We(r,a,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
25
25
  const ${s} = new Array(${t}.length);
26
26
  for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
27
27
  const ${a} = ${t}[${i}];
28
28
  ${c.pre}${s}[${i}] = ${c.out};
29
29
  }
30
- `;return{out:s,pre:d}},Rn=(e,t,n,r)=>{const o=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||lt(t))return;const{inner:i}=t;if(!i)return;const a=We(i,n,r);if(!a)return;const c=r.next(),d=`__has${String(c)}`,p=`__val${String(c)}`,h=`let ${d} = false;
30
+ `;return{out:s,pre:d}},Sn=(e,t,n,r)=>{const o=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||lt(t))return;const{inner:i}=t;if(!i)return;const a=We(i,n,r);if(!a)return;const c=r.next(),d=`__has${String(c)}`,p=`__val${String(c)}`,h=`let ${d} = false;
31
31
  let ${p};
32
32
  if (${n} !== undefined) {
33
33
  ${a.pre}${p} = ${a.out};
34
34
  ${d} = true;
35
35
  }
36
- `;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:h}}const s=We(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},Sn=new Set(Object.getOwnPropertyNames(Object.prototype)),ct=(e,t,n)=>{let r="";const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)return;const a=JSON.stringify(s);let c=`${t}[${a}]`;if(Sn.has(s)){const p=`__f${String(n.next())}`;r+=`const ${p} = Object.hasOwn(${t}, ${a}) ? ${t}[${a}] : undefined;
37
- `,c=p}const d=Rn(s,i,c,n);if(!d)return;r+=d.pre,o.push(d.entry)}return{entries:o.join(", "),pre:r}},dt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
38
- `},Nn=(e,t,n)=>{const r=e.shape??{},o=ct(r,t,n);if(!o)return;const s=n.next(),i=`__obj${String(s)}`,a=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
36
+ `;return{entry:`...(${d} ? { ${o}: ${p} } : {})`,pre:h}}const s=We(t,n,r);if(s)return{entry:`${o}: ${s.out}`,pre:s.pre}},Nn=new Set(Object.getOwnPropertyNames(Object.prototype)),ct=(e,t,n)=>{let r="";const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)return;const a=JSON.stringify(s);let c=`${t}[${a}]`;if(Nn.has(s)){const p=`__f${String(n.next())}`;r+=`const ${p} = Object.hasOwn(${t}, ${a}) ? ${t}[${a}] : undefined;
37
+ `,c=p}const d=Sn(s,i,c,n);if(!d)return;r+=d.pre,o.push(d.entry)}return{entries:o.join(", "),pre:r}},dt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
38
+ `},Tn=(e,t,n)=>{const r=e.shape??{},o=ct(r,t,n);if(!o)return;const s=n.next(),i=`__obj${String(s)}`,a=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
39
39
  ${dt(t)}${o.pre}const ${i} = { ${o.entries} };
40
- `;return{out:i,pre:a}},Tn=e=>{let t=0;const r=ct(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
40
+ `;return{out:i,pre:a}},An=e=>{let t=0;const r=ct(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
41
41
  if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
42
42
  ${dt("source")}${r.pre}return { ${r.entries} };
43
43
  }`},S=`// GENERATED by @lunora/codegen — do not edit.
44
44
  // Run \`lunora codegen\` to regenerate.
45
45
 
46
- `,ne=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},ut=/^[A-Za-z_$][\w$]*$/u,An=/^[\w./-]+$/u,g=(e,t)=>{if(!ut.test(e))throw new te("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},qe=e=>e.charAt(0).toUpperCase()+e.slice(1),E=e=>ut.test(e)?e:JSON.stringify(e),On={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},In=e=>{if(e===void 0)return"unknown";if(!it.test(e))throw new te("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},A=e=>{const t=On[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?A(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return g(n,"v.id() table name"),`Id<"${n}">`}case"literal":return In(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>pt(r,o)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?A(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?A(e.keyType):"string",r=e.valueType?A(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>A(n)).join(" | "):"never";default:return"unknown"}},pt=(e,t)=>{const n=E(e);if(t.kind==="optional"){const r=t.inner?A(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${A(t)}`},ke=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>pt(n,r)).join("; ")} }`},mt=e=>e.kind==="optional"||!!e.column?.hasDefault,re=e=>e.kind==="optional"&&e.inner?e.inner:e,Cn=e=>{g(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=re(o),i=A(s),a=E(r);return mt(o)?` ${a}?: ${i};`:` ${a}: ${i};`}).join(`
46
+ `,ne=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},ut=/^[A-Za-z_$][\w$]*$/u,On=/^[\w./-]+$/u,g=(e,t)=>{if(!ut.test(e))throw new te("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},qe=e=>e.charAt(0).toUpperCase()+e.slice(1),E=e=>ut.test(e)?e:JSON.stringify(e),In={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},Cn=e=>{if(e===void 0)return"unknown";if(!it.test(e))throw new te("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},A=e=>{const t=In[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?A(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return g(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Cn(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>pt(r,o)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?A(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?A(e.keyType):"string",r=e.valueType?A(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>A(n)).join(" | "):"never";default:return"unknown"}},pt=(e,t)=>{const n=E(e);if(t.kind==="optional"){const r=t.inner?A(t.inner):"unknown";return`${n}?: ${r}`}return`${n}: ${A(t)}`},ke=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>pt(n,r)).join("; ")} }`},mt=e=>e.kind==="optional"||!!e.column?.hasDefault,re=e=>e.kind==="optional"&&e.inner?e.inner:e,Ln=e=>{g(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const s=re(o),i=A(s),a=E(r);return mt(o)?` ${a}?: ${i};`:` ${a}: ${i};`}).join(`
47
47
  `),n=t?`
48
48
  ${t}
49
49
  `:"";return`export interface Insert_${e.name} {
@@ -61,7 +61,7 @@ ${l}
61
61
  `),i=e.tables.map(u=>{const l=u.searchIndexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
62
62
  `),a=e.tables.map(u=>{const l=u.rankIndexes.map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
63
63
  `),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(f=>JSON.stringify(f.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
64
- `),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>Cn(u)).join(`
64
+ `),d=e.vectorIndexes.map(u=>JSON.stringify(u.name)).join(" | ")||"never",p=e.tables.map(u=>Ln(u)).join(`
65
65
 
66
66
  `),h=e.tables.map(u=>` ${u.name}: Insert_${u.name};`).join(`
67
67
  `),y=e.tables.map(u=>{const l=u.relations.map(f=>(g(f.table,"relation target table"),` ${E(f.name)}: ${f.kind==="one"?"OneRelation":"ManyRelation"}<"${f.table}">;`)).join(`
@@ -160,7 +160,7 @@ export interface Relations {
160
160
  ${y}
161
161
  }
162
162
 
163
- `,Ue)},Ln=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,ht=/^(?:\.\.?\/)*_generated\//u,gt=/\.[A-Za-z]\w*$/u,_n=e=>e.replaceAll(Ln,(t,n)=>{const r=n.replace(ht,"./");return`import("${gt.test(r)?r:`${r}.js`}")`}),En=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Dn=/^(?:\.\.?\/)+/u,Fn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Pn=(e,t)=>e.replaceAll(En,(n,r)=>{if(ht.test(r.replace(Dn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Fn(`${o}/${r}`)}`;return`import("${gt.test(i)?i:`${i}.js`}")`}),D=(e,t)=>_n(Pn(e,t)),Mn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],Bn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Mn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),jn={flags:new Set(["/web"]),platform:new Set},ft=(e,t)=>t?e.replaceAll(Bn,(n,r,o)=>{const s=jn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,Ke=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),qn=e=>e.output===void 0||e.output.kind==="any"?e.returnType:A(e.output),Qe=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},rt=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=D(ke(s.args),s.filePath),a=D(qn(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
163
+ `,Ue)},_n=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,ht=/^(?:\.\.?\/)*_generated\//u,gt=/\.[A-Za-z]\w*$/u,En=e=>e.replaceAll(_n,(t,n)=>{const r=n.replace(ht,"./");return`import("${gt.test(r)?r:`${r}.js`}")`}),Dn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Fn=/^(?:\.\.?\/)+/u,Pn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Mn=(e,t)=>e.replaceAll(Dn,(n,r)=>{if(ht.test(r.replace(Fn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Pn(`${o}/${r}`)}`;return`import("${gt.test(i)?i:`${i}.js`}")`}),D=(e,t)=>En(Mn(e,t)),Bn=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],jn=new RegExp(String.raw`import\("@lunora/(?<pkg>${Bn.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),qn={flags:new Set(["/web"]),platform:new Set},ft=(e,t)=>t?e.replaceAll(jn,(n,r,o)=>{const s=qn[r];return o&&s&&!s.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,Ke=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`\b${t}<`,"u").test(e)),yt=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:A(e.output),Qe=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},rt=e=>{const t=([n,r])=>{const o=r.toSorted((s,i)=>s.exportName.localeCompare(i.exportName)).map(s=>{const i=D(ke(s.args),s.filePath),a=D(yt(s),s.filePath);return` ${s.exportName}: FunctionReference<"${s.kind}", ${i}, ${a}>;`}).join(`
164
164
  `);return` ${E(N(n))}: {
165
165
  ${o}
166
166
  };`};return Qe(e).map(n=>t(n)).join(`
@@ -196,7 +196,7 @@ export const agents: AgentsRef = {
196
196
  ${i}
197
197
  };
198
198
  `,n.push(`import type { AgentRunInput } from "@lunora/agent";
199
- `)}return{block:r,importLine:n.join("")}},Un=()=>Object.keys(at().functions).toSorted((e,t)=>e.localeCompare(t)),yt=e=>new Set(e.filter(t=>N(t.filePath)==="agents").map(t=>t.exportName)),Kn=()=>new Set(Object.entries(at().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Qn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=yt(t),o=Kn(),s=t.find(a=>N(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new te("INTERNAL",`@lunora/codegen: "agents:${s.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${s.exportName}" export in ${s.filePath}`);const i=Un().filter(a=>!r.has(a));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
199
+ `)}return{block:r,importLine:n.join("")}},Un=()=>Object.keys(at().functions).toSorted((e,t)=>e.localeCompare(t)),bt=e=>new Set(e.filter(t=>N(t.filePath)==="agents").map(t=>t.exportName)),Kn=()=>new Set(Object.entries(at().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),Qn=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=bt(t),o=Kn(),s=t.find(a=>N(a.filePath)==="agents"&&o.has(a.exportName));if(s)throw new te("INTERNAL",`@lunora/codegen: "agents:${s.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${s.exportName}" export in ${s.filePath}`);const i=Un().filter(a=>!r.has(a));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
200
200
  `,lines:i.map(a=>` "agents:${a}": lunoraAgentRuntimeFunctions.${a} as unknown as RegisteredLunoraFunction,`).join(`
201
201
  `),prelude:`
202
202
  /**
@@ -206,7 +206,7 @@ ${i}
206
206
  */
207
207
  const lunoraAgentRuntimeFunctions = agentComponent().functions;
208
208
  `}},Vn=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>N(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new te("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
209
- `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},Hn=(e,t)=>{if(e.length===0)return[];const n=yt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},Jn=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>N(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},Gn=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Qe(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=D(d.chunkType??"unknown",d.filePath),h=D(ke(d.searchParams),d.filePath),y=D(ke(d.params),d.filePath);return` ${E(d.exportName)}: HttpStreamRef<${p}, ${h}, ${y}>;`}).join(`
209
+ `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},Hn=(e,t)=>{if(e.length===0)return[];const n=bt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},Jn=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>N(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},Gn=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Qe(t),r=n.map(([i,a])=>{const c=a.map(d=>{const p=D(d.chunkType??"unknown",d.filePath),h=D(ke(d.searchParams),d.filePath),y=D(ke(d.params),d.filePath);return` ${E(d.exportName)}: HttpStreamRef<${p}, ${h}, ${y}>;`}).join(`
210
210
  `);return` ${E(N(i))}: {
211
211
  ${c}
212
212
  };`}).join(`
@@ -321,13 +321,13 @@ ${s}
321
321
  }
322
322
 
323
323
  return (await registered.handler(context, args ?? {})) as R;
324
- };`,Xn=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,zn(l,o.size))};for(const l of e)s(l.filePath);for(const l of t)s(l.filePath);for(const l of n)s(l.filePath);for(const l of r)s(l.filePath);const i=[...o.entries()].map(([l,f])=>{if(!An.test(l))throw new te("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${f} from "../${l}.js";`}).join(`
324
+ };`,Xn=(e,t,n=[],r=[])=>{const o=new Map,s=l=>{o.has(l)||o.set(l,zn(l,o.size))};for(const l of e)s(l.filePath);for(const l of t)s(l.filePath);for(const l of n)s(l.filePath);for(const l of r)s(l.filePath);const i=[...o.entries()].map(([l,f])=>{if(!On.test(l))throw new te("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${f} from "../${l}.js";`}).join(`
325
325
  `),a=e.map(l=>` "${N(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
326
326
  `),c=t.map(l=>` ${JSON.stringify(l.id)}: ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
327
327
  `),d=n.map(l=>` "${N(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
328
328
  `),p=r.map(l=>` "${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
329
329
  `),h=n.map(l=>`${N(l.filePath)}:${l.exportName}`),y=[a,d].filter(l=>l.length>0).join(`
330
- `),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const f=Tn(l.args);return f===void 0?void 0:`installCompiledValidatorMap(${o.get(l.filePath)??""}.${l.exportName}.args, ${f});`}).filter(l=>l!==void 0).join(`
330
+ `),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const f=An(l.args);return f===void 0?void 0:`installCompiledValidatorMap(${o.get(l.filePath)??""}.${l.exportName}.args, ${f});`}).filter(l=>l!==void 0).join(`
331
331
  `);return{dispatchBody:y.length>0?`
332
332
  ${y}
333
333
  `:"",importBlock:i.length>0?`${i}
@@ -336,7 +336,7 @@ ${y}
336
336
  ${c}
337
337
  `:"",mutatorPaths:h,shapeBody:p.length>0?`
338
338
  ${p}
339
- `:""}},Zn=e=>{const t=Qe(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=D(ke(a.args),a.filePath),d=c==="{}"?"?":"",p=D(a.returnType,a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
339
+ `:""}},Zn=e=>{const t=Qe(e),n=t.map(([o,s])=>{const i=s.map(a=>{const c=D(ke(a.args),a.filePath),d=c==="{}"?"?":"",p=D(yt(a),a.filePath);return a.kind==="stream"?` ${a.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${p}>>;`:` ${a.exportName}: (args${d}: ${c}) => Promise<${p}>;`}).join(`
340
340
  `);return` ${E(N(o))}: {
341
341
  ${i}
342
342
  };`}).join(`
@@ -377,7 +377,7 @@ ${L}`:""}
377
377
  }
378
378
 
379
379
  /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
380
- export type Env = CloudflareBindings;`,j=(m,Me)=>Me?kn.get(m)?.field??"":"",ie=j("kv",p),le=j("analytics",s),Se=j("hyperdrive",c),Ne=j("browser",i),Te=j("images",d),ce=j("pipelines",u),V=j("r2sql",l),P=(x?.vectorIndexes.length??0)>0,H=P?' | "vectors"':"",Z=P?`
380
+ export type Env = CloudflareBindings;`,j=(m,Me)=>Me?wn.get(m)?.field??"":"",ie=j("kv",p),le=j("analytics",s),Se=j("hyperdrive",c),Ne=j("browser",i),Te=j("images",d),ce=j("pipelines",u),V=j("r2sql",l),P=(x?.vectorIndexes.length??0)>0,H=P?' | "vectors"':"",Z=P?`
381
381
  readonly vectors: VectorSearch<VectorIndexName>;`:"",de=P?`
382
382
  readonly vectors: VectorSearchReader<VectorIndexName>;`:"",J=P?`import type { VectorSearch, VectorSearchReader } from "${v.server}";
383
383
  import type { VectorIndexName } from "./dataModel.js";
@@ -1146,14 +1146,14 @@ ${t}
1146
1146
  const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
1147
1147
  ${t}
1148
1148
  ];
1149
- `}},bt=(e,t,n,r,o)=>({constant:`
1149
+ `}},kt=(e,t,n,r,o)=>({constant:`
1150
1150
  ${o}
1151
1151
  const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1152
1152
  `,override:`
1153
1153
  protected override ${n}(): ${t} {
1154
1154
  return ${e};
1155
1155
  }
1156
- `}),Tr=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return bt("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Ar=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return bt("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Or=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
1156
+ `}),Tr=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({binding:n.bindingName,className:n.className,exportName:n.exportName,name:n.name}))};return kt("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Ar=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return kt("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},Or=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
1157
1157
  const payments: LunoraPayment = config.payment
1158
1158
  ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
1159
1159
  : paymentStub;
@@ -1164,10 +1164,10 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1164
1164
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1165
1165
  : x402Stub;
1166
1166
  `,configField:`
1167
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:O("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Cr=(e,t,n,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],ro=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:h=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:w=!1,hasR2sql:$=!1,hasX402:x=!1,maskMetadata:I,mutators:T=[],queues:_=[],rlsMetadata:v,schema:k,schemaSnapshot:M,shapes:oe=[],storageRules:B,studioFeatures:ae,useUmbrella:se=!1,workflows:W=[]})=>{const C=ne(se),X=T.length>0,L=oe.length>0,R=M===void 0?"":fn(M),j=M===void 0?"":`
1167
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:O("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Cr=(e,t,n,r)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult",...n?["QueuesResult"]:[],"RunShardApplyCdcArgs","RunShardExportArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike","TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],ro=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:s=[],hasAccessFacade:i=!1,hasAi:a=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:p=!1,hasHyperdrive:h=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:f=!1,hasPipelines:w=!1,hasR2sql:$=!1,hasX402:x=!1,maskMetadata:I,mutators:T=[],queues:_=[],rlsMetadata:v,schema:k,schemaSnapshot:M,shapes:oe=[],storageRules:B,studioFeatures:ae,useUmbrella:se=!1,workflows:W=[]})=>{const C=ne(se),X=T.length>0,L=oe.length>0,R=M===void 0?"":yn(M),j=M===void 0?"":`
1168
1168
  /** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
1169
- const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(yn(M))}, json: ${JSON.stringify(R)} };
1170
- `,ie=M===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:Se,contextField:Ne,stub:Te}=dr(a),ce=gr(i),V=ur(u),P=pr(p,C.flags),H=fr(s,p,C.flags),Z=mr(l),de=hr(o),J=yr(c),U=br(y),K=kr(h),Q=wr(d),q=xr($),ee=vr(w),{build:Ae,contextField:we,importLines:xe,specs:ue}=Sr(_),{build:Oe,contextField:Ie,importLines:ve,specs:pe}=$r(r,k.jurisdiction),{build:Ce,contextField:Le,importLines:$e,specs:_e}=Rr(W),{build:Ee,contextField:me,importLines:he,specs:De}=Nr(n),{build:Fe,configField:Pe,contextField:ge,imports:fe,stub:He}=Or(f),{build:m,configField:Me,imports:wt,stub:xt}=Ir(x),vt=e,$t=t,Rt=v??{policies:[],roles:[]},St=I??{columns:[]},Nt=B??{rules:[]},Tt=ae??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:At,override:Ot}=Tr(W),{constant:It,override:Ct}=Ar(_),G=k.vectorIndexes.length>0,Je=new Set(k.tables.filter(b=>typeof b.shardMode=="object"&&b.shardMode.kind==="shardBy").map(b=>b.name)),Re=k.vectorIndexes.some(b=>Je.has(b.table)),ye=k.tables.some(b=>b.shardMode==="global"),Be=k.tables.some(b=>b.shardMode==="global"&&b.globalBackend==="hyperdrive"),Ge=k.tables.some(b=>b.shardMode==="global"&&b.globalBackend!=="hyperdrive"),z=k.tables.some(b=>b.externalSource!==void 0),ze=k.tables.some(b=>b.memory===!0);if(Ge&&Be)throw new te("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const je=k.tables.length>0,Lt=nr(k),_t=or(k),Et=lr(k),Dt=rr(k),Ye=ar(k),Xe=Cr(G,W.length>0,_.length>0,p);L&&Xe.push("WhereInput");const Ze=cr(ye),Ft=L?`
1169
+ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(bn(M))}, json: ${JSON.stringify(R)} };
1170
+ `,ie=M===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:le,configField:Se,contextField:Ne,stub:Te}=dr(a),ce=gr(i),V=ur(u),P=pr(p,C.flags),H=fr(s,p,C.flags),Z=mr(l),de=hr(o),J=yr(c),U=br(y),K=kr(h),Q=wr(d),q=xr($),ee=vr(w),{build:Ae,contextField:we,importLines:xe,specs:ue}=Sr(_),{build:Oe,contextField:Ie,importLines:ve,specs:pe}=$r(r,k.jurisdiction),{build:Ce,contextField:Le,importLines:$e,specs:_e}=Rr(W),{build:Ee,contextField:me,importLines:he,specs:De}=Nr(n),{build:Fe,configField:Pe,contextField:ge,imports:fe,stub:He}=Or(f),{build:m,configField:Me,imports:xt,stub:vt}=Ir(x),$t=e,Rt=t,St=v??{policies:[],roles:[]},Nt=I??{columns:[]},Tt=B??{rules:[]},At=ae??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Ot,override:It}=Tr(W),{constant:Ct,override:Lt}=Ar(_),G=k.vectorIndexes.length>0,Je=new Set(k.tables.filter(b=>typeof b.shardMode=="object"&&b.shardMode.kind==="shardBy").map(b=>b.name)),Re=k.vectorIndexes.some(b=>Je.has(b.table)),ye=k.tables.some(b=>b.shardMode==="global"),Be=k.tables.some(b=>b.shardMode==="global"&&b.globalBackend==="hyperdrive"),Ge=k.tables.some(b=>b.shardMode==="global"&&b.globalBackend!=="hyperdrive"),z=k.tables.some(b=>b.externalSource!==void 0),ze=k.tables.some(b=>b.memory===!0);if(Ge&&Be)throw new te("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const je=k.tables.length>0,_t=nr(k),Et=or(k),Dt=lr(k),Ft=rr(k),Ye=ar(k),Xe=Cr(G,W.length>0,_.length>0,p);L&&Xe.push("WhereInput");const Ze=cr(ye),Pt=L?`
1171
1171
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: { identity?: Record<string, unknown>; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
1172
1172
  const shape = LUNORA_SHAPES[name];
1173
1173
 
@@ -1220,30 +1220,30 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1220
1220
 
1221
1221
  return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
1222
1222
  }
1223
- `:"",Pt=X?`
1223
+ `:"",Mt=X?`
1224
1224
  protected override isCustomMutator(functionPath: string): boolean {
1225
1225
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1226
1226
  }
1227
- `:"",Mt=L?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",Bt=L?"assertShapeShardable, ":"",be=[`import type { ${Xe.join(", ")} } from "${C.do}";`,`import { applyCdcChanges, buildReprojectionMigration, ${ze?"clearMemoryTables, ":""}${Bt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${z?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${Re?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Ze.importFragment}ShardDO as ShardDOBase } from "${C.do}";`,...z?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${C.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${C.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${C.server}";`];je&&be.push(`import { bindOrm, bindTableFacade } from "${C.server}";`),G&&be.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&be.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),be.push(...ce.importLines,...V.importLines,...P.importLines,...Z.importLines,...de.importLines,...J.importLines,...U.importLines,...K.importLines,...Q.importLines,...q.importLines,...ee.importLines,...ve,...$e,...xe,...he,...fe,...wt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...X?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const jt=G?`
1228
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",qt=Ge?`
1229
- d1?: (env: Record<string, unknown>, request?: { bookmark?: string; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Wt=Be?`
1230
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ut=z?`
1231
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Kt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Qt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Vt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Ht='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Jt=ye?O("globalDbStub: DatabaseWriterLike",Kt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",Gt=G?O("vectorsStub: VectorSearchLike",Qt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",zt=Re?`
1227
+ `:"",Bt=L?"\n/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */\nconst LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS));\n":"",jt=L?"assertShapeShardable, ":"",be=[`import type { ${Xe.join(", ")} } from "${C.do}";`,`import { applyCdcChanges, buildReprojectionMigration, ${ze?"clearMemoryTables, ":""}${jt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${z?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}${Re?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Ze.importFragment}ShardDO as ShardDOBase } from "${C.do}";`,...z?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${C.do}";`]:[],L?`import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "${C.server}";`:`import { asBucketStorage, createSecrets, LunoraError } from "${C.server}";`];je&&be.push(`import { bindOrm, bindTableFacade } from "${C.server}";`),G&&be.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),a&&be.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),be.push(...ce.importLines,...V.importLines,...P.importLines,...Z.importLines,...de.importLines,...J.importLines,...U.importLines,...K.importLines,...Q.importLines,...q.importLines,...ee.importLines,...ve,...$e,...xe,...he,...fe,...xt,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...X?["LUNORA_MUTATOR_PATHS"]:[],...L?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const qt=G?`
1228
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Wt=Ge?`
1229
+ d1?: (env: Record<string, unknown>, request?: { bookmark?: string; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Ut=Be?`
1230
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Kt=z?`
1231
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Qt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Vt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Ht='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Jt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',Gt=ye?O("globalDbStub: DatabaseWriterLike",Qt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",zt=G?O("vectorsStub: VectorSearchLike",Vt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",Yt=Re?`
1232
1232
  const vectorShardKey = this.currentShardKey();
1233
- `:"",Yt=Re?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",Xt=Re?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${k.vectorIndexes.filter(b=>Je.has(b.table)).map(b=>JSON.stringify(b.name)).join(", ")}] }`:"",Zt=G?`
1233
+ `:"",Xt=Re?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",Zt=Re?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${k.vectorIndexes.filter(b=>Je.has(b.table)).map(b=>JSON.stringify(b.name)).join(", ")}] }`:"",en=G?`
1234
1234
  let vectors: VectorSearchLike;
1235
1235
  let onWrite: WriteHook | undefined;
1236
1236
 
1237
1237
  if (config.vectors) {
1238
1238
  const lunora = createVectors({ indexes: config.vectors(env) });
1239
- ${zt}
1240
- vectors = createContextVectors(lunora${Xt});
1241
- onWrite = createVectorSyncHook({ ${Yt}schema: schema as unknown as VectorSchemaLike, vectors });
1239
+ ${Yt}
1240
+ vectors = createContextVectors(lunora${Zt});
1241
+ onWrite = createVectorSyncHook({ ${Xt}schema: schema as unknown as VectorSchemaLike, vectors });
1242
1242
  } else {
1243
1243
  vectors = vectorsStub;
1244
1244
  onWrite = undefined;
1245
1245
  }
1246
- `:"",en=`{
1246
+ `:"",tn=`{
1247
1247
  auth: { identity: identity ?? null, userId: userId ?? null },
1248
1248
  broadcast: (delta) => {
1249
1249
  this.recordChangedTable(delta.table, delta.indexKeys);
@@ -1284,11 +1284,11 @@ ${zt}
1284
1284
  scheduler,
1285
1285
  schema: schema as unknown as SchemaLike,
1286
1286
  sql: this.sql as SqlExec,
1287
- });`,tn=G?`
1288
- vectors,`:"",nn=je?`
1289
- orm: bindOrm(facade),`:"",et=Be?"config.hyperdriveGlobal":"config.d1",rn=ye?` const globalRequest = { bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
1287
+ });`,nn=G?`
1288
+ vectors,`:"",rn=je?`
1289
+ orm: bindOrm(facade),`:"",et=Be?"config.hyperdriveGlobal":"config.d1",on=ye?` const globalRequest = { bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { this.setOutboundBookmark(bookmarkValue); }, userId };
1290
1290
  const globalDb: DatabaseWriterLike = ${et}?.(env, globalRequest) ?? globalDbStub;
1291
- `:"",on=L&&ye?`
1291
+ `:"",an=L&&ye?`
1292
1292
  protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: { identity?: Record<string, unknown>; userId?: string }): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
1293
1293
  const env = this.env as Record<string, unknown>;
1294
1294
  // A shape read performs no writes, so the widened request only needs
@@ -1322,17 +1322,17 @@ ${zt}
1322
1322
 
1323
1323
  return rows;
1324
1324
  }
1325
- `:"",an=z?`
1325
+ `:"",sn=z?`
1326
1326
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1327
1327
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1328
- `:"",sn=`
1328
+ `:"",ln=`
1329
1329
  protected override async runShardInit(): Promise<void> {
1330
1330
  this.ensureMigrated();
1331
1331
  ${ze?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1332
1332
  `:""}
1333
1333
  await this.dispatchShardInit();
1334
1334
  }
1335
- `,ln=z?`
1335
+ `,cn=z?`
1336
1336
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1337
1337
  const env = (this.env ?? {}) as Record<string, unknown>;
1338
1338
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1467,7 +1467,7 @@ ${ze?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1467
1467
 
1468
1468
  return nextDueAt;
1469
1469
  }
1470
- `:"",tt=Ye.length>0,cn=z||tt?`
1470
+ `:"",tt=Ye.length>0,dn=z||tt?`
1471
1471
  public constructor(state: ShardDOState, env: unknown) {
1472
1472
  super(state, env);
1473
1473
  ${z?`
@@ -1485,21 +1485,21 @@ ${z?`
1485
1485
  void this.scheduleTtlSweep();
1486
1486
  }
1487
1487
  `:""} }
1488
- `:"",dn=je?`
1488
+ `:"",un=je?`
1489
1489
  const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
1490
1490
  ${k.tables.map(b=>` facade[${JSON.stringify(b.name)}] = bindTableFacade(db, ${JSON.stringify(b.name)});`).join(`
1491
1491
  `)}
1492
- `:"",un=`${ce.build}${V.build}${P.build}${J.build}${de.build}
1492
+ `:"",pn=`${ce.build}${V.build}${P.build}${J.build}${de.build}
1493
1493
  const secrets = createSecrets(env);
1494
- `,pn=`${ce.contextField}${V.contextField}${P.contextField}${Z.contextField}${J.contextField}${de.contextField}
1495
- secrets,`,mn=Z.build,nt=y||h||d||$||w||x,hn=nt?`
1494
+ `,mn=`${ce.contextField}${V.contextField}${P.contextField}${Z.contextField}${J.contextField}${de.contextField}
1495
+ secrets,`,hn=Z.build,nt=y||h||d||$||w||x,gn=nt?`
1496
1496
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
1497
1497
  // and attached only for an \`action\` so query/mutation ctx never carry them.
1498
1498
  if (isAction) {
1499
1499
  ${U.build}${K.build}${Q.build}${q.build}${ee.build}${m}${[...y?[" ctx.images = images;"]:[],...h?[" ctx.sql = sql;"]:[],...d?[" ctx.browser = browser;"]:[],...$?[" ctx.r2sql = r2sql;"]:[],...w?[" ctx.pipelines = pipelines;"]:[],...x?[" ctx.x402 = x402;"]:[]].join(`
1500
1500
  `)}
1501
1501
  }
1502
- `:"",gn=nt?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1502
+ `:"",fn=nt?` const isAction = LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind === "action";
1503
1503
  `:"";return`${S}${be.join(`
1504
1504
  `)}
1505
1505
 
@@ -1510,50 +1510,50 @@ interface FunctionReference {
1510
1510
  }
1511
1511
 
1512
1512
  /** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
1513
- const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(Lt,void 0,4)};
1513
+ const LUNORA_TABLE_REFS: Record<string, Record<string, string>> = ${JSON.stringify(_t,void 0,4)};
1514
1514
 
1515
1515
  /** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
1516
- const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(_t,void 0,4)};
1516
+ const LUNORA_TABLE_INDEXES: Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>> = ${JSON.stringify(Et,void 0,4)};
1517
1517
 
1518
1518
  /** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
1519
1519
  const LUNORA_TABLE_COLUMNS: Record<
1520
1520
  string,
1521
1521
  Array<{ bucket?: string; enumValues?: string[]; isStorage?: boolean; name: string; nullable?: boolean; optional: boolean; pk?: boolean; ref?: string; type: string }>
1522
- > = ${JSON.stringify(Et,void 0,4)};
1522
+ > = ${JSON.stringify(Dt,void 0,4)};
1523
1523
 
1524
1524
  /** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
1525
- const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(Dt,void 0,4)};
1525
+ const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(Ft,void 0,4)};
1526
1526
 
1527
1527
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1528
1528
  const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(Ye,void 0,4)};
1529
1529
 
1530
1530
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1531
- const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(vt,void 0,4)};
1531
+ const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify($t,void 0,4)};
1532
1532
 
1533
1533
  /** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
1534
- const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify($t,void 0,4)};
1534
+ const LUNORA_ADVISOR_PROCEDURES: AdvisorProcedure[] = ${JSON.stringify(Rt,void 0,4)};
1535
1535
 
1536
1536
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1537
- const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(Rt,void 0,4)};
1537
+ const LUNORA_RLS_METADATA: RlsPoliciesResult = ${JSON.stringify(St,void 0,4)};
1538
1538
 
1539
1539
  /** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
1540
- const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(St,void 0,4)};
1540
+ const LUNORA_MASK_METADATA: MaskPoliciesResult = ${JSON.stringify(Nt,void 0,4)};
1541
1541
 
1542
1542
  /** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
1543
- const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Nt,void 0,4)};
1543
+ const LUNORA_STORAGE_RULES: StorageRulesResult = ${JSON.stringify(Tt,void 0,4)};
1544
1544
 
1545
1545
  /** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
1546
- const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(Tt,void 0,4)};
1547
- ${j}${H.constant}${Mt}${At}${It}${pe}${_e}${ue}${De}
1546
+ const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = ${JSON.stringify(At,void 0,4)};
1547
+ ${j}${H.constant}${Bt}${Ot}${Ct}${pe}${_e}${ue}${De}
1548
1548
  export interface ShardDOConfig {
1549
1549
  /** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
1550
1550
  cdc?: boolean;
1551
1551
  /** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
1552
1552
  observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
1553
1553
  scheduler?: (env: Record<string, unknown>) => unknown;
1554
- storage?: (env: Record<string, unknown>) => unknown;${jt}${Se}${V.configField}${P.configField}${J.configField}${U.configField}${K.configField}${Q.configField}${q.configField}${ee.configField}${Pe}${Me}${qt}${Wt}${Ut}
1554
+ storage?: (env: Record<string, unknown>) => unknown;${qt}${Se}${V.configField}${P.configField}${J.configField}${U.configField}${K.configField}${Q.configField}${q.configField}${ee.configField}${Pe}${Me}${Wt}${Ut}${Kt}
1555
1555
  }
1556
- ${O("schedulerStub",Vt,["cancel","runAfter","runAt"])}${O("storageStub",Ht,["delete","download","getMetadata","getSignedUrl","getUrl","list","upload"],{sync:["getUrl"]})}${Jt}${an}${Gt}${Te}${V.stub}${P.stub}${J.stub}${U.stub}${K.stub}${Q.stub}${q.stub}${ee.stub}${He}${xt}
1556
+ ${O("schedulerStub",Ht,["cancel","runAfter","runAt"])}${O("storageStub",Jt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${Gt}${sn}${zt}${Te}${V.stub}${P.stub}${J.stub}${U.stub}${K.stub}${Q.stub}${q.stub}${ee.stub}${He}${vt}
1557
1557
  // Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
1558
1558
  // referencing call fails loudly with a clear error instead of overflowing the
1559
1559
  // stack. Tracked across the awaited handler chain (one DO invocation is
@@ -1590,7 +1590,7 @@ const dispatchRun = async (expected: FunctionKind, functionPath: string, args: R
1590
1590
  * from the worker entry so wrangler binds it by name.
1591
1591
  */
1592
1592
  export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
1593
- class extends ShardDOBase {${cn}
1593
+ class extends ShardDOBase {${dn}
1594
1594
  private migrated = false;
1595
1595
 
1596
1596
  public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker): Promise<unknown> {
@@ -1684,11 +1684,11 @@ ${Ze.override}
1684
1684
  iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath }), args, signal),
1685
1685
  };
1686
1686
  }
1687
- ${Pt}${Ft}${on}${ln}
1687
+ ${Mt}${Pt}${an}${cn}
1688
1688
  protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor"): readonly string[] {
1689
1689
  return LUNORA_LIFECYCLE_HOOKS[event];
1690
1690
  }
1691
- ${sn}
1691
+ ${ln}
1692
1692
  // One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
1693
1693
  // socket-terminated half of the same reactivity — and differs only in who
1694
1694
  // consumes the result: the base's \`dispatchReactors\` stores the digest as
@@ -1763,7 +1763,7 @@ ${sn}
1763
1763
  protected override studioFeatures(): StudioFeaturesResult {
1764
1764
  return LUNORA_STUDIO_FEATURES;
1765
1765
  }
1766
- ${H.evaluateOverride}${H.subscriptionOverride}${Ot}${Ct}
1766
+ ${H.evaluateOverride}${H.subscriptionOverride}${It}${Lt}
1767
1767
  protected override advisories(): AdvisoryFinding[] {
1768
1768
  return LUNORA_ADVISORIES;
1769
1769
  }
@@ -1996,7 +1996,7 @@ ${Y}
1996
1996
  // dispatch path) fall back to the per-request fields as before.
1997
1997
  const userId = options.identity ? options.identity.userId : this.getCurrentUserId();
1998
1998
  const identity = options.identity ? options.identity.identity : this.getCurrentIdentity();
1999
- ${Zt}${le}${un}${Oe}${Ce}${Ae}${Ee}
1999
+ ${en}${le}${pn}${Oe}${Ce}${Ae}${Ee}
2000
2000
  const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
2001
2001
  // Build the storage adapter once and share it between \`ctx.storage\`
2002
2002
  // and \`ctx.db.system._storage\` so both read the same R2 binding. The
@@ -2023,13 +2023,13 @@ ${Zt}${le}${un}${Oe}${Ce}${Ae}${Ee}
2023
2023
  // so both write to the same trace.
2024
2024
  const span = this.makeDispatchSpan(traceAnchor, observability);
2025
2025
 
2026
- ${rn} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
2026
+ ${on} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
2027
2027
  // adds aggregate counters (call count, total time, per-operation
2028
2028
  // breakdown) to the wide event rather than a span per call, so a
2029
2029
  // handler making hundreds of queries stays readable. See
2030
2030
  // \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
2031
- const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${en}), logFunctionPath, traceAnchor, observability);
2032
- ${dn}${Fe}
2031
+ const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${tn}), logFunctionPath, traceAnchor, observability);
2032
+ ${un}${Fe}
2033
2033
 
2034
2034
  // \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
2035
2035
  // The trace anchor is threaded explicitly for the same reason \`identity\`
@@ -2037,7 +2037,7 @@ ${dn}${Fe}
2037
2037
  // writing mutation's trace from the shared per-request field.
2038
2038
  const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
2039
2039
  const metrics = this.makeMetrics(logFunctionPath, observability);
2040
- ${mn}
2040
+ ${hn}
2041
2041
  // \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
2042
2042
  // captured ONCE so the whole handler body sees a single stable value.
2043
2043
  // Query/mutation handlers must be deterministic (they may be re-run on
@@ -2060,13 +2060,13 @@ ${mn}
2060
2060
  ip: this.getCurrentIp(),
2061
2061
  log,
2062
2062
  metrics,
2063
- now,${nn}
2063
+ now,${rn}
2064
2064
  scheduler,
2065
2065
  span,
2066
2066
  storage,
2067
- trace,${tn}${Ne}${pn}${ge}${Ie}${Le}${we}${me}
2067
+ trace,${nn}${Ne}${mn}${ge}${Ie}${Le}${we}${me}
2068
2068
  };
2069
- ${gn}${hn}
2069
+ ${fn}${gn}
2070
2070
  ctx.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx);
2071
2071
  ctx.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx);
2072
2072
  // \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
@@ -2092,13 +2092,13 @@ ${gn}${hn}
2092
2092
  return ctx;
2093
2093
  }
2094
2094
  };
2095
- `},Ve=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:A(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:A(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Ve(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},kt=(e,t)=>{const n=re(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Lr=(e,t,n)=>{g(e,"drizzle column name");const r=Ve(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=kt(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},_r=e=>{g(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(g(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},Er=(e,t)=>{g(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,s])=>` ${o}: ${Lr(o,s,t)},`)].join(`
2095
+ `},Ve=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:A(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:A(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Ve(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},wt=(e,t)=>{const n=re(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Lr=(e,t,n)=>{g(e,"drizzle column name");const r=Ve(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let s=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(s+=`.$type<${r.typeAnnotation}>()`);const i=wt(t,n);return i!==void 0&&(s+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(s+=".notNull()"),s},_r=e=>{g(e.name,"drizzle index name");const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(g(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${e.name}: ${t}("${e.name}").on(${n}),`},Er=(e,t)=>{g(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,s])=>` ${o}: ${Lr(o,s,t)},`)].join(`
2096
2096
  `),r=e.indexes.length>0?`, (t) => ({
2097
2097
  ${e.indexes.map(o=>_r(o)).join(`
2098
2098
  `)}
2099
2099
  })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
2100
2100
  ${n}
2101
- }${r});`},Dr=e=>e.typeAnnotation?.includes('Id<"')??!1,Fr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Ve(a);n.add(c.builder),s=s||Dr(c),o=o||kt(a,t)!==void 0}for(const a of i.indexes)r.add(a.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,a)=>i.localeCompare(a)),indexes:[...r].toSorted((i,a)=>i.localeCompare(a)),needsAnyColumn:o,needsId:s}},ot=(e,t=!1)=>{if(e.length===0)return`${S}export {};
2101
+ }${r});`},Dr=e=>e.typeAnnotation?.includes('Id<"')??!1,Fr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,s=!1;for(const i of e){for(const a of Object.values(i.shape)){const c=Ve(a);n.add(c.builder),s=s||Dr(c),o=o||wt(a,t)!==void 0}for(const a of i.indexes)r.add(a.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,a)=>i.localeCompare(a)),indexes:[...r].toSorted((i,a)=>i.localeCompare(a)),needsAnyColumn:o,needsId:s}},ot=(e,t=!1)=>{if(e.length===0)return`${S}export {};
2102
2102
  `;const n=ne(t),r=new Set(e.map(h=>h.name)),{columns:o,indexes:s,needsAnyColumn:i,needsId:a}=Fr(e,r),c=[...s,...o].toSorted((h,y)=>h.localeCompare(y)),d=e.map(h=>Er(h,r)).join(`
2103
2103
 
2104
2104
  `),p=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
@@ -2164,4 +2164,4 @@ export interface LunoraVectorIndex {
2164
2164
  * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2165
2165
  */
2166
2166
  export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
2167
- `},io=e=>[...new Set(e.map(t=>t.cron))];export{Vr as A,bn as C,S as G,Mn as U,Jr as a,zr as b,Zr as c,ao as d,to as e,Hr as f,oo as g,Xr as h,Yr as i,ro as j,so as k,eo as l,io as m,rr as n,no as o,Gr as p};
2167
+ `},io=e=>[...new Set(e.map(t=>t.cron))];export{Vr as A,kn as C,S as G,Bn as U,Jr as a,zr as b,Zr as c,ao as d,to as e,Hr as f,oo as g,Xr as h,Yr as i,ro as j,so as k,eo as l,io as m,rr as n,no as o,Gr as p};
@@ -1,4 +1,4 @@
1
- import{A as S,G as D}from"./emit-CW4ceRjr.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),g=e=>v.some(([t])=>e[t]),A=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";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");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),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(l),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...m].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},I=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. */
1
+ import{A as S,G as D}from"./emit-BlC5DV56.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),g=e=>v.some(([t])=>e[t]),A=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";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");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),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(l),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...m].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},I=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. */
2
2
  interface StorageDeclaration<Env> {
3
3
  /** The default R2 bucket binding (the bare \`ctx.storage\`). */
4
4
  bucket: Selector<Env, R2BucketLike>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.121",
3
+ "version": "1.0.0-alpha.123",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.86",
50
- "@lunora/agent": "1.0.0-alpha.61",
49
+ "@lunora/advisor": "1.0.0-alpha.87",
50
+ "@lunora/agent": "1.0.0-alpha.62",
51
51
  "@lunora/container": "1.0.0-alpha.33",
52
52
  "@lunora/errors": "1.0.0-alpha.22",
53
- "@lunora/platform": "1.0.0-alpha.16",
54
- "@lunora/queue": "1.0.0-alpha.32",
55
- "@lunora/scheduler": "1.0.0-alpha.36",
53
+ "@lunora/platform": "1.0.0-alpha.17",
54
+ "@lunora/queue": "1.0.0-alpha.33",
55
+ "@lunora/scheduler": "1.0.0-alpha.37",
56
56
  "@lunora/values": "1.0.0-alpha.27",
57
57
  "@lunora/workflow": "1.0.0-alpha.31",
58
58
  "jsonc-parser": "^3.3.1",
@@ -1,3 +0,0 @@
1
- import{G as S}from"./emit-CW4ceRjr.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
2
- `,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
- `;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
@@ -1 +0,0 @@
1
- import{Node as s,SyntaxKind as O}from"ts-morph";import{l as w,a as k}from"./discover-ast-D33zP-NZ.mjs";import{a as z}from"./module-specifiers-WF8iAydP.mjs";import{p as _,a as b}from"./parse-validator-C5ycrhR3.mjs";import{s as R}from"./paths-C-9fwEgQ.mjs";const y=new Set(["action","mutation","query","stream"]),P=/\bany\b(?!\s*(?:\?\s*)?:)/u,T=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,U=/^[A-Za-z_$][\w$]*$/u,j=e=>U.test(e)?e:JSON.stringify(e),N={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},$={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init"},V=z,h=e=>{const t=e.getSymbol();if(!t)return e.getText();const r=t.getDeclarations();for(const i of r){if(!s.isImportSpecifier(i))continue;const o=i.getImportDeclaration().getModuleSpecifierValue();return V(o)?i.getNameNode().getText():void 0}},S=(e,t=!1)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))return;r=n.getExpression()}if(!s.isIdentifier(r))return;const i=h(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?S(o,!0):void 0}return}return y.has(i)?"public":N[i]?"internal":void 0},m=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isStringLiteral(i)?i.getLiteralValue():void 0},E=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isNumericLiteral(i)?i.getLiteralValue():void 0},M=e=>{const t=e.getProperty("cache");if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();if(r===void 0||!s.isObjectLiteralExpression(r))return;const i=m(r,"scope"),n=E(r,"maxAge"),o=E(r,"staleWhileRevalidate"),a=m(r,"tag"),c=m(r,"vary"),l={...n===void 0?{}:{maxAge:n},...i==="private"||i==="public"?{scope:i}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},B=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const t=M(e),r=e.getProperty("rest");return r!==void 0&&s.isPropertyAssignment(r)?{...t===void 0?{}:{cache:t},rest:r.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},K=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="expose")return B(t.getArguments()[0]);t=r.getExpression()}},H=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const r=t.getProperty("args");if(!r||!s.isPropertyAssignment(r))return{};const i=r.getInitializer();return!i||!s.isObjectLiteralExpression(i)?{}:b(i)},G="/_generated/",q=(e,t,r)=>{const i=t.getSourceFile(),n=(a,c)=>i.getImportDeclarations().some(l=>l.getModuleSpecifierSourceFile()!==a?!1:l.getNamespaceImport()!==void 0||l.getNamedImports().some(f=>f.getName()===c)),o=a=>{const c=a.getSourceFile();if(c.isInNodeModules()||c.isDeclarationFile()||!s.isInterfaceDeclaration(a)&&!s.isTypeAliasDeclaration(a))return!1;const l=c.getFilePath();return l.includes(G)?!1:l===r||n(c,a.getName())};return[e.getSymbol(),e.getAliasSymbol()].flatMap(a=>a?.getDeclarations()??[]).some(a=>o(a))},Q=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},I=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,g=(e,t,r,i=new Set)=>i.has(e)?!1:(i.add(e),q(e,t,r)||Q(e).some(n=>g(n,t,r,i))?!0:I(e)?e.getProperties().some(n=>g(n.getTypeAtLocation(t),t,r,i)):!1),W=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(s.isPropertySignature(r)||s.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(i=>i.isUndefined())},X=8,Y=(e,t,r,i,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,r,i,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},J=(e,t,r,i,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,r,i,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},Z=(e,t,r,i,n,o)=>{if(!I(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),f=W(c,l),L=f&&l.isUnion()?l.getUnionTypes().filter(d=>!d.isUndefined()):[l],v=[];for(const d of L){const x=o(d,t,r,i+1,n);if(x===void 0)return;v.push(x)}a.push(`${j(c.getName())}${f?"?":""}: ${v.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},p=(e,t,r,i,n)=>{if(i>X||n.has(e))return;if(!g(e,t,r))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?Y(e,t,r,i,o,p):e.isUnion()?J(e,t,r,i,o,p):Z(e,t,r,i,o,p)},C=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const n=(r.getSymbol()??r.getAliasSymbol())?.getName();if(n==="Promise"||n==="AsyncIterable"||n==="AsyncIterableIterator"||n==="AsyncGenerator"){const c=r.getTypeArguments()[0];c&&(r=c)}const o=r.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return"unknown";const a=e.getSourceFile().getFilePath();return g(r,e,a)?p(r,e,a,0,new Set)??"unknown":o},ve=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const r=t.getTypeAtLocation(e).getProperty("types");if(!r)return;const i=r.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!i)return;const n=i.getTypeAtLocation(e),o=n.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return;const a=e.getSourceFile().getFilePath();return g(n,e,a)?p(n,e,a,0,new Set):o},ee=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const r=t.getProperty("handler");if(!r||!s.isPropertyAssignment(r))return"unknown";const i=r.getInitializer();return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":C(i)},te=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":C(t)},re=e=>{let t={},r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...b(n),...t})}r=i.getExpression()}return t},ie=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="output"){const i=t.getArguments()[0];return i&&s.isExpression(i)?_(i):void 0}t=r.getExpression()}},ne=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!y.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=S(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const r=h(t);if(!r)return;if(y.has(r))return{kind:r,visibility:"public"};const i=N[r];if(i)return{kind:i,visibility:"internal"};const n=$[r];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},A=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,xe=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",Ee=e=>{const t=e.getArguments()[0],r=A(t);if(r!==void 0)return r;if(t===void 0||!s.isObjectLiteralExpression(t))return;const i=t.getProperty("handler");return i!==void 0&&s.isPropertyAssignment(i)?A(i.getInitializer()):void 0},se=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ae=(e,t)=>{let r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()===t)return!0;r=i.getExpression()}return!1},be=(e,t,r)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=i.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&se(o.getExpression())===r)return!0;i=n.getExpression()}return!1},oe=e=>{const t=ne(e);if(t){if(t.receiver){const r=K(t.receiver),i=ie(t.receiver);return{args:re(t.receiver),...r?{expose:r}:{},kind:t.kind,...i?{output:i}:{},returnType:te(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:H(e),kind:t.kind,returnType:ee(e),visibility:t.visibility}}},ae=8,u=(e,t=0)=>{if(t>ae)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const r=e.getSymbol()?.getValueDeclaration();return r?F(r,t+1):void 0},F=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const r=e.getInitializer();return r?u(r,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const r=e.getPropertyNameNode()?.getText()??e.getName(),o=e.getFirstAncestorByKind(O.VariableDeclaration)?.getInitializer()?.getType().getProperty(r)?.getValueDeclaration();return o?F(o,t+1):void 0}},ce=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const r=e.getInitializer(),i=r&&(s.isCallExpression(r)?r:u(r));return i?[[e.getName(),i]]:[]},D=(e,t,r)=>{const i=oe(e);if(i)return{args:i.args,exportName:t,filePath:r,kind:i.kind,returnType:i.returnType,...i.output?{output:i.output}:{},visibility:i.visibility,...i.expose?{expose:i.expose}:{},...i.lifecycle?{lifecycle:i.lifecycle}:{}}},le=(e,t)=>{const r=[];for(const i of e.getExportAssignments()){if(i.isExportEquals())continue;const n=u(i.getExpression()),o=n?D(n,"default",t):void 0;o&&r.push(o)}return r},ue=(e,t)=>{const r=[];for(const i of e.getVariableStatements())if(i.isExported())for(const n of i.getDeclarations())for(const[o,a]of ce(n)){const c=D(a,o,t);c&&r.push(c)}return r.push(...le(e,t)),r},pe=e=>{const t=new Map;for(const r of e){const i=R(r.filePath),n=t.get(i);if(n&&n!==r.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${r.filePath}" both resolve to "${i}". 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:[n,r.filePath],status:500});t.set(i,r.filePath)}},Pe=(e,t)=>{const r=w(t),i=[];for(const n of r){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=k(t,n);i.push(...ue(o,a))}return i.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),pe(i),i};export{Ae as chainHasStep,be as chainUsesWrappedCall,ne as classifyProcedureCall,Pe as discoverFunctions,A as inlineHandler,xe as isDatabaseAccessor,w as listLunoraSourceFiles,k as lunoraRelativePath,Ee as procedureHandler,ve as resolveStandardSchemaType,C as unwrapHandlerReturn};