@lunora/codegen 1.0.0-alpha.396 → 1.0.0-alpha.397

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -3297,17 +3297,16 @@ interface SourceCapabilitySignals {
3297
3297
  */
3298
3298
  valueImports: ReadonlySet<string>;
3299
3299
  }
3300
+ declare const targetScopeBrand: unique symbol;
3300
3301
  /**
3301
3302
  * The targets one scan follows. A target is parsed at most once per scope, into a project per declaring project: adding it
3302
3303
  * to the declaring project would throw that program away. A target's own relative specifiers resolve with the declaring
3303
3304
  * project's options, so a barrel's next hop keeps its `rootDirs` and `moduleSuffixes`. A scope is made per scan, so an
3304
3305
  * edit between scans is seen and no file is re-read within one.
3305
3306
  */
3307
+ /** Opaque: callers only pass it back, so how targets are cached can change without a public API break. */
3306
3308
  interface TargetScope {
3307
- /** Each target project's declaring project, so a target's own hop can still see the declaring project's files. */
3308
- readonly origins: Map<Project, Project>;
3309
- /** The target project each declaring project resolves into. */
3310
- readonly projects: Map<Project, Project>;
3309
+ readonly [targetScopeBrand]: true;
3311
3310
  }
3312
3311
  /** A fresh scope for one scan: the targets it follows are parsed once and kept for that scan only. */
3313
3312
  declare const createTargetScope: () => TargetScope;
package/dist/index.d.ts CHANGED
@@ -3297,17 +3297,16 @@ interface SourceCapabilitySignals {
3297
3297
  */
3298
3298
  valueImports: ReadonlySet<string>;
3299
3299
  }
3300
+ declare const targetScopeBrand: unique symbol;
3300
3301
  /**
3301
3302
  * The targets one scan follows. A target is parsed at most once per scope, into a project per declaring project: adding it
3302
3303
  * to the declaring project would throw that program away. A target's own relative specifiers resolve with the declaring
3303
3304
  * project's options, so a barrel's next hop keeps its `rootDirs` and `moduleSuffixes`. A scope is made per scan, so an
3304
3305
  * edit between scans is seen and no file is re-read within one.
3305
3306
  */
3307
+ /** Opaque: callers only pass it back, so how targets are cached can change without a public API break. */
3306
3308
  interface TargetScope {
3307
- /** Each target project's declaring project, so a target's own hop can still see the declaring project's files. */
3308
- readonly origins: Map<Project, Project>;
3309
- /** The target project each declaring project resolves into. */
3310
- readonly projects: Map<Project, Project>;
3309
+ readonly [targetScopeBrand]: true;
3311
3310
  }
3312
3311
  /** A fresh scope for one scan: the targets it follows are parsed once and kept for that scan only. */
3313
3312
  declare const createTargetScope: () => TargetScope;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-BuNEmlCO.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BxpEvZgW.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-DrszPMtU.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-D-ZsZKvv.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as _}from"./packem_shared/CONTAINERS_FILENAME-CvPP3wR-.mjs";import{default as P}from"./packem_shared/discoverCrons-BT_qyOt8.mjs";import{capabilitiesUsedBy as y,createTargetScope as b,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-B8KULfAq.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-Ce1G6kZd.mjs";import{d as z}from"./packem_shared/index-DzO8JT7M.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-DOkHmHzy.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-BGhSZp00.mjs";import{default as J}from"./packem_shared/discoverInserts-d_zAWqc4.mjs";import{d as X}from"./packem_shared/index-VKPwR6Cj.mjs";import{default as $}from"./packem_shared/discoverMigrations-Dq-7Od3H.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-JBFlT9aD.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-CWLdAwUM.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-DLGxunzB.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-Bvh__ZjJ.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-2K8DSvbt.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-CexxhDRt.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-CDbsnndn.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-CugyqoLu.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CSt29RbS.mjs";import{default as he}from"./packem_shared/discoverSchema-DTgg8rAu.mjs";import{readServiceBindings as Ie,resolveServiceBindings as Le}from"./packem_shared/readServiceBindings-rDIqDBSW.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-DCqsIdQQ.mjs";import{default as ye}from"./packem_shared/discoverStorageRulesMetadata-DTXC-pY3.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{emitApp as je}from"./packem_shared/emitApp-D-fxbE34.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-KKQFkA_W.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-CLZ5Em9J.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-C0xI7Xqd.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir,readProjectLazyFunctions as sr}from"./packem_shared/loadProjectConfig-Dbux4jI3.mjs";import{PROJECT_CONFIG_FILENAMES as mr,findCodegenConfigFile as dr,findProjectConfigFile as pr,projectConfigCandidatePaths as nr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as lr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BRRkfu5-.mjs";import{SchemaSnapshotParseError as Er,buildSchemaSnapshot as ur,evaluateSchemaDrift as Ar,indexReferencesOf as vr,parseSchemaSnapshot as gr}from"./packem_shared/SchemaSnapshotParseError-DnAuFdpl.mjs";import{default as Nr}from"./packem_shared/fingerprintSchemaSources-Pmxw808S.mjs";import{schemaFromIr as Rr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as hr,validatorIrToJsonSchema as Fr}from"./packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{SDK_LANGUAGES as Lr,SDK_TARGETS as _r,generateSdk as Mr}from"./sdk/index.mjs";import{redact as Dr,secretKindOf as yr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Ur}from"./packem_shared/emitDrizzleSchema-Dszoyymv.mjs";import{e as Hr}from"./packem_shared/server-Box8pDwi.mjs";import{e as Br}from"./packem_shared/shard-DXVp_Iht.mjs";import{G as Wr}from"./packem_shared/shared-DhqnD5R3.mjs";import{MESSAGE_SOLUTIONS as Kr,findSolutionByMessage as Vr}from"@lunora/errors";import{createCodegenProject as qr,findTsconfig as wr,refreshCodegenProject as Jr,tsconfigFingerprint as Yr}from"./packem_shared/createCodegenProject-khHqIXPY.mjs";import{t as Zr,u as $r,v as eo}from"./packem_shared/shard-runtime-BHljpfS5.mjs";import{emitApi as oo,emitCollections as to,emitInternalApi as ao}from"./packem_shared/emitApi-Cdc8MeNK.mjs";import{emitCrons as so,emitScheduler as fo,emitVectors as mo,emitWranglerCronTriggers as po}from"./packem_shared/emitCrons-BQjDleCe.mjs";import{emitDataModel as co}from"./packem_shared/emitDataModel-MjAOi3KM.mjs";import{emitFunctions as xo}from"./packem_shared/emitFunctions-BIMKBLQ8.mjs";import{isTypedSchema as Eo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Wr as GENERATED_HEADER,hr as LUNORA_ERROR_CODES,Kr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,mr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,lr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Lr as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Er as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,Je as buildOpenRpcDocument,ur as buildSchemaSnapshot,y as capabilitiesUsedBy,qr as createCodegenProject,b as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,F as discoverAuthApiCalls,_ as discoverContainers,P as discoverCrons,k as discoverFlags,z as discoverFunctions,V as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ge as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,ye as discoverStorageRulesMetadata,Ge as discoverWorkflows,Zr as emitAgents,oo as emitApi,je as emitApp,to as emitCollections,$r as emitContainers,so as emitCrons,co as emitDataModel,Ur as emitDrizzleSchema,xo as emitFunctions,ao as emitInternalApi,Ve as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,fo as emitScheduler,Hr as emitServer,Br as emitShard,mo as emitVectors,eo as emitWorkflows,po as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Ar as evaluateSchemaDrift,dr as findCodegenConfigFile,Vr as findLunoraSolution,pr as findProjectConfigFile,wr as findTsconfig,Nr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Mr as generateSdk,vr as indexReferencesOf,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,Eo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,gr as parseSchemaSnapshot,er as platformMatrixIds,nr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,sr as readProjectLazyFunctions,rr as readProjectTarget,Ie as readServiceBindings,Dr as redact,Jr as refreshCodegenProject,or as resolveCodegenTarget,Le as resolveServiceBindings,xr as runCodegen,Rr as schemaFromIr,yr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,Yr as tsconfigFingerprint,Fr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as f,lintSchema as m,toAdvisorContext as d}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-BuNEmlCO.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BxpEvZgW.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-DrszPMtU.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-D-ZsZKvv.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as _}from"./packem_shared/CONTAINERS_FILENAME-CvPP3wR-.mjs";import{default as P}from"./packem_shared/discoverCrons-BT_qyOt8.mjs";import{capabilitiesUsedBy as y,createTargetScope as b,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-CsqWN4ob.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-Ce1G6kZd.mjs";import{d as z}from"./packem_shared/index-DuvSMZEy.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-DOkHmHzy.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-BGhSZp00.mjs";import{default as J}from"./packem_shared/discoverInserts-d_zAWqc4.mjs";import{d as X}from"./packem_shared/index-VKPwR6Cj.mjs";import{default as $}from"./packem_shared/discoverMigrations-Dq-7Od3H.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-JBFlT9aD.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-BnSxt5nN.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-DLGxunzB.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-Bvh__ZjJ.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-2K8DSvbt.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-CexxhDRt.mjs";import{default as ge}from"./packem_shared/discoverRlsProcedures-CDbsnndn.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-CugyqoLu.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CSt29RbS.mjs";import{default as he}from"./packem_shared/discoverSchema-DTgg8rAu.mjs";import{readServiceBindings as Ie,resolveServiceBindings as Le}from"./packem_shared/readServiceBindings-rDIqDBSW.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-DCqsIdQQ.mjs";import{default as ye}from"./packem_shared/discoverStorageRulesMetadata-DTXC-pY3.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{emitApp as je}from"./packem_shared/emitApp-D-fxbE34.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-KKQFkA_W.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-CLZ5Em9J.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-C0xI7Xqd.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir,readProjectLazyFunctions as sr}from"./packem_shared/loadProjectConfig-Dbux4jI3.mjs";import{PROJECT_CONFIG_FILENAMES as mr,findCodegenConfigFile as dr,findProjectConfigFile as pr,projectConfigCandidatePaths as nr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as lr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-5N9d9CIu.mjs";import{SchemaSnapshotParseError as Er,buildSchemaSnapshot as ur,evaluateSchemaDrift as Ar,indexReferencesOf as vr,parseSchemaSnapshot as gr}from"./packem_shared/SchemaSnapshotParseError-DnAuFdpl.mjs";import{default as Nr}from"./packem_shared/fingerprintSchemaSources-Pmxw808S.mjs";import{schemaFromIr as Rr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as hr,validatorIrToJsonSchema as Fr}from"./packem_shared/LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{SDK_LANGUAGES as Lr,SDK_TARGETS as _r,generateSdk as Mr}from"./sdk/index.mjs";import{redact as Dr,secretKindOf as yr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Ur}from"./packem_shared/emitDrizzleSchema-Dszoyymv.mjs";import{e as Hr}from"./packem_shared/server-C4h6-BZx.mjs";import{e as Br}from"./packem_shared/shard-DKSPraAt.mjs";import{G as Wr}from"./packem_shared/shared-DhqnD5R3.mjs";import{MESSAGE_SOLUTIONS as Kr,findSolutionByMessage as Vr}from"@lunora/errors";import{createCodegenProject as qr,findTsconfig as wr,refreshCodegenProject as Jr,tsconfigFingerprint as Yr}from"./packem_shared/createCodegenProject-khHqIXPY.mjs";import{t as Zr,u as $r,v as eo}from"./packem_shared/shard-runtime-BHljpfS5.mjs";import{emitApi as oo,emitCollections as to,emitInternalApi as ao}from"./packem_shared/emitApi-Cdc8MeNK.mjs";import{emitCrons as so,emitScheduler as fo,emitVectors as mo,emitWranglerCronTriggers as po}from"./packem_shared/emitCrons-BQjDleCe.mjs";import{emitDataModel as co}from"./packem_shared/emitDataModel-MjAOi3KM.mjs";import{emitFunctions as xo}from"./packem_shared/emitFunctions-BIMKBLQ8.mjs";import{isTypedSchema as Eo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Wr as GENERATED_HEADER,hr as LUNORA_ERROR_CODES,Kr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,mr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,lr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Lr as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Er as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,Je as buildOpenRpcDocument,ur as buildSchemaSnapshot,y as capabilitiesUsedBy,qr as createCodegenProject,b as createTargetScope,n as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,F as discoverAuthApiCalls,_ as discoverContainers,P as discoverCrons,k as discoverFlags,z as discoverFunctions,V as discoverHttpRoutes,q as discoverHyperdriveCalls,J as discoverInserts,X as discoverMaskProcedures,$ as discoverMigrations,oe as discoverMutators,ae as discoverNondeterministicCalls,fe as discoverNotifyCalls,me as discoverNotifyChannels,de as discoverNotifyConfig,le as discoverQueries,Ee as discoverQueues,Ae as discoverR2sqlCalls,Ne as discoverRlsMetadata,ge as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,ye as discoverStorageRulesMetadata,Ge as discoverWorkflows,Zr as emitAgents,oo as emitApi,je as emitApp,to as emitCollections,$r as emitContainers,so as emitCrons,co as emitDataModel,Ur as emitDrizzleSchema,xo as emitFunctions,ao as emitInternalApi,Ve as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,fo as emitScheduler,Hr as emitServer,Br as emitShard,mo as emitVectors,eo as emitWorkflows,po as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Ar as evaluateSchemaDrift,dr as findCodegenConfigFile,Vr as findLunoraSolution,pr as findProjectConfigFile,wr as findTsconfig,Nr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Mr as generateSdk,vr as indexReferencesOf,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,Eo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,gr as parseSchemaSnapshot,er as platformMatrixIds,nr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,sr as readProjectLazyFunctions,rr as readProjectTarget,Ie as readServiceBindings,Dr as redact,Jr as refreshCodegenProject,or as resolveCodegenTarget,Le as resolveServiceBindings,xr as runCodegen,Rr as schemaFromIr,yr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,Yr as tsconfigFingerprint,Fr as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as K,readFileSync as Je,mkdirSync as jt,writeFileSync as Pr,rmSync as we,readdirSync as Dn}from"node:fs";import{dirname as Ht,join as v,relative as Gt}from"node:path";import{performance as St}from"node:perf_hooks";import{runAdvisor as wr}from"@lunora/advisor";import{LunoraError as M}from"@lunora/errors";import{serializeSchemaSnapshot as Ir}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Tr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Yt,ts as Cr,VariableDeclarationKind as Qt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as T,descendantsOfKind as E,bindingKeyName as fe,collectCallRows as k,findObjectProperty as U,collectSecurityCallRows as Or,propertyInitializer as D,listSecurityScanFiles as Ze,objectLiteralFromCallbackBody as Mn,limitNameOf as _n,optionsObjectLiteral as zn,handlerOf as kr,collectNodeRows as re,chainRootOf as et,outermostValueWrapper as O,isWriteTarget as tt,isSameNode as b,unwrapExpression as h,isConstDeclaration as oe,memberAccessOf as Xt,returningFunctionOf as kt,walkChain as Rr,RUN_METHODS as Kn,functionReferenceSegments as Fr,isTestPath as Lr,isFunctionLike as ae,functionKeyOf as $n,withSourceListMemo as Dr}from"./isTestPath-DrszPMtU.mjs";import{j as J,h as G,d as _,b as Jt,c as S,a as st,w as Zt,k as Mr,l as _r,f as zr,m as Kr,g as Rt,i as $r}from"./attribution-7Qs8xFmy.mjs";import{b as $s,r as At,a as Q,e as Br,m as Bn,c as nt,f as es,E as Vn,C as Un,d as Vr,g as Ur,i as Wr}from"./context-root-DHXNIvVA.mjs";import{a as C,i as Wn,c as se,d as qn,e as qr,f as jr,g as jn}from"./classify-procedure-call-D7XTLd8w.mjs";import{a as A,s as Hr}from"./property-name-7cBlgK_O.mjs";import{b as Gr,a as it}from"./module-specifiers-BctA0m_p.mjs";import{r as rt,s as Yr}from"./parse-validator-BisfC8bR.mjs";import Qr from"./discoverAuthApiCalls-D-ZsZKvv.mjs";import{i as $,r as Hn}from"./database-calls-CxJgjC_X.mjs";import{i as Ft,p as Gn,w as Xr,d as Jr}from"./index-DzO8JT7M.mjs";import Zr from"./discoverHyperdriveCalls-BGhSZp00.mjs";import{diagnosticAt as ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ts,a as qe,s as Yn,d as eo}from"./index-VKPwR6Cj.mjs";import{MUTATORS_FILENAME as to,isDefineMutatorCallee as so,mutatorServerImplOf as no,discoverMutators as io}from"./MUTATORS_FILENAME-JBFlT9aD.mjs";import ro from"./discoverNondeterministicCalls-CWLdAwUM.mjs";import{discoverNotifyConfig as oo,discoverNotifyCalls as ao}from"./NOTIFY_FILENAME-DLGxunzB.mjs";import co from"./discoverR2sqlCalls-CexxhDRt.mjs";import lo from"./discoverRlsProcedures-CDbsnndn.mjs";import{s as ss,n as uo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as fo,redact as go,isHeuristicSecretKind as po,isSecretishName as mo}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Qn,readProjectLazyFunctions as ho,readMergeDurableObjects as vo}from"./loadProjectConfig-Dbux4jI3.mjs";import{a as Me,d as Eo,r as xo}from"./modules-CYf6V2w7.mjs";import{WORKFLOWS_FILENAME as So,discoverWorkflows as Ao}from"./WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{r as yo}from"./json-data-Chfs2Cz5.mjs";import{a as bo,I as No,g as Po,G as Xn,d as wo,i as Io}from"./shared-DhqnD5R3.mjs";import{createCodegenProject as To}from"./createCodegenProject-khHqIXPY.mjs";import{findTsconfig as HE,refreshCodegenProject as GE,tsconfigFingerprint as YE}from"./createCodegenProject-khHqIXPY.mjs";import{CAPABILITIES as Co,usedCapabilities as Oo}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Jn,isHyperdriveGlobalTable as Zn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as ko}from"./AGENTS_FILENAME-BxpEvZgW.mjs";import{discoverContainers as Ro}from"./CONTAINERS_FILENAME-CvPP3wR-.mjs";import Fo from"./discoverCrons-BT_qyOt8.mjs";import{contextPropertiesRead as Lo,fileWiresRequestSecretTool as Do,createTargetScope as Mo,discoverFeatureUsage as _o}from"./capabilitiesUsedBy-B8KULfAq.mjs";import ei from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as zo,findProjectConfigFile as Ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as $o}from"./QUEUES_FILENAME-2K8DSvbt.mjs";import{discoverSandboxUsage as Bo}from"./discoverSandboxUsage-CSt29RbS.mjs";import{resolveServiceBindings as Vo}from"./readServiceBindings-rDIqDBSW.mjs";import Uo from"./discoverStorageRulesMetadata-DTXC-pY3.mjs";import{resolveCodegenTarget as _e,gatePlatformFeatures as Wo,readTargetDiagnostics as qo,vectorizeDimensionDiagnostics as jo,liveStreamsDeliveryAuthorizationDiagnostic as Ho,socketRoutesDeliveryAuthorizationDiagnostic as Go,studioPlatformFor as Yo,platformFeatureAvailable as Qo,gateAdminTokenRevocation as Xo}from"./DEFAULT_TARGET-C0xI7Xqd.mjs";import{i as Jo}from"./schema-BgM8A3XV.mjs";import{b as ti,e as Zo}from"./shard-DXVp_Iht.mjs";import{e as ea,a as ta}from"./server-Box8pDwi.mjs";import{emitDataModel as sa}from"./emitDataModel-MjAOi3KM.mjs";import{i as na,b as ia,e as ra,d as oa,f as aa,c as ca}from"./unwrap-handler-return-X7HuBhd5.mjs";import la from"./discoverHttpRoutes-DOkHmHzy.mjs";import da from"./discoverInserts-d_zAWqc4.mjs";import{e as si}from"./exported-procedure-chains-D1wkgxKb.mjs";import ua from"./discoverMigrations-Dq-7Od3H.mjs";import Bs from"./discoverQueries-Bvh__ZjJ.mjs";import fa from"./discoverRlsMetadata-CugyqoLu.mjs";import ga from"./discoverSchema-DTgg8rAu.mjs";import{discoverShapes as pa}from"./SHAPES_FILENAME-DCqsIdQQ.mjs";import{i as ma}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as ha,emitApp as va}from"./emitApp-D-fxbE34.mjs";import{readJsonSync as Ea}from"@visulima/fs";import{indexReferencesOf as xa,buildSchemaSnapshot as Sa}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as Aa,emitOpenApiModule as ya}from"./buildOpenApiDocument-KKQFkA_W.mjs";import{buildOpenRpcDocument as ba,emitOpenRpcModule as Na}from"./OPENRPC_VERSION-CLZ5Em9J.mjs";import{w as Pa,u as wa,v as Ia,t as Ta,x as Ca}from"./shard-runtime-BHljpfS5.mjs";import{emitCollections as Oa,emitSeed as ka,emitApi as Ra,emitInternalApi as Fa}from"./emitApi-Cdc8MeNK.mjs";import{emitCrons as La,emitScheduler as Da,emitAdminRevocations as Ma,emitShardRegistry as _a,emitDurableObjects as za,emitVectors as Ka,emitWranglerCronTriggers as $a}from"./emitCrons-BQjDleCe.mjs";import Ba from"./emitDrizzleSchema-Dszoyymv.mjs";import{LAZY_FUNCTION_DIRECTORY as ni,emitFunctions as Va,emitLazyFunctionModules as Ua}from"./emitFunctions-BIMKBLQ8.mjs";const Wa=(e,t=!1)=>{if(e.length===0)return"";const s=wo(t),n=e.map(c=>{if(bo(c.exportName,"live stream export name"),!No.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{Po(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const x=u.fields.map(N=>`\${encodeURIComponent(key.${N})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
1
+ import{existsSync as K,readFileSync as Je,mkdirSync as jt,writeFileSync as Pr,rmSync as we,readdirSync as Dn}from"node:fs";import{dirname as Ht,join as v,relative as Gt}from"node:path";import{performance as St}from"node:perf_hooks";import{runAdvisor as wr}from"@lunora/advisor";import{LunoraError as M}from"@lunora/errors";import{serializeSchemaSnapshot as Ir}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Tr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Yt,ts as Cr,VariableDeclarationKind as Qt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as T,descendantsOfKind as E,bindingKeyName as fe,collectCallRows as k,findObjectProperty as U,collectSecurityCallRows as Or,propertyInitializer as D,listSecurityScanFiles as Ze,objectLiteralFromCallbackBody as Mn,limitNameOf as _n,optionsObjectLiteral as zn,handlerOf as kr,collectNodeRows as re,chainRootOf as et,outermostValueWrapper as O,isWriteTarget as tt,isSameNode as b,unwrapExpression as h,isConstDeclaration as oe,memberAccessOf as Xt,returningFunctionOf as kt,walkChain as Rr,RUN_METHODS as Kn,functionReferenceSegments as Fr,isTestPath as Lr,isFunctionLike as ae,functionKeyOf as $n,withSourceListMemo as Dr}from"./isTestPath-DrszPMtU.mjs";import{j as J,h as G,d as _,b as Jt,c as S,a as st,w as Zt,k as Mr,l as _r,f as zr,m as Kr,g as Rt,i as $r}from"./attribution-7Qs8xFmy.mjs";import{b as $s,r as At,a as Q,e as Br,m as Bn,c as nt,f as es,E as Vn,C as Un,d as Vr,g as Ur,i as Wr}from"./context-root-DHXNIvVA.mjs";import{a as C,i as Wn,c as se,d as qn,e as qr,f as jr,g as jn}from"./classify-procedure-call-D7XTLd8w.mjs";import{a as A,s as Hr}from"./property-name-7cBlgK_O.mjs";import{b as Gr,a as it}from"./module-specifiers-BctA0m_p.mjs";import{r as rt,s as Yr}from"./parse-validator-BisfC8bR.mjs";import Qr from"./discoverAuthApiCalls-D-ZsZKvv.mjs";import{i as $,r as Hn}from"./database-calls-CxJgjC_X.mjs";import{i as Ft,p as Gn,w as Xr,d as Jr}from"./index-DuvSMZEy.mjs";import Zr from"./discoverHyperdriveCalls-BGhSZp00.mjs";import{diagnosticAt as ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ts,a as qe,s as Yn,d as eo}from"./index-VKPwR6Cj.mjs";import{MUTATORS_FILENAME as to,isDefineMutatorCallee as so,mutatorServerImplOf as no,discoverMutators as io}from"./MUTATORS_FILENAME-JBFlT9aD.mjs";import ro from"./discoverNondeterministicCalls-BnSxt5nN.mjs";import{discoverNotifyConfig as oo,discoverNotifyCalls as ao}from"./NOTIFY_FILENAME-DLGxunzB.mjs";import co from"./discoverR2sqlCalls-CexxhDRt.mjs";import lo from"./discoverRlsProcedures-CDbsnndn.mjs";import{s as ss,n as uo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as fo,redact as go,isHeuristicSecretKind as po,isSecretishName as mo}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Qn,readProjectLazyFunctions as ho,readMergeDurableObjects as vo}from"./loadProjectConfig-Dbux4jI3.mjs";import{a as Me,d as Eo,r as xo}from"./modules-CYf6V2w7.mjs";import{WORKFLOWS_FILENAME as So,discoverWorkflows as Ao}from"./WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{r as yo}from"./json-data-Chfs2Cz5.mjs";import{a as bo,I as No,g as Po,G as Xn,d as wo,i as Io}from"./shared-DhqnD5R3.mjs";import{createCodegenProject as To}from"./createCodegenProject-khHqIXPY.mjs";import{findTsconfig as HE,refreshCodegenProject as GE,tsconfigFingerprint as YE}from"./createCodegenProject-khHqIXPY.mjs";import{CAPABILITIES as Co,usedCapabilities as Oo}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Jn,isHyperdriveGlobalTable as Zn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as ko}from"./AGENTS_FILENAME-BxpEvZgW.mjs";import{discoverContainers as Ro}from"./CONTAINERS_FILENAME-CvPP3wR-.mjs";import Fo from"./discoverCrons-BT_qyOt8.mjs";import{contextPropertiesRead as Lo,createTargetScope as Do,fileWiresRequestSecretTool as Mo,discoverFeatureUsage as _o}from"./capabilitiesUsedBy-CsqWN4ob.mjs";import ei from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as zo,findProjectConfigFile as Ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as $o}from"./QUEUES_FILENAME-2K8DSvbt.mjs";import{discoverSandboxUsage as Bo}from"./discoverSandboxUsage-CSt29RbS.mjs";import{resolveServiceBindings as Vo}from"./readServiceBindings-rDIqDBSW.mjs";import Uo from"./discoverStorageRulesMetadata-DTXC-pY3.mjs";import{resolveCodegenTarget as _e,gatePlatformFeatures as Wo,readTargetDiagnostics as qo,vectorizeDimensionDiagnostics as jo,liveStreamsDeliveryAuthorizationDiagnostic as Ho,socketRoutesDeliveryAuthorizationDiagnostic as Go,studioPlatformFor as Yo,platformFeatureAvailable as Qo,gateAdminTokenRevocation as Xo}from"./DEFAULT_TARGET-C0xI7Xqd.mjs";import{i as Jo}from"./schema-BgM8A3XV.mjs";import{b as ti,e as Zo}from"./shard-DKSPraAt.mjs";import{e as ea,a as ta}from"./server-C4h6-BZx.mjs";import{emitDataModel as sa}from"./emitDataModel-MjAOi3KM.mjs";import{i as na,b as ia,e as ra,d as oa,f as aa,c as ca}from"./unwrap-handler-return-X7HuBhd5.mjs";import la from"./discoverHttpRoutes-DOkHmHzy.mjs";import da from"./discoverInserts-d_zAWqc4.mjs";import{e as si}from"./exported-procedure-chains-D1wkgxKb.mjs";import ua from"./discoverMigrations-Dq-7Od3H.mjs";import Bs from"./discoverQueries-Bvh__ZjJ.mjs";import fa from"./discoverRlsMetadata-CugyqoLu.mjs";import ga from"./discoverSchema-DTgg8rAu.mjs";import{discoverShapes as pa}from"./SHAPES_FILENAME-DCqsIdQQ.mjs";import{i as ma}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as ha,emitApp as va}from"./emitApp-D-fxbE34.mjs";import{readJsonSync as Ea}from"@visulima/fs";import{indexReferencesOf as xa,buildSchemaSnapshot as Sa}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as Aa,emitOpenApiModule as ya}from"./buildOpenApiDocument-KKQFkA_W.mjs";import{buildOpenRpcDocument as ba,emitOpenRpcModule as Na}from"./OPENRPC_VERSION-CLZ5Em9J.mjs";import{w as Pa,u as wa,v as Ia,t as Ta,x as Ca}from"./shard-runtime-BHljpfS5.mjs";import{emitCollections as Oa,emitSeed as ka,emitApi as Ra,emitInternalApi as Fa}from"./emitApi-Cdc8MeNK.mjs";import{emitCrons as La,emitScheduler as Da,emitAdminRevocations as Ma,emitShardRegistry as _a,emitDurableObjects as za,emitVectors as Ka,emitWranglerCronTriggers as $a}from"./emitCrons-BQjDleCe.mjs";import Ba from"./emitDrizzleSchema-Dszoyymv.mjs";import{LAZY_FUNCTION_DIRECTORY as ni,emitFunctions as Va,emitLazyFunctionModules as Ua}from"./emitFunctions-BIMKBLQ8.mjs";const Wa=(e,t=!1)=>{if(e.length===0)return"";const s=wo(t),n=e.map(c=>{if(bo(c.exportName,"live stream export name"),!No.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{Po(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const x=u.fields.map(N=>`\${encodeURIComponent(key.${N})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
2
  __lunoraLive: ${m},
3
3
  topic: \`${u.name}:${x}\`,
4
4
  }),`});return` ${c.exportName}: {
@@ -25,7 +25,7 @@ ${i.join(`
25
25
  `);throw new M("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
26
26
  ${i}
27
27
 
28
- Install them with your package manager, then re-run codegen.`)},Jp="env.ts",Zp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return it(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},em=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&it(n.getModuleSpecifierValue())}return!1},tm=e=>{if(r.isIdentifier(e))return Zp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&em(t)}return!1},sm=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!tm(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ce(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=st(s,"member");a!==void 0&&t.push({exportName:a})}return t},nm=(e,t)=>{const s=v(t,Jp);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=sm(n);if(i.length!==0){if(i.length>1)throw ce(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},im={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},rm=new Set(["allowedHosts","deniedHosts","interceptHttps"]),om=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},am=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),cm=new Set(["durable"]),lm=new Set(["rollback"]),Bi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},dm="defineApp",Pe="app",Nn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===Pe&&s.getInitializer()?.getText()===t)||t===Pe&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===Pe),um=e=>{if(e===void 0||!zo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===Pe;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===Pe;if(r.isVariableDeclaration(t))return Nn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&Nn(e.getSourceFile(),s)},fm="AppBuilder",Vi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},gm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===fm&&s.getDeclarations().some(n=>Vi(n))},pm=e=>e.getText()===dm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Vi(t)),Ui=(e,t,s=new Set)=>{const n=et(t);if(n===void 0||!r.isIdentifier(n))return!1;if(pm(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return um(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Ui(e,a.getInitializer(),s)}}return!1},Wi=(e,t)=>{const s=Xt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Ui(e,s.object)||gm(s.object))},mm=new Map([["defineContainer",{keys:rm,signal:"containerEgressPolicy"}],["defineStep",{keys:lm,signal:"workflowRollback"}],["stream",{keys:cm,signal:"durableStreams"}]]),hm=(e,t)=>{const s=mm.get(Bi(t));if(s!==void 0)return t.getArguments().some(n=>am(om(e,n),s.keys))?s.signal:void 0},vm=(e,t)=>im[Bi(t)]??(Wi(e,t)?"deliveryAuthorization":void 0),Em=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Lo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=E(o,d.CallExpression);for(const c of a){const l=hm(o,c)??vm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>jn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Je(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Wi(i,o))}return n},xm=(e,t)=>{const s=Mo();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Do(i,s))return!0}return!1},Sm="createWorker",Am="extend",Pn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,wn=e=>{const t=[],s=Pn(D(e,"backupCron"));s!==void 0&&t.push(s);const n=D(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=Pn(i.getNameNode());o!==void 0&&t.push(o)}return t},ym=e=>{const t=C(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Sm)return r.isObjectLiteralExpression(s)?wn(s):[];if(t!==Am||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Mn(s.getBody());return n===void 0?[]:wn(n)},bm=(e,t)=>{const s=[];for(const{filePath:n}of Ze(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...ym(o))}return[...new Set(s)]},qi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:qi(e.inner)},Nm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=qi(n);return i!==void 0&&t.has(i)}))},Pm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new M("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new M("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},wm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=pd(s,t),a=nm(s,t),c=Ao(s,t),{queues:l,topics:u}=$o(s,t),f=Vo(n),g=ko(s,t);Pm(c,g);const m=Ro(s,t),x=Uo(s,t),N=Fo(s,t,c,g),pe=bm(s,t),P=Em(s,t,Ko(n)),B=Bo(s,t),Y=xm(s,t),w=_o(s,t);w.browser=w.browser||B.usesSandboxBrowser;const W=_e(n,e.target),L=Wo(w,W,{agents:g.length>0,commitOrderedTables:i.tables.some(z=>z.commitOrdered===!0),cronTriggers:N.length>0,crossShardFanout:i.tables.some(z=>Jo(z)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(z=>z.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(z=>z.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(z=>z.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:Nm(i),secretValues:Y,secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:B.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(z=>z.schedules!==void 0)}),R=L.usage,Z=Oo(R),ee=L.signals.vectorStore!==!1,ne=L.signals.services===!1?[]:f,ie=ei(n),le=ie??new Set,I=le.has("lunorash");Xp(i,ie,{hasVectors:ee,scheduler:R.scheduler||N.length>0,storage:R.storage||x.rules.length>0||Object.keys(ti(i)).length>0,usage:R});const F=K(v(t,"flags.ts")),V=K(v(t,"notify.ts"));return{agents:g,capabilities:Z,containers:m,crons:N,dataModelContent:sa(i),declaredDependencies:ie,dependencies:le,entryCronTriggers:pe,env:a,featureUsage:R,hasFlags:F,hasNotify:V,identity:o,platformGate:{...L,diagnostics:[...qo(n,e.target),...L.diagnostics,...jo(W,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[Ho(W)]:[],...P.socketRoutes&&P.deliveryAuthorization?[Go(W)]:[]]},queues:l,serverContent:ea({agents:g,capabilities:Z,containers:m,env:a,hasVectors:ee,hasFlags:F,hasNotify:V,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:x.rules.map(z=>z.bucket),topics:u,useUmbrella:I,workflows:c}),services:ne,storageRulesMetadata:x,topics:u,usesSandbox:B.usesSandboxBrowser||B.usesSandboxContainer||B.usesSandboxFs,useUmbrella:I,workflows:c}},ji=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Im=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},Tm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Cm=/^[\w$]+:[\w$]+$/u,Om=(e,t)=>{const s=$n(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},In=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},km=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return In(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Qt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?In(s):void 0}}},Rm=(e,t,s)=>({schedule:{argKeys:km(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Fm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Kn.has(s))return Om(s,n);if((s==="runAfter"||s==="runAt")&&Im(t)){const l=$n(i)??(r.isStringLiteral(i)&&Cm.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Rm(s,n,o)}}const a=Tm.get(s),c=a===void 0?void 0:ji(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Lm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Hi=e=>Cr.isOptionalChain(e.compilerNode),Dm=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ae(t)?t.getFirstAncestor(ae)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Lm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Hi(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Hg(s)),Mm=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ae);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(ae),i))===!0},_m=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),zm=(e,t)=>{if(Hi(e)||t==="schedule"&&Mm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Dm(s,i)){if(!_m(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Tn=(e,t,s)=>{if(s===void 0)return;const n=zm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Km=(e,t)=>[...k(e,t,(s,n)=>Tn(s,n,Fm(s))),...re(e,t,d.PropertyAccessExpression,(s,n)=>{const i=ji(s,"services");return Tn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],$m=new Set(["boolean","number","object","string"]),Bm=e=>{const t=e.getName();if(!$m.has(t))return;const s=e.getExpression();return Q(s,["flags"])||Q(s,["flags","details"])?t:void 0},Vm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Bm(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},Um=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=Vm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Wm=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||na(o))return;const a=e.getSourceFile().getFilePath();if(ia(i,e,a)){const c=ra(i,e,a,0,new Set);return c===void 0&&oa(o),c}return o},qm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Hr(t.getNameNode());return s===void 0||s==="namespace"}),jm=(e,t)=>{for(const{filePath:s}of Ze(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of E(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||qm(a)))return i}}},Hm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Gm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ce(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Hm}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},Ym="room:",Qm="__lunora_socket__:",Xm=/^[A-Za-z]\w*$/u,Cn=e=>Xm.test(e),Jm=e=>`${e}:`.startsWith(Ym)||`${e}:`.startsWith(Qm),Gi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Yi=e=>Gi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),On=e=>A(e),us=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),ue=(e,t)=>{const s=ce(e,`defineLiveStream ${t}`);return new M("LIVE_STREAM_NOT_LITERAL",s.message)},Qi=(e,t,s)=>{const n=us(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ue(n??e,`needs ${s} so codegen can read its topics`);if(Yi(i))throw ue(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Zm=(e,t)=>{const s=On(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Yi(n))throw ue(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Cn(s)||Jm(s))throw new M("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(us(n,"key")===void 0)return{fields:[],name:s};const a=Qi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>On(l)),c=a.find(l=>!Cn(l));if(c!==void 0)throw new M("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},eh=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Gi(n))throw ue(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=us(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ue(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Qi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:T(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Zm(a,l))}},th=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new M("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},sh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},nh=(e,t)=>E(e,d.CallExpression).filter(s=>jn(s,"defineLiveStream")).map(s=>{const n=sh(s),i=r.isVariableDeclaration(n)?st(n,"binding"):void 0;if(i===void 0)throw new M("LIVE_STREAM_NOT_EXPORTED",ce(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return eh(s,i,t)}),ih=(e,t)=>{const s=y(t).flatMap(n=>nh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return th(s),s},rh=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,oh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?rh(e):!0,Xi=(e,t=!1)=>{for(const s of e.getProperties()){if(oh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Xi(n,!0))return!0}return!1},ah=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of si(n))for(const o of ts(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Xi(a)))return!0}}return!1},ch=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=qe(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=qe(a);c!==void 0&&s.push({column:c,strategy:Yn(a),table:i})}}return s},lh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of si(i))for(const a of ts(o))for(const c of ch(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},dh=["providerSubscriptionId","state"],uh=["providerEventId","processedAt"],kn=(e,t)=>t.every(s=>s in e.shape),fh=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&kn(t,dh)&&kn(s,uh)},gh=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],ph=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},mh=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},hh="@lunora/privacy",Ji="userId",Rn=new Set(["user","users"]),vh=e=>e.replaceAll("\\","/"),Eh="privacy",xh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),at=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Te=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",fs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Sh=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},ct=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Ah=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Sh(s,"tables"),i=at(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:fs(n).map(a=>Te(a)))t.datasets.set(o,i)},gs=8,ve=(e,t=0)=>{if(t>gs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return ve(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:ve(i,t+1)},yh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:ve(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[],o=new Set(i.map(a=>Te(a)));for(const a of gh)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?at(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Te(a)==="user"&&t.userTables.add(c))}},Fn=(e,t,s)=>{t.datasets.set(at(e.getArguments()[0])??s,s)},bh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Te(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Zi=(e,t=0)=>{const s=ve(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>gs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Zi(i.getExpression(),t+1):[bh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Nh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Zi(t)},Ph=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:ve(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[])t.excluded.set(Te(i),r.isPropertyAssignment(i)?at(i.getInitializer())??"":"")},wh=(e,t)=>{switch(ct(e)){case"actionCacheDataset":{Fn(e,t,"actionCache");break}case"authDataset":{yh(e,t);break}case"defineDataset":{Ah(e,t);break}case"documentHistoryDataset":{Fn(e,t,"documentHistory");break}}},ps=e=>e!==void 0&&r.isCallExpression(e)&&ct(e)==="defineDataset",er=e=>e!==void 0&&r.isCallExpression(e)&&xh.has(ct(e)??""),Ih=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(ps(i)||er(i))?n:void 0},tr=(e,t,s=0)=>{const n=ve(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>gs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!tr(i.getExpression(),t,s+1))return!1}else if(!ps(i)&&!er(i)){const o=r.isIdentifier(i)?Ih(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Th=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||tr(t,s)?s:void 0},Ch=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if(wh(i,t),ct(i)==="definePrivacy"){const o=Nh(i);Ph(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Th(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>ps(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Oh=(e,t)=>{const s=v(t,"schema.ts"),n=[...y(t),...K(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>vh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},kh=(e,t,s)=>{if(s?.has(hh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Rn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Rn)},i=[],o=[];for(const f of Oh(e,t)){const g=Ch(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:ph(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},sr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&sr(n,t)),Rh=(e,t)=>e.extensionKey!==Eh&&(Ji in e.shape||Object.values(e.shape).some(s=>sr(s,t))),Fh=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${Ji}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Lh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Rh(o,t.userTables)).map(o=>o.name),[n]=mh(s,t.classifications);if(n!==void 0)throw new M("PRIVACY_COVERAGE",Fh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new M("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Dh=(e,t)=>{const s=Yo(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Mh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Ln=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),_h="",zh=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Kh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Qt.Const?t.getInitializer():void 0},Ue=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ue(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Kh(e);if(n!==void 0)return Ue(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},$h=(e,t)=>{if(Mh.has(e))return{method:e,tables:Ue(t)??[_h]}},Ot=(e,t,s)=>e===void 0?void 0:{...e,fields:zh(t,e.method,s)},Bh=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Qt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},Vh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Bh(n);if(i!==void 0)return Ln.has(s)?Ot({method:s,tables:[i]},e,1):void 0;if($(n))return Ot($h(s,e.getArguments()[0]),e,2);if(Ln.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Ot({method:s,tables:[n.getName()]},e,1)},Uh=(e,t)=>k(e,t,(s,n)=>{const i=Vh(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Wh=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),qh=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||U(s,"args")===void 0)return!1}return is(e,t).opaque},jh=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=se(a);c!==void 0&&qh(a,c.receiver)&&s.push(Wh(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},Hh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...jh(i,T(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Gh=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Xe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),nr=e=>!e.isAny(),ir=e=>{const t=e.getType();if(!nr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Gh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Yh=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},rr={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},Qh=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),Xh={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},Jh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Zh={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},ev=(e,t,s)=>{if(!t.some(i=>$r(i)))return Xh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Jh.has(s.typeName)&&!n&&!t.some(i=>ma(i))?Zh:rr},or=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Qh(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},tv=(e,t,s)=>{const n=[];for(const i of J(e)){const o=r.isIdentifier(i.getNameNode())?Rt(i):[i.getName()],c=o.some(u=>Xe(s,t,u))||!Yh(i)?void 0:ir(i),[l=i.getName()]=o;c!==void 0&&n.push(or(t,l,c,i.getStartLineNumber(),ev(i,o,c)))}return n},sv=(e,t,s)=>{if(Xe(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=ir(i.getExpression());o!==void 0&&n.push(or(t,"default",o,i.getStartLineNumber(),rr))}return n},nv=(e,t,s)=>[...tv(e,t,s),...sv(e,t,s)],iv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Rt(n).some(i=>Xe(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Rt(n).find(o=>Xe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),rv=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),ov=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=T(t,a);n.push(...nv(c,l,s)),i.push(...iv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!nr(a.getType()))&&n.push(rv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},av=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},cv=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},lv=(e,t)=>k(e,t,(s,n)=>av(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:cv(s)}:void 0),ar=e=>e==="@lunora/workflow",dv=e=>new Set(e.getImportDeclarations().filter(t=>ar(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),uv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),fv=(e,t)=>{const s=Wn(e,"defineWorkflowEvent",ar),n=dv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!uv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?st(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new M("WORKFLOW_EVENT_NOT_LITERAL",ce(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:T(t,e.getFilePath()),type:l.getLiteralValue()})}return i},gv=(e,t)=>{const s=y(t).flatMap(i=>fv(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new M("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},Ce=(e,t)=>{K(e)&&Je(e,"utf8")===t||Pr(e,t,"utf8")},pv=(e,t)=>{if(t===""){we(e,{force:!0});return}Ce(e,t)},mv=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){we(s,{force:!0,recursive:!0});return}if(K(s))for(const n of Dn(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Gt(e,i)]===void 0&&we(i)}for(const[n,i]of Object.entries(t))jt(Ht(v(e,n)),{recursive:!0}),Ce(v(e,n),i)},hv=(e,t,s)=>{const n=v(e,t);if(Object.keys(s).length===0){we(n,{force:!0,recursive:!0});return}if(K(n))for(const i of Dn(n,{recursive:!0,withFileTypes:!0})){const o=v(i.parentPath,i.name);i.isFile()&&s[Gt(n,o)]===void 0&&we(o)}for(const[i,o]of Object.entries(s)){const a=v(n,i);jt(Ht(a),{recursive:!0}),Ce(a,o)}},vv=e=>{try{const t=Ea(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},We=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Ev=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,xv=(e,t)=>{K(e)||jt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Ce(v(e,n.name),n.content),s.push(n.name);break}case"directory":{hv(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{mv(e,n.files),s.push(...Object.keys(n.files));break}default:pv(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},Sv=e=>{const t=vv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Aa({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=ba({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
28
+ Install them with your package manager, then re-run codegen.`)},Jp="env.ts",Zp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return it(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},em=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&it(n.getModuleSpecifierValue())}return!1},tm=e=>{if(r.isIdentifier(e))return Zp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&em(t)}return!1},sm=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!tm(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ce(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=st(s,"member");a!==void 0&&t.push({exportName:a})}return t},nm=(e,t)=>{const s=v(t,Jp);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=sm(n);if(i.length!==0){if(i.length>1)throw ce(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},im={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},rm=new Set(["allowedHosts","deniedHosts","interceptHttps"]),om=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},am=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),cm=new Set(["durable"]),lm=new Set(["rollback"]),Bi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},dm="defineApp",Pe="app",Nn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===Pe&&s.getInitializer()?.getText()===t)||t===Pe&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===Pe),um=e=>{if(e===void 0||!zo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===Pe;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===Pe;if(r.isVariableDeclaration(t))return Nn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&Nn(e.getSourceFile(),s)},fm="AppBuilder",Vi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},gm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===fm&&s.getDeclarations().some(n=>Vi(n))},pm=e=>e.getText()===dm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Vi(t)),Ui=(e,t,s=new Set)=>{const n=et(t);if(n===void 0||!r.isIdentifier(n))return!1;if(pm(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return um(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Ui(e,a.getInitializer(),s)}}return!1},Wi=(e,t)=>{const s=Xt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Ui(e,s.object)||gm(s.object))},mm=new Map([["defineContainer",{keys:rm,signal:"containerEgressPolicy"}],["defineStep",{keys:lm,signal:"workflowRollback"}],["stream",{keys:cm,signal:"durableStreams"}]]),hm=(e,t)=>{const s=mm.get(Bi(t));if(s!==void 0)return t.getArguments().some(n=>am(om(e,n),s.keys))?s.signal:void 0},vm=(e,t)=>im[Bi(t)]??(Wi(e,t)?"deliveryAuthorization":void 0),Em=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Lo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=E(o,d.CallExpression);for(const c of a){const l=hm(o,c)??vm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>jn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Je(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Wi(i,o))}return n},xm=(e,t)=>{const s=Do();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Mo(i,s))return!0}return!1},Sm="createWorker",Am="extend",Pn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,wn=e=>{const t=[],s=Pn(D(e,"backupCron"));s!==void 0&&t.push(s);const n=D(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=Pn(i.getNameNode());o!==void 0&&t.push(o)}return t},ym=e=>{const t=C(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Sm)return r.isObjectLiteralExpression(s)?wn(s):[];if(t!==Am||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Mn(s.getBody());return n===void 0?[]:wn(n)},bm=(e,t)=>{const s=[];for(const{filePath:n}of Ze(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...ym(o))}return[...new Set(s)]},qi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:qi(e.inner)},Nm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=qi(n);return i!==void 0&&t.has(i)}))},Pm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new M("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new M("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},wm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=pd(s,t),a=nm(s,t),c=Ao(s,t),{queues:l,topics:u}=$o(s,t),f=Vo(n),g=ko(s,t);Pm(c,g);const m=Ro(s,t),x=Uo(s,t),N=Fo(s,t,c,g),pe=bm(s,t),P=Em(s,t,Ko(n)),B=Bo(s,t),Y=xm(s,t),w=_o(s,t);w.browser=w.browser||B.usesSandboxBrowser;const W=_e(n,e.target),L=Wo(w,W,{agents:g.length>0,commitOrderedTables:i.tables.some(z=>z.commitOrdered===!0),cronTriggers:N.length>0,crossShardFanout:i.tables.some(z=>Jo(z)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(z=>z.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(z=>z.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(z=>z.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:Nm(i),secretValues:Y,secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:B.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(z=>z.schedules!==void 0)}),R=L.usage,Z=Oo(R),ee=L.signals.vectorStore!==!1,ne=L.signals.services===!1?[]:f,ie=ei(n),le=ie??new Set,I=le.has("lunorash");Xp(i,ie,{hasVectors:ee,scheduler:R.scheduler||N.length>0,storage:R.storage||x.rules.length>0||Object.keys(ti(i)).length>0,usage:R});const F=K(v(t,"flags.ts")),V=K(v(t,"notify.ts"));return{agents:g,capabilities:Z,containers:m,crons:N,dataModelContent:sa(i),declaredDependencies:ie,dependencies:le,entryCronTriggers:pe,env:a,featureUsage:R,hasFlags:F,hasNotify:V,identity:o,platformGate:{...L,diagnostics:[...qo(n,e.target),...L.diagnostics,...jo(W,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[Ho(W)]:[],...P.socketRoutes&&P.deliveryAuthorization?[Go(W)]:[]]},queues:l,serverContent:ea({agents:g,capabilities:Z,containers:m,env:a,hasVectors:ee,hasFlags:F,hasNotify:V,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:x.rules.map(z=>z.bucket),topics:u,useUmbrella:I,workflows:c}),services:ne,storageRulesMetadata:x,topics:u,usesSandbox:B.usesSandboxBrowser||B.usesSandboxContainer||B.usesSandboxFs,useUmbrella:I,workflows:c}},ji=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Im=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},Tm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Cm=/^[\w$]+:[\w$]+$/u,Om=(e,t)=>{const s=$n(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},In=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},km=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return In(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Qt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?In(s):void 0}}},Rm=(e,t,s)=>({schedule:{argKeys:km(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Fm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Kn.has(s))return Om(s,n);if((s==="runAfter"||s==="runAt")&&Im(t)){const l=$n(i)??(r.isStringLiteral(i)&&Cm.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Rm(s,n,o)}}const a=Tm.get(s),c=a===void 0?void 0:ji(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Lm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Hi=e=>Cr.isOptionalChain(e.compilerNode),Dm=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ae(t)?t.getFirstAncestor(ae)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Lm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Hi(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Hg(s)),Mm=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ae);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(ae),i))===!0},_m=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),zm=(e,t)=>{if(Hi(e)||t==="schedule"&&Mm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Dm(s,i)){if(!_m(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Tn=(e,t,s)=>{if(s===void 0)return;const n=zm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Km=(e,t)=>[...k(e,t,(s,n)=>Tn(s,n,Fm(s))),...re(e,t,d.PropertyAccessExpression,(s,n)=>{const i=ji(s,"services");return Tn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],$m=new Set(["boolean","number","object","string"]),Bm=e=>{const t=e.getName();if(!$m.has(t))return;const s=e.getExpression();return Q(s,["flags"])||Q(s,["flags","details"])?t:void 0},Vm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Bm(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},Um=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=Vm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Wm=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||na(o))return;const a=e.getSourceFile().getFilePath();if(ia(i,e,a)){const c=ra(i,e,a,0,new Set);return c===void 0&&oa(o),c}return o},qm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Hr(t.getNameNode());return s===void 0||s==="namespace"}),jm=(e,t)=>{for(const{filePath:s}of Ze(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of E(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||qm(a)))return i}}},Hm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Gm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ce(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Hm}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},Ym="room:",Qm="__lunora_socket__:",Xm=/^[A-Za-z]\w*$/u,Cn=e=>Xm.test(e),Jm=e=>`${e}:`.startsWith(Ym)||`${e}:`.startsWith(Qm),Gi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Yi=e=>Gi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),On=e=>A(e),us=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),ue=(e,t)=>{const s=ce(e,`defineLiveStream ${t}`);return new M("LIVE_STREAM_NOT_LITERAL",s.message)},Qi=(e,t,s)=>{const n=us(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ue(n??e,`needs ${s} so codegen can read its topics`);if(Yi(i))throw ue(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Zm=(e,t)=>{const s=On(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Yi(n))throw ue(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Cn(s)||Jm(s))throw new M("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(us(n,"key")===void 0)return{fields:[],name:s};const a=Qi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>On(l)),c=a.find(l=>!Cn(l));if(c!==void 0)throw new M("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},eh=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Gi(n))throw ue(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=us(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ue(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Qi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:T(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Zm(a,l))}},th=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new M("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},sh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},nh=(e,t)=>E(e,d.CallExpression).filter(s=>jn(s,"defineLiveStream")).map(s=>{const n=sh(s),i=r.isVariableDeclaration(n)?st(n,"binding"):void 0;if(i===void 0)throw new M("LIVE_STREAM_NOT_EXPORTED",ce(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return eh(s,i,t)}),ih=(e,t)=>{const s=y(t).flatMap(n=>nh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return th(s),s},rh=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,oh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?rh(e):!0,Xi=(e,t=!1)=>{for(const s of e.getProperties()){if(oh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Xi(n,!0))return!0}return!1},ah=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of si(n))for(const o of ts(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Xi(a)))return!0}}return!1},ch=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=qe(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=qe(a);c!==void 0&&s.push({column:c,strategy:Yn(a),table:i})}}return s},lh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of si(i))for(const a of ts(o))for(const c of ch(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},dh=["providerSubscriptionId","state"],uh=["providerEventId","processedAt"],kn=(e,t)=>t.every(s=>s in e.shape),fh=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&kn(t,dh)&&kn(s,uh)},gh=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],ph=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},mh=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},hh="@lunora/privacy",Ji="userId",Rn=new Set(["user","users"]),vh=e=>e.replaceAll("\\","/"),Eh="privacy",xh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),at=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Te=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",fs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Sh=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},ct=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Ah=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Sh(s,"tables"),i=at(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:fs(n).map(a=>Te(a)))t.datasets.set(o,i)},gs=8,ve=(e,t=0)=>{if(t>gs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return ve(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:ve(i,t+1)},yh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:ve(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[],o=new Set(i.map(a=>Te(a)));for(const a of gh)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?at(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Te(a)==="user"&&t.userTables.add(c))}},Fn=(e,t,s)=>{t.datasets.set(at(e.getArguments()[0])??s,s)},bh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Te(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Zi=(e,t=0)=>{const s=ve(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>gs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Zi(i.getExpression(),t+1):[bh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Nh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Zi(t)},Ph=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:ve(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[])t.excluded.set(Te(i),r.isPropertyAssignment(i)?at(i.getInitializer())??"":"")},wh=(e,t)=>{switch(ct(e)){case"actionCacheDataset":{Fn(e,t,"actionCache");break}case"authDataset":{yh(e,t);break}case"defineDataset":{Ah(e,t);break}case"documentHistoryDataset":{Fn(e,t,"documentHistory");break}}},ps=e=>e!==void 0&&r.isCallExpression(e)&&ct(e)==="defineDataset",er=e=>e!==void 0&&r.isCallExpression(e)&&xh.has(ct(e)??""),Ih=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(ps(i)||er(i))?n:void 0},tr=(e,t,s=0)=>{const n=ve(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>gs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!tr(i.getExpression(),t,s+1))return!1}else if(!ps(i)&&!er(i)){const o=r.isIdentifier(i)?Ih(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Th=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||tr(t,s)?s:void 0},Ch=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if(wh(i,t),ct(i)==="definePrivacy"){const o=Nh(i);Ph(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Th(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>ps(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Oh=(e,t)=>{const s=v(t,"schema.ts"),n=[...y(t),...K(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>vh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},kh=(e,t,s)=>{if(s?.has(hh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Rn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Rn)},i=[],o=[];for(const f of Oh(e,t)){const g=Ch(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:ph(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},sr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&sr(n,t)),Rh=(e,t)=>e.extensionKey!==Eh&&(Ji in e.shape||Object.values(e.shape).some(s=>sr(s,t))),Fh=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${Ji}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Lh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Rh(o,t.userTables)).map(o=>o.name),[n]=mh(s,t.classifications);if(n!==void 0)throw new M("PRIVACY_COVERAGE",Fh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new M("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Dh=(e,t)=>{const s=Yo(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Mh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Ln=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),_h="",zh=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Kh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Qt.Const?t.getInitializer():void 0},Ue=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ue(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Kh(e);if(n!==void 0)return Ue(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},$h=(e,t)=>{if(Mh.has(e))return{method:e,tables:Ue(t)??[_h]}},Ot=(e,t,s)=>e===void 0?void 0:{...e,fields:zh(t,e.method,s)},Bh=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Qt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},Vh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Bh(n);if(i!==void 0)return Ln.has(s)?Ot({method:s,tables:[i]},e,1):void 0;if($(n))return Ot($h(s,e.getArguments()[0]),e,2);if(Ln.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Ot({method:s,tables:[n.getName()]},e,1)},Uh=(e,t)=>k(e,t,(s,n)=>{const i=Vh(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Wh=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),qh=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||U(s,"args")===void 0)return!1}return is(e,t).opaque},jh=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=se(a);c!==void 0&&qh(a,c.receiver)&&s.push(Wh(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},Hh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...jh(i,T(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Gh=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Xe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),nr=e=>!e.isAny(),ir=e=>{const t=e.getType();if(!nr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Gh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Yh=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},rr={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},Qh=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),Xh={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},Jh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Zh={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},ev=(e,t,s)=>{if(!t.some(i=>$r(i)))return Xh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Jh.has(s.typeName)&&!n&&!t.some(i=>ma(i))?Zh:rr},or=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:Qh(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},tv=(e,t,s)=>{const n=[];for(const i of J(e)){const o=r.isIdentifier(i.getNameNode())?Rt(i):[i.getName()],c=o.some(u=>Xe(s,t,u))||!Yh(i)?void 0:ir(i),[l=i.getName()]=o;c!==void 0&&n.push(or(t,l,c,i.getStartLineNumber(),ev(i,o,c)))}return n},sv=(e,t,s)=>{if(Xe(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=ir(i.getExpression());o!==void 0&&n.push(or(t,"default",o,i.getStartLineNumber(),rr))}return n},nv=(e,t,s)=>[...tv(e,t,s),...sv(e,t,s)],iv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Rt(n).some(i=>Xe(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Rt(n).find(o=>Xe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),rv=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),ov=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=T(t,a);n.push(...nv(c,l,s)),i.push(...iv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!nr(a.getType()))&&n.push(rv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},av=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},cv=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},lv=(e,t)=>k(e,t,(s,n)=>av(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:cv(s)}:void 0),ar=e=>e==="@lunora/workflow",dv=e=>new Set(e.getImportDeclarations().filter(t=>ar(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),uv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),fv=(e,t)=>{const s=Wn(e,"defineWorkflowEvent",ar),n=dv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!uv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?st(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new M("WORKFLOW_EVENT_NOT_LITERAL",ce(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:T(t,e.getFilePath()),type:l.getLiteralValue()})}return i},gv=(e,t)=>{const s=y(t).flatMap(i=>fv(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new M("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},Ce=(e,t)=>{K(e)&&Je(e,"utf8")===t||Pr(e,t,"utf8")},pv=(e,t)=>{if(t===""){we(e,{force:!0});return}Ce(e,t)},mv=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){we(s,{force:!0,recursive:!0});return}if(K(s))for(const n of Dn(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Gt(e,i)]===void 0&&we(i)}for(const[n,i]of Object.entries(t))jt(Ht(v(e,n)),{recursive:!0}),Ce(v(e,n),i)},hv=(e,t,s)=>{const n=v(e,t);if(Object.keys(s).length===0){we(n,{force:!0,recursive:!0});return}if(K(n))for(const i of Dn(n,{recursive:!0,withFileTypes:!0})){const o=v(i.parentPath,i.name);i.isFile()&&s[Gt(n,o)]===void 0&&we(o)}for(const[i,o]of Object.entries(s)){const a=v(n,i);jt(Ht(a),{recursive:!0}),Ce(a,o)}},vv=e=>{try{const t=Ea(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},We=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Ev=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,xv=(e,t)=>{K(e)||jt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Ce(v(e,n.name),n.content),s.push(n.name);break}case"directory":{hv(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{mv(e,n.files),s.push(...Object.keys(n.files));break}default:pv(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},Sv=e=>{const t=vv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Aa({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=ba({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
29
29
  `,openApiModuleContent:ya(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
30
30
  `,openRpcModuleContent:Na(i)}},Av=".lunora-schema.json",yv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},bv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new M("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new M("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new M("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},Nv=8,Pv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:x}=e,N=()=>ca(()=>{const w=Jr(l,a,{lazyFunctions:o}),W=io(l,a);return{functions:w,httpRoutes:la(l,a),mutators:W}});let{erased:pe,value:{functions:P,httpRoutes:B,mutators:Y}}=N();Xr(y(a).map(w=>l.getSourceFileOrThrow(w)),w=>Gt(a,w.getFilePath())),bn([...P,...Y].map(w=>w.filePath)),bn(B.filter(w=>w.stream).map(w=>w.filePath),"http-stream");for(let w=1;;w+=1){const W=u?P:P.filter(I=>I.channel?.kind!=="room"&&I.lifecycle!=="socket"),L=Ra({agents:t,functions:W,httpRoutes:B,mutators:Y,useUmbrella:m,workflows:x}),R={agents:t,functions:W,lazyFunctions:o,migrations:c,mutators:Y,shapes:f,useUmbrella:m,usesSandbox:g},Z=Va(R),ee=Ua(R),ne=Fa({functions:P,useUmbrella:m}),ie=v(a,"_generated",ni),le=[[s,L],[i,ne],[n,Z],...Object.entries(ee).map(([I,F])=>[v(ie,I),F])];if(w>=Nv||le.every(([I,F])=>Ev(l,I,F)))return{apiContent:L,erased:pe,functions:P,functionModulesContent:ee,functionsContent:Z,httpRoutes:B,internalContent:ne,mutators:Y};for(const[I,F]of le)We(l,I,F);({erased:pe,value:{functions:P,httpRoutes:B,mutators:Y}}=N())}},wv=e=>{const t=yv(),s=t?St.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=ho(n),o=e.lazyFunctions===!0||i,a=v(n,"schema.ts");if(!K(a))throw new M("INTERNAL",`schema.ts not found at ${a}`);const c=e.project??To(n);Yr(Wm);const l=ga(c,a,e.projectRoot);Lh(l.tables,kh(c,n,ei(e.projectRoot)));const{agents:u,capabilities:f,containers:g,crons:m,dataModelContent:x,dependencies:N,entryCronTriggers:pe,env:P,featureUsage:B,hasFlags:Y,hasNotify:w,identity:W,platformGate:L,queues:R,serverContent:Z,services:ee,storageRulesMetadata:ne,topics:ie,usesSandbox:le,useUmbrella:I,workflows:F}=wm({lunoraDirectory:n,project:c,projectRoot:e.projectRoot,schema:l,target:e.target});Gm(l,l.jurisdiction===void 0?void 0:jm(c,n));const V=v(n,"_generated"),z=v(V,"dataModel.ts"),cr=v(V,"server.ts"),lr=v(V,"api.ts"),dr=v(V,"internal.ts"),ur=v(V,"functions.ts");We(c,z,x),We(c,cr,Z);const ms=Object.fromEntries(ee.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(ta(p,V))));for(const[p,xt]of Object.entries(ms))We(c,v(V,p),xt);const Oe=ua(c,n),de=pa(c,n),lt=L.signals.typedWebSockets!==!1,{apiContent:hs,erased:fr,functions:q,functionModulesContent:vs,functionsContent:Es,httpRoutes:dt,internalContent:xs,mutators:ut}=Pv({agents:u,apiPath:lr,generatedFunctionsPath:ur,internalPath:dr,lazyFunctions:o,roomsSupported:lt,lunoraDirectory:n,migrations:Oe,project:c,shapes:de,useUmbrella:I,usesSandbox:le,workflows:F}),Ss=Eo(c,n),ft=xo(Ss,l,[...q,...dt].map(p=>p.filePath)),ke=Ss.length>0,Ee=e.lint===!1&&!ke?void 0:{callEdges:Km(c,n),inserts:da(c,n),queries:Bs(c,n,q),tableWrites:Uh(c,n),workflowCalls:lv(c,n)},gr=xa(Ee?.queries??Bs(c,n,q)),Re=e.lint===!1||Ee===void 0?void 0:wp(c,n,{callSites:Ee,containers:g,crons:m,functions:q,modules:ft,mutators:ut,queues:R,schema:l,shapes:de,workflows:F,wranglerVariables:e.wranglerVariables}),As=Re===void 0?[]:Fp(e.projectRoot,[...wr(Re,{source:"static"}),...ov(c,n,{byName:new Set([...F,...R,...u,...g].map(p=>p.exportName)),byPath:new Set([...q,...ut,...de,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...Hh(c,n),...aa(fr,n),...Pa(R,e.wranglerQueueProducers)]),pr=fa(c,n),ys=lh(c,n);bv(de,ys,ah(c,n));const mr=Y?Um(c,n):[],gt=L.signals.vectorStore!==!1,hr=Qo(_e(e.projectRoot,e.target),"deliveryAuthorization"),xe=Dh(B,{containerCount:g.length,cronCount:m.length,dependencies:N,hasPaymentTables:fh(l.tables),queueCount:R.length,storageColumnCount:Object.keys(ti(l)).length,storageRuleCount:ne.rules.length,vectorIndexCount:l.vectorIndexes.length,target:_e(e.projectRoot,e.target),vectorStoreSupported:gt,workflowCount:F.length}),bs=t?St.now():0,pt=Sa(l,Oe.map(p=>p.id)),mt=ih(c,n),Ns=Zo({advisories:As.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Re?.procedureProtections??[],agents:u,capabilities:f,containers:g,env:P,flagKeys:mr,hasFlags:Y,hasNotify:w,hasIpReaders:q.some(p=>p.readsIp===!0)||de.some(p=>p.readsIp===!0),hasRooms:lt&&q.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:u.length>0||q.some(p=>Io(p)),hasSecretValues:L.signals.secretValues===!0,hasSockets:lt&&q.some(p=>p.lifecycle==="socket"),lazyFunctions:o,hasVectors:gt,liveStreamDeclarations:mt,liveStreams:L.signals.liveStreams===!0,maskMetadata:ys,mutators:ut,queues:R,rlsMetadata:pr,schema:l,schemaSnapshot:pt,shapes:de,services:ee,storageRules:ne,studioFeatures:xe,topics:ie,useUmbrella:I,workflowEvents:gv(c,n),workflows:F}),Ps=Oa(de,N.has("@lunora/db"),I),ws=wa(g,l.jurisdiction),Is=Ia(F,{lazy:o}),Ts=Ta(u,{lazy:o}),Cs=Ca(R,e.wranglerQueueProducers),Os=Wa(mt,I),ks=La(m),vr=Da(xe.scheduler),Fe=Xo(_e(e.projectRoot,e.target)),Er=Fe.supported?Ma(I):"",xr=_a(l.tables,I,l.jurisdiction),Sr=vo(e.projectRoot)?za(I):"",Rs=Ka(l.vectorIndexes),Le=Ba(l,I),Fs=ka(N.has("@lunora/seed")),De=e.apiSpec??"openapi",ht=De==="openapi"||De==="both",vt=De==="openrpc"||De==="both",Ls=ha(N.has("@lunora/auth")),Ds=va({agentWorkflows:u.map(p=>p.className),capabilities:f,emailAgents:u.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:N.has("@lunora/cloudflare-access"),hasAuth:N.has("@lunora/auth"),hasFramework:N.has("@lunora/astro")||N.has("@lunora/svelte")||N.has("@lunora/vue")||K(v(e.projectRoot,"src","worker.ts")),hasGlobal:l.tables.some(p=>Jn(p)),hasHyperdriveGlobal:l.tables.some(p=>Zn(p)),hasKvIntrospector:xe.kv,hasNotify:w,hasQueue:R.some(p=>p.mode==="push"),liveStreams:L.signals.liveStreams===!0,liveStreamsWithheld:L.liveStreamsWithheld,liveStreamDeclarations:mt,hasAdminRevocations:Fe.supported,hasScheduler:xe.scheduler,hasSourcedTables:l.tables.some(p=>p.externalSource!==void 0),hasStorage:xe.storage,hasDeliveryAuthorization:hr,hasVectors:gt,hasWorkflow:F.length>0,identity:W,jurisdiction:l.jurisdiction,jurisdictionPinsAuth:l.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:l.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:I,vectorIndexCount:l.vectorIndexes.length,voiceAgents:u.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:ht,wantsOpenRpc:vt}),{openApiContent:Ms,openApiModuleContent:_s,openRpcContent:zs,openRpcModuleContent:Ks}=Sv({functions:q,httpRoutes:dt,modules:ft,projectRoot:e.projectRoot,wantsArchitecture:ke}),Se=ke&&Ee!==void 0?Gp({...Ee,crons:m,functions:q,httpRoutes:dt,modules:ft,queues:R,schema:l,services:ee,topics:ie,workflows:F}):void 0,Et=v(n,Av),Ar=K(Et),yr=e.dryRun?[]:xv(V,[{content:Ds,kind:"always",name:"app.ts"},{content:x,kind:"always",name:"dataModel.ts"},{content:hs,kind:"always",name:"api.ts"},{content:xs,kind:"always",name:"internal.ts"},{content:Z,kind:"always",name:"server.ts"},{content:Es,kind:"always",name:"functions.ts"},{files:vs,kind:"directory",name:ni},{content:Ns,kind:"always",name:"shard.ts"},{content:ks,kind:"always",name:"crons.ts"},{content:Rs,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:ws,kind:"optional",name:"containers.ts"},{content:Is,kind:"optional",name:"workflows.ts"},{content:Ts,kind:"optional",name:"agents.ts"},{content:Cs,kind:"optional",name:"queues.ts"},{content:Os,kind:"optional",name:"live.ts"},{content:vr,kind:"optional",name:"scheduler.ts"},{content:xr,kind:"optional",name:"shardRegistry.ts"},{content:Er,kind:"optional",name:"adminRevocations.ts"},{content:Sr,kind:"optional",name:"durableObjects.ts"},{content:Fs,kind:"optional",name:"seed.ts"},{content:Ls,kind:"optional",name:"authModule.ts"},{content:Ps,kind:"optional",name:"collections.ts"},{files:ms,kind:"services"},{content:ht?Ms:"",kind:"optional",name:"openapi.json"},{content:ht?_s:"",kind:"optional",name:"openapi.ts"},{content:vt?zs:"",kind:"optional",name:"openrpc.json"},{content:vt?Ks:"",kind:"optional",name:"openrpc.ts"},{content:Se===void 0?"":`${JSON.stringify(Se,void 0,2)}
31
31
  `,kind:"optional",name:"architecture.json"},{content:Se===void 0?"":Yp(Se),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!Ar&&Ce(Et,Ir(pt)),t){const p=St.now(),xt=Math.round(p-s),br=Math.round(bs-s),Nr=Math.round(p-bs);console.error(`@lunora/codegen: codegen took ${xt.toString()}ms (discovery ${br.toString()}ms, emit ${Nr.toString()}ms)`)}return{advisories:As,advisorContext:Re,agents:u,architecture:Se,containers:g,cronTriggers:[...new Set([...$a(m),...pe])],generated:{agents:Ts,api:hs,app:Ds,authModule:Ls,collections:Ps,containers:ws,crons:ks,dataModel:x,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:vs,functions:Es,internal:xs,live:Os,openApi:Ms,openApiModule:_s,openRpc:zs,openRpcModule:Ks,queues:Cs,seed:Fs,server:Z,shard:Ns,vectors:Rs,workflows:Is},migrations:Oe,outputDirectory:V,platformDiagnostics:Fe.diagnostic===void 0?L.diagnostics:[...L.diagnostics,Fe.diagnostic],queues:R,indexReferences:gr,schemaSnapshot:pt,schemaSnapshotPath:Et,schemaTables:l.tables,workflows:F,writtenFiles:yr}},WE=e=>Dr(()=>wv(e));export{Av as SCHEMA_SNAPSHOT_FILENAME,To as createCodegenProject,HE as findTsconfig,GE as refreshCodegenProject,WE as runCodegen,YE as tsconfigFingerprint};
@@ -0,0 +1 @@
1
+ import{SyntaxKind as g,Node as m,ts as D,Project as M}from"ts-morph";import{CAPABILITIES as u}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{descendantsOfKind as l,bindingKeyName as v,listLunoraSourceFiles as P}from"./isTestPath-DrszPMtU.mjs";import{scanImportDeclaration as A,noSandboxUsage as I}from"./discoverSandboxUsage-CSt29RbS.mjs";const f="ctx",L=(e,t,s)=>{for(const o of l(e,g.ElementAccessExpression)){const r=o.getArgumentExpression();t(o.getExpression())&&r!==void 0&&(m.isStringLiteral(r)||m.isNoSubstitutionTemplateLiteral(r))&&s.add(r.getLiteralValue())}},C=e=>{const t=new Set,s=new Set,o=new Set(l(e,g.Parameter).map(n=>n.getName())),r=l(e,g.VariableDeclaration).some(n=>{const c=n.getInitializer();return n.getName()===f&&m.isIdentifier(c)&&o.has(c.getText())});(o.has(f)||r)&&s.add(f);const i=n=>{if(m.isObjectBindingPattern(n))for(const c of n.getElements()){const d=v(c);d&&t.add(d)}};for(const n of l(e,g.BindingElement)){if(v(n)!==f)continue;const c=n.getNameNode();m.isIdentifier(c)?s.add(c.getText()):i(c)}const a=n=>m.isIdentifier(n)&&s.has(n.getText());for(const n of l(e,g.PropertyAccessExpression))a(n.getExpression())&&t.add(n.getName());L(e,a,t);for(const n of l(e,g.VariableDeclaration)){const c=n.getInitializer();c!==void 0&&a(c)&&i(n.getNameNode())}return t},V=e=>{if(e.isTypeOnly())return!0;if(m.isExportDeclaration(e)){const s=e.getNamedExports();return!e.isNamespaceExport()&&s.length>0&&s.every(o=>o.isTypeOnly())}const t=e.getNamedImports();return e.getDefaultImport()===void 0&&e.getNamespaceImport()===void 0&&t.length>0&&t.every(s=>s.isTypeOnly())},z=new Map(u.flatMap(({bindingFreeExports:e,moduleSpecifier:t})=>e===void 0?[]:[[t,new Set(e)]])),F=(e,t)=>{const s=z.get(t);if(s===void 0||m.isImportDeclaration(e)&&(e.getDefaultImport()!==void 0||e.getNamespaceImport()!==void 0))return!1;const o=m.isExportDeclaration(e)?e.getNamedExports():e.getNamedImports();return o.length>0&&o.every(r=>r.isTypeOnly()||s.has(r.getName()))},_=e=>{const t=new Set;for(const s of l(e,g.CallExpression)){const[o]=s.getArguments();s.getExpression().getKind()===g.ImportKeyword&&(m.isStringLiteral(o)||m.isNoSubstitutionTemplateLiteral(o))&&t.add(o.getLiteralValue())}return t},T="@lunora/agent",E="requestSecretTool",b=e=>e.startsWith("./")||e.startsWith("../"),S=e=>e.getAliasNode()?.getText()??e.getNameNode().getText(),h=(e,t)=>{const s=e!==void 0&&m.isCallExpression(e)?e.getExpression():e;return s!==void 0&&m.isIdentifier(s)&&t.has(s.getText())},k=e=>{const t=new Set;for(const s of e.getImportDeclarations())if(!(s.getModuleSpecifierValue()!==T||s.isTypeOnly()))for(const o of s.getNamedImports())!o.isTypeOnly()&&o.getNameNode().getText()===E&&t.add(S(o));for(const s of e.getVariableStatements())for(const o of s.getDeclarations())h(o.getInitializer(),t)&&t.add(o.getName());return t},p=e=>({names:new Set(e),namespaces:new Map}),x=new WeakMap,y=()=>{const e=Object.freeze({});return x.set(e,{projects:new Map,origins:new Map}),e},B=(e,t)=>{const s=x.get(e);if(s.origins.has(t))return t;let o=s.projects.get(t);return o===void 0&&(o=new M({compilerOptions:{...t.getCompilerOptions(),allowJs:!0},fileSystem:t.getFileSystem(),skipAddingFilesFromTsConfig:!0,skipFileDependencyResolution:!0,skipLoadingLibFiles:!0}),s.projects.set(t,o),s.origins.set(o,t)),o},O=(e,t,s)=>{const o=t.getSourceFile(),r=o.getProject(),i=x.get(e)?.origins.get(r)??r,{resolvedModule:a}=D.resolveModuleName(s,o.getFilePath(),i.getCompilerOptions(),i.getModuleResolutionHost()),n=a?.resolvedFileName;if(n===void 0)return;const c=i.getSourceFile(n)??r.getSourceFile(n);if(c!==void 0)return c;const d=B(e,r);return d.getSourceFile(n)??d.addSourceFileAtPath(n)},K=(e,t,s)=>{const o=e.getNamespaceExport();if(o!==void 0){const r=new Set(t.names);t.namespaces.forEach((i,a)=>{i.forEach(n=>{r.add(`${a}.${n}`)})}),r.size>0&&s.namespaces.set(o.getName(),r);return}if(!e.hasNamedExports()){t.names.forEach(r=>s.names.add(r)),t.namespaces.forEach((r,i)=>s.namespaces.set(i,r));return}for(const r of e.getNamedExports()){if(r.isTypeOnly())continue;const i=r.getNameNode().getText(),a=S(r);t.names.has(i)&&s.names.add(a);const n=t.namespaces.get(i);n!==void 0&&s.namespaces.set(a,n)}},W=(e,t,s,o)=>{const r=t.getModuleSpecifierValue();if(r===void 0)return p(s);if(r===T)return p([E]);const i=b(r)?O(e,t,r):void 0;return i===void 0?p([]):o(i)},w=(e,t,s)=>{const o=p([]),r=e.getFilePath();if(t.has(r))return o;t.add(r);const i=k(e);for(const a of e.getExportDeclarations())a.isTypeOnly()||K(a,W(s,a,i,n=>w(n,t,s)),o);for(const a of e.getVariableStatements())if(a.hasExportKeyword())for(const n of a.getDeclarations())h(n.getInitializer(),i)&&o.names.add(n.getName());return t.delete(r),o},j=(e,t,s)=>{const o=e.getModuleSpecifierValue();if(o===T)return p([E]);const r=b(o)?O(s,e,o):void 0;return r===void 0?p([]):w(r,new Set([t.getFilePath()]),s)},$=e=>{const t=e.getPropertyNameNode();return t===void 0?e.getName():m.isStringLiteral(t)?t.getLiteralValue():t.getText()},N=(e,t,s)=>{const o=(n,c)=>n===t?s.has(c):n.startsWith(`${t}.`)&&s.has(`${n.slice(t.length+1)}.${c}`),r=e.getDescendantsOfKind(g.PropertyAccessExpression).some(n=>o(n.getExpression().getText(),n.getName())),i=l(e,g.ElementAccessExpression).some(n=>{const c=n.getArgumentExpression();return m.isStringLiteral(c)&&o(n.getExpression().getText(),c.getLiteralValue())}),a=l(e,g.VariableDeclaration).some(n=>{const c=n.getInitializer(),d=n.getNameNode();return c!==void 0&&m.isObjectBindingPattern(d)&&d.getElements().some(R=>o(c.getText(),$(R)))});return r||i||a},q=(e,t,s)=>{if(s.names.has(t.getNameNode().getText()))return!0;const o=s.namespaces.get(t.getNameNode().getText());return o!==void 0&&N(e,S(t),o)},U=(e,t=y())=>e.getImportDeclarations().some(s=>{if(s.isTypeOnly())return!1;const o=j(s,e,t);if(o.names.size===0&&o.namespaces.size===0)return!1;const r=s.getDefaultImport(),i=s.getNamespaceImport();return r!==void 0&&(o.names.has("default")||N(e,r.getText(),o.namespaces.get("default")??new Set))||s.getNamedImports().some(n=>!n.isTypeOnly()&&q(e,n,o))||i!==void 0&&N(e,i.getText(),o.names)}),X=(e,t=y())=>{const s=e.getImportDeclarations(),o=I();for(const r of s){const i=A(r);for(const a of Object.keys(o))o[a]||=i[a]}return{contextReads:C(e),dynamicImports:_(e),requestSecretTool:U(e,t),sandboxTools:o,valueImports:new Set([...s,...e.getExportDeclarations()].flatMap(r=>{const i=r.getModuleSpecifierValue();return i===void 0||V(r)||F(r,i)?[]:[i]}))}},G=e=>{const t=new Set,s=new Set,o=I(),r=new Set;let i=!1;for(const a of e){i||=a.requestSecretTool;for(const n of a.contextReads)t.add(n);for(const n of a.dynamicImports)s.add(n);for(const n of a.valueImports)r.add(n);for(const n of Object.keys(o))o[n]||=a.sandboxTools[n]}return{contextReads:t,dynamicImports:s,requestSecretTool:i,sandboxTools:o,valueImports:r}},H=e=>new Set(u.filter(({contextProperty:t,moduleSpecifier:s})=>e.valueImports.has(s)||t!==void 0&&e.contextReads.has(t)).map(({key:t})=>t)),J=new RegExp(String.raw`\b${f}\b`,"u"),Q=new RegExp(String.raw`\b(?:${u.flatMap(({contextProperty:e})=>e===void 0?[]:[e]).join("|")})\b`,"u"),se=e=>J.test(e)&&Q.test(e),oe=(e,t)=>{const s=y(),o=G(P(t).map(i=>X(e.getSourceFile(i)??e.addSourceFileAtPath(i),s))),r=H(o);return Object.fromEntries(u.map(({key:i})=>[i,r.has(i)]))};export{H as capabilitiesUsedBy,C as contextPropertiesRead,y as createTargetScope,oe as discoverFeatureUsage,U as fileWiresRequestSecretTool,G as foldCapabilitySignals,se as mayReadCapabilityContext,X as sourceCapabilitySignals};
@@ -1 +1 @@
1
- import"./declared-output-Iaar469J.mjs";import"./isTestPath-DrszPMtU.mjs";import"./attribution-7Qs8xFmy.mjs";import"./unwrap-handler-return-X7HuBhd5.mjs";import"./ip-reads-CAzOWzOH.mjs";import"./classify-procedure-call-D7XTLd8w.mjs";import{d as f}from"./index-DzO8JT7M.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
1
+ import"./declared-output-Iaar469J.mjs";import"./isTestPath-DrszPMtU.mjs";import"./attribution-7Qs8xFmy.mjs";import"./unwrap-handler-return-X7HuBhd5.mjs";import"./ip-reads-CAzOWzOH.mjs";import"./classify-procedure-call-D7XTLd8w.mjs";import{d as f}from"./index-DuvSMZEy.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as d}from"ts-morph";import{listLunoraSourceFiles as m,lunoraRelativePath as g,handlerOf as u,descendantsOfKind as l}from"./isTestPath-DrszPMtU.mjs";import{j as N,h as x}from"./attribution-7Qs8xFmy.mjs";import{c as p}from"./classify-procedure-call-D7XTLd8w.mjs";const h={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},E=new Set(["globalThis","self"]),v=new Set(["globalThis","self","window"]),I=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&v.has(t.getText()))return e.getName()}},S=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=I(t.getExpression());if(i!==void 0)return n==="fetch"&&E.has(i)?"fetch":h[`${i}.${n}`]},T=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},y=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=p(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=u(t,n.receiver);return i?{exportName:x(e)??e.getName(),handler:i,kind:n.kind}:void 0},L=e=>{const t=new Set(["ctx"]),n=r=>{if(s.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getNameNode().getText(),f=a.getNameNode();c==="ctx"&&s.isIdentifier(f)&&t.add(f.getText())}},[i]=s.isParametered(e)?e.getParameters():[],o=i!==void 0&&s.isIdentifier(i.getNameNode())?i.getNameNode().getText():void 0;if(i!==void 0){const r=i.getNameNode();s.isIdentifier(r)?t.add(r.getText()):n(r)}for(const r of l(e,d.VariableDeclaration)){const a=r.getInitializer();o!==void 0&&a!==void 0&&s.isIdentifier(a)&&a.getText()===o&&n(r.getNameNode())}return t},P=(e,t,n)=>{const i=e.getExpression();if(!s.isPropertyAccessExpression(i)||i.getName()!=="random")return!1;const o=i.getExpression();return!s.isIdentifier(o)||!t.has(o.getText())?!1:o.getSymbol()?.getDeclarations()[0]?.getFirstAncestor(c=>s.isFunctionLikeDeclaration(c))===n},w=(e,t)=>{const n=[],i=L(e.handler);for(const o of l(e.handler,d.CallExpression)){const r=e.kind==="query"&&P(o,i,e.handler)?"ctx.random":S(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}for(const o of l(e.handler,d.NewExpression)){const r=T(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}return n},O=(e,t)=>{const n=[];for(const i of N(e)){const o=y(i);o&&n.push(...w(o,t))}return n},A=(e,t)=>{const n=[];for(const i of m(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...O(o,g(t,i)))}return n};export{A as default};
@@ -1 +1 @@
1
- import"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{e}from"./server-Box8pDwi.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
1
+ import"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{e}from"./server-C4h6-BZx.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DXVp_Iht.mjs";import"./shard-runtime-BHljpfS5.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-DKSPraAt.mjs";import"./shard-runtime-BHljpfS5.mjs";import"./shared-DhqnD5R3.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-DrszPMtU.mjs";import{e as K,i as S}from"./attribution-7Qs8xFmy.mjs";import{u as R,p as q,r as Y,c as O,a as G}from"./unwrap-handler-return-X7HuBhd5.mjs";import{m as J}from"./ip-reads-CAzOWzOH.mjs";import{b as N,s as X,c as Q}from"./classify-procedure-call-D7XTLd8w.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./static-literal-BwDHHjEJ.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const w=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=w(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?w(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of N(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=N(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},A=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},I=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=A(t,"scope"),o=I(t,"maxAge"),r=I(t,"staleWhileRevalidate"),a=A(t,"tag"),l=A(t,"vary"),c={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=N(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=N(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},p=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},x=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return p(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return p(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return p(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=x(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return p(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return p(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return p(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return p(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():p(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=x(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?p(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=x(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?p(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return p(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return p(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),b=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=b(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},tt=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(d=>U(d.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(d=>be(d)))continue;const c=n.getName(),u=a.map(d=>d.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${c} ships functions (${u}) that nothing re-exports, so none is in the generated api. Add \`export const { ${u} } = ${c}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,E=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:v(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},v=(e,i,t)=>{if(t>Ae)return E(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?b(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?E(e,i):{inner:v(a,i,t+1),kind:"array"}}return Te(e,i,t)??E(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(c=>c.isBooleanLiteral()).map(c=>c.getText(i))).size===Ee.size,r=e.filter(c=>!(o&&c.isBooleanLiteral())).map(c=>v(c,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[l]=a;return a.length===1&&l!==void 0?l:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(c=>!c.isUndefined());if(!i&&r.length===o.length)return v(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?v(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const l=b(o,"lifecycle",e),c=o.getProperty("lifecycle");if(l===void 0&&c!==void 0&&!c.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(l!==void 0){if(!Ne.has(l))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${l}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:l,returnType:"void",visibility:"internal"}}const u=b(o,"visibility",e);if(u!=="internal"&&u!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(u==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const d=o.getProperty("args")?.getTypeAtLocation(e);if(d===void 0||d.isAny()||d.isUnknown()||d.getStringIndexType()!==void 0||d.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const f=Object.fromEntries(d.getProperties().map(m=>[m.getName(),xe(m.getTypeAtLocation(e),e)]));return{...a,args:f,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:u}},ke=8,L=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return L(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?P(t,i+1):void 0},P=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?L(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?P(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?P(r,i+1):void 0}return{deadEnd:e}},T=e=>{const i=L(e);return i!==void 0&&"call"in i?i.call:void 0},k=e=>{const i=L(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(l=>i(l.getName()))){const l=T(a.getNameNode());l&&r.push([a.getName(),l])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:T(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&k(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&k(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(c=>s.isSpreadAssignment(c)||s.isPropertyAssignment(c)&&s.isComputedPropertyName(c.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const l=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(l===void 0||!(s.isTrueLiteral(l)||s.isFalseLiteral(l)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(l),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),l=O(()=>ae(i)),c=O(()=>oe(e)),u=z({kind:t.kind,output:l.value});return G(u?l.erased:c.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...l.value?{output:l.value}:{},returnType:c.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),_=(e,i)=>V(e.getVariableStatements().find(t=>t.isExported()&&t.getDeclarations().some(n=>n.getName()===i))),j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},je=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=T(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},Be=(e,i,t)=>{const n=K(e),o=new Map,r=(c,u)=>{if(c?.channel?.kind!=="room")return;const d=o.get(c.channel.name);if(d!==void 0&&d!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${c.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);o.set(c.channel.name,u)},a=e.getVariableStatements().flatMap(c=>c.getDeclarations()).flatMap(c=>_e(c,u=>n.has(u))).flatMap(([c,u])=>(n.get(c)??[]).filter(d=>S(d)).flatMap(d=>{const f=j(u,d,i,t,_(e,d));return r(f,u),f?[f]:[]})),l=new Set(a.map(c=>c.exportName));for(const c of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,d]of Re(c,f=>n.has(f)))for(const f of(n.get(u)??[]).filter(m=>S(m)&&!l.has(m))){const m=Ie(d,f,i,_(e,f));m&&(a.push(m),l.add(f))}for(const{call:c,entry:u}of je(e,i,t))l.has(u.exportName)||(r(u,c),a.push(u));return a},ze=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},He=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". 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:[o,t.filePath],status:500});i.set(n,t.filePath)}},it=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),l=W(i,r);o.push(...Be(a,l,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),He(o),ze(o),o};export{it as d,w as i,ne as p,tt as w};
1
+ import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-DrszPMtU.mjs";import{e as K,i as O}from"./attribution-7Qs8xFmy.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-X7HuBhd5.mjs";import{m as J}from"./ip-reads-CAzOWzOH.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-D7XTLd8w.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./static-literal-BwDHHjEJ.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". 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:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
@@ -1,10 +1,10 @@
1
- import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as N,u as Ke,d as Ue}from"./shared-DhqnD5R3.mjs";import{p as Je}from"./platform-8oj7iXQy.mjs";const me=/(?:\.d)?\.([cm]?)tsx?$/u,ze=t=>t.replace(me,".d.$1ts"),ye=(t,o)=>{const a=y(t,o).split(ue).join("/").replace(me,".$1js");return a.startsWith(".")?a:`./${a}`},he=t=>t.replaceAll("\\","/"),Y=(t,o,a)=>he(h(t,ze(y(o,a)))),Ye=t=>ye(".",h("services",t.name,y(d(t.wranglerPath),t.main))),Xe=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},T=t=>{const{mtimeMs:o,size:a}=Le(t);return`${String(o)}:${String(a)}`},Ze=new Set([".git",".wrangler","dist","node_modules","target"]),fe=t=>de(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${ce(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${T(a)}`,...fe(a)]:[]}),be=t=>[`${t}:${T(t)}`,...fe(t)],ge=t=>{const o=h(t,"node_modules"),a=D(o)?be(o):[],e=d(t);return e===t?a:[...a,...ge(e)]},et=(t,o)=>{const a=[];try{const e=s=>{for(const n of de(s,{withFileTypes:!0})){const l=h(s,n.name);if(l!==o)if(n.isSymbolicLink())a.push(`${l}->${ce(l)}`);else if(n.isDirectory()){if(n.name==="node_modules")a.push(...be(l));else if(!Ze.has(n.name)){if(!qe(l).isDirectory())throw new Error(`${l} changed during the scan`);e(l)}}else a.push(`${l}:${T(l)}`)}};e(t),a.push(...ge(t))}catch{return}return[...new Set(a)].toSorted((e,s)=>e.localeCompare(s)).join(`
1
+ import{CAPABILITIES as Qe}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{existsSync as D,readdirSync as de,readlinkSync as ce,lstatSync as qe,statSync as Le}from"node:fs";import{join as h,relative as y,dirname as d,sep as ue,isAbsolute as _e,resolve as Ve,basename as Ge}from"node:path";import{ts as c,Project as He}from"ts-morph";import{G as pe,a as C,u as Ke,d as Ue}from"./shared-DhqnD5R3.mjs";import{p as Je}from"./platform-8oj7iXQy.mjs";const me=/(?:\.d)?\.([cm]?)tsx?$/u,ze=t=>t.replace(me,".d.$1ts"),ye=(t,o)=>{const a=y(t,o).split(ue).join("/").replace(me,".$1js");return a.startsWith(".")?a:`./${a}`},he=t=>t.replaceAll("\\","/"),Y=(t,o,a)=>he(h(t,ze(y(o,a)))),Ye=t=>ye(".",h("services",t.name,y(d(t.wranglerPath),t.main))),Xe=t=>{const o=[],a=e=>{(c.isImportDeclaration(e)||c.isExportDeclaration(e))&&e.moduleSpecifier!==void 0&&c.isStringLiteral(e.moduleSpecifier)?o.push(e.moduleSpecifier):c.isImportTypeNode(e)&&c.isLiteralTypeNode(e.argument)&&c.isStringLiteral(e.argument.literal)&&o.push(e.argument.literal),c.forEachChild(e,a)};return a(t),o},T=t=>{const{ctimeMs:o,mtimeMs:a,size:e}=Le(t);return`${String(a)}:${String(o)}:${String(e)}`},Ze=new Set([".git",".wrangler","dist","node_modules","target"]),fe=t=>de(t,{withFileTypes:!0}).flatMap(o=>{const a=h(t,o.name);return o.isSymbolicLink()?[`${a}->${ce(a)}`]:o.isDirectory()&&o.name.startsWith("@")?[`${a}:${T(a)}`,...fe(a)]:[]}),be=t=>[`${t}:${T(t)}`,...fe(t)],ge=t=>{const o=h(t,"node_modules"),a=D(o)?be(o):[],e=d(t);return e===t?a:[...a,...ge(e)]},et=(t,o)=>{const a=[];try{const e=s=>{for(const n of de(s,{withFileTypes:!0})){const l=h(s,n.name);if(l!==o)if(n.isSymbolicLink())a.push(`${l}->${ce(l)}`);else if(n.isDirectory()){if(n.name==="node_modules")a.push(...be(l));else if(!Ze.has(n.name)){if(!qe(l).isDirectory())throw new Error(`${l} changed during the scan`);e(l)}}else a.push(`${l}:${T(l)}`)}};e(t),a.push(...ge(t))}catch{return}return[...new Set(a)].toSorted((e,s)=>e.localeCompare(s)).join(`
2
2
  `)},tt=t=>Ge(d(t)).startsWith("@")?d(d(t)):d(t),se=(t,o)=>!y(o,t).startsWith("..")&&!t.split(ue).includes("node_modules"),ie=(t,o)=>{const a=[];let e=t;for(;e!==d(e)&&!D(h(e,"package.json"));)a.push(e),e=d(e);if(D(h(e,"package.json"))){for(const s of[...a,e,h(e,"package.json")])o.add(s);return e}},at=(t,o,a)=>{let e=t;for(;y(e,o).startsWith("..")&&e!==d(e);)a.add(e),e=d(e);a.add(e)},rt=(t,o)=>{const a=new Set;t.some(e=>se(e,o))&&ie(o,a);for(const e of t){if(se(e,o)){for(let n=d(e);n!==o&&n!==d(n);n=d(n))a.add(n);continue}const s=ie(d(e),a);s===void 0?at(d(e),o,a):a.add(tt(s))}return[...a].map(e=>[e,T(e)])},xe=new Map,le=([t,o])=>{try{return T(t)===o}catch{return!1}},ot=(t,o,a)=>{const e=xe.get(t);return e?.optionsKey===o&&e.stamps.every(n=>le(n))&&e.directories.every(n=>le(n))&&a!==void 0&&e.tree===a?e.files:void 0},nt=(t,o,a)=>{const e=[...o.stamps,...o.directories].every(([,s])=>Math.floor(Number.parseFloat(s))<=a);o.tree!==void 0&&e&&xe.set(t,{...o,tree:o.tree})},st=(t,o)=>({directories:rt(o,t),stamps:o.map(a=>[a,T(a)])}),ht=(t,o)=>{const a=d(t.wranglerPath),e=y(a,t.main);if(e.startsWith("..")||_e(e))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const s=h(o,"services",t.name),n=c.findConfigFile(a,i=>c.sys.fileExists(i)),l=new He({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:s,rootDir:a},skipAddingFilesFromTsConfig:!0,...n===void 0?{}:{tsConfigFilePath:n}}),m=JSON.stringify([t.name,t.main,t.wranglerPath,o]),v=JSON.stringify(l.getCompilerOptions()),w=et(a,Ve(o)),g=ot(m,v,w);if(g!==void 0)return g;const A=Date.now();l.addSourceFileAtPath(t.main),l.resolveSourceFileDependencies();const $=l.getProgram().compilerObject.getSourceFiles().map(i=>i.fileName).filter(i=>D(i)),{directories:F,stamps:S}=st(a,$),u={...l.getCompilerOptions(),preserveSymlinks:!0},O=new Map(l.getSourceFiles().map(i=>i.getFilePath()).filter(i=>!i.endsWith(".d.ts")&&!y(a,i).startsWith("..")).map(i=>[Y(s,a,i),i])),f={};for(const i of l.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const B=O.get(he(i.filePath));if(B===void 0)continue;const R=c.createSourceFile(i.filePath,i.text,c.ScriptTarget.Latest,!1);let{text:b}=i;for(const k of Xe(R).toReversed()){const x=c.resolveModuleName(k.text,B,u,c.sys).resolvedModule?.resolvedFileName;if(x===void 0)continue;const I=Y(s,a,x),W=O.has(I)?I:x;b=`${b.slice(0,k.getStart(R))}${JSON.stringify(ye(d(i.filePath),W))}${b.slice(k.getEnd())}`}f[y(o,i.filePath)]=`${pe}${b}`}if(f[y(o,Y(s,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return nt(m,{files:f,optionsKey:v,directories:F,stamps:S,tree:w},A),f},it=(t,o=[])=>{const a=new Set;for(const e of t.tables)for(const s of Object.values(e.shape)){const n=Ke(s);n.kind==="storage"&&typeof n.bucket=="string"&&n.bucket!==""&&a.add(n.bucket)}for(const e of o)e!==""&&e!=="default"&&a.add(e);return["default",...[...a].toSorted((e,s)=>e.localeCompare(s))]},ft=({agents:t=[],capabilities:o=new Set,containers:a=[],env:e,hasVectors:s=!0,hasFlags:n=!1,hasNotify:l=!1,identity:m,queues:v=[],schema:w,services:g=[],storageRuleBuckets:A=[],topics:$=[],useUmbrella:F=!1,workflows:S=[]}={})=>{const u=Ue(F),O=it(w??{tables:[]},A).map(r=>JSON.stringify(r)).join(" | "),f=r=>r.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",i=[...new Set(a.map(r=>f(r)))].toSorted((r,p)=>r.localeCompare(p)),B=a.length>0?`import type { ${i.join(", ")} } from "@lunora/container";
3
3
  `:"",R=a.length>0?`
4
4
  readonly containers: {${a.map(r=>`
5
5
  readonly ${r.exportName}: ${f(r)};`).join("")}
6
- };`:"",b=[...o.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...a.map(r=>(N(r.bindingName,`container binding "${r.bindingName}"`),` /** Durable Object namespace for the \`${r.exportName}\` container. */
7
- readonly ${r.bindingName}?: unknown;`)),...v.map(r=>(N(r.bindingName,`queue binding "${r.bindingName}"`),` /** Queue producer binding for the \`${r.exportName}\` queue. */
6
+ };`:"",b=[...o.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...a.map(r=>(C(r.bindingName,`container binding "${r.bindingName}"`),` /** Durable Object namespace for the \`${r.exportName}\` container. */
7
+ readonly ${r.bindingName}?: unknown;`)),...v.map(r=>(C(r.bindingName,`queue binding "${r.bindingName}"`),` /** Queue producer binding for the \`${r.exportName}\` queue. */
8
8
  readonly ${r.bindingName}?: unknown;`))].join(`
9
9
  `),k=`
10
10
 
@@ -24,9 +24,9 @@ ${b}`:""}
24
24
  }
25
25
 
26
26
  /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
27
- export type Env = CloudflareBindings;`,x=r=>Qe.map(p=>p.tier!==void 0&&r.includes(p.tier)&&o.has(p.key)?p.serverCtxField:"").join(""),I=x(["every"]),W=x(["every","action"]),M=s&&(w?.vectorIndexes.length??0)>0,P=M?' | "vectors"':"",X=M?`
28
- readonly vectors: VectorSearch<VectorIndexName>;`:"",Te=M?`
29
- readonly vectors: VectorSearchReader<VectorIndexName>;`:"",ve=M?`import type { VectorSearch, VectorSearchReader } from "${u.server}";
27
+ export type Env = CloudflareBindings;`,x=r=>Qe.map(p=>p.tier!==void 0&&r.includes(p.tier)&&o.has(p.key)?p.serverCtxField:"").join(""),I=x(["every"]),W=x(["every","action"]),N=s&&(w?.vectorIndexes.length??0)>0,P=N?' | "vectors"':"",X=N?`
28
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",Te=N?`
29
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",ve=N?`import type { VectorSearch, VectorSearchReader } from "${u.server}";
30
30
  import type { VectorIndexName } from "./dataModel.js";
31
31
  `:"",j=n?`
32
32
  /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
@@ -34,9 +34,9 @@ import type { VectorIndexName } from "./dataModel.js";
34
34
  /** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
35
35
  readonly notify: import("@lunora/notify").LunoraNotify;
36
36
  /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
37
- readonly push: import("@lunora/notify").LunoraPush;`:"",C=S.length>0,we=C?`import type { WorkflowHandle } from "@lunora/workflow";
37
+ readonly push: import("@lunora/notify").LunoraPush;`:"",M=S.length>0,we=M?`import type { WorkflowHandle } from "@lunora/workflow";
38
38
  import type * as lunoraWorkflowDefinitions from "../workflows.js";
39
- `:"",$e=C?`
39
+ `:"",$e=M?`
40
40
 
41
41
  /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
42
42
  type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
@@ -49,7 +49,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
49
49
  export interface LunoraWorkflows {
50
50
  ${S.map(r=>` get(name: ${JSON.stringify(r.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${r.exportName}>>;`).join(`
51
51
  `)}
52
- }`:"",Z=C?' | "workflows"':"",ee=C?`
52
+ }`:"",Z=M?' | "workflows"':"",ee=M?`
53
53
  readonly workflows: LunoraWorkflows;`:"",Q=Je(v),q=Q.length>0,L=$.length>0,_=[...q?["QueueProducer"]:[],...L?["TopicPublisher"]:[]],te=[...new Set([...Q,...$].map(r=>r.filePath))].toSorted((r,p)=>+(p==="queues")-+(r==="queues")||r.localeCompare(p)),V=r=>r==="queues"?"lunoraQueueDefinitions":`lunoraQueueDefinitions${String(te.indexOf(r))}`,ke=_.length>0?`import type { ${_.join(", ")} } from "@lunora/queue";
54
54
  ${te.map(r=>`import type * as ${V(r)} from "../${r}.js";
55
55
  `).join("")}`:"",Ie=_.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",Se=q?`
@@ -66,21 +66,21 @@ ${$.map(r=>` readonly ${r.exportName}: TopicPublisher<QueueBodyOf<typeof ${V(
66
66
  `)}
67
67
  }`:"",Be=`${Ie}${Se}${Oe}`,ae=q?`
68
68
  readonly queues: LunoraQueues;`:"",re=L?`
69
- readonly topics: LunoraTopics;`:"",G=g.length>0,oe=g.filter(r=>r.rpcEntrypoint!==void 0),Re=oe.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",Me=G?`import type { ${Re} } from "${u.server}";
69
+ readonly topics: LunoraTopics;`:"",G=g.length>0,oe=g.filter(r=>r.rpcEntrypoint!==void 0),Re=oe.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",Ne=G?`import type { ${Re} } from "${u.server}";
70
70
  ${oe.map(r=>`import type * as lunoraService_${r.name} from ${JSON.stringify(Ye(r))};
71
- `).join("")}`:"",Ce=G?`
71
+ `).join("")}`:"",Me=G?`
72
72
 
73
73
  /** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
74
74
  export interface LunoraServices {
75
- ${g.map(r=>{N(r.name,`service "${r.name}"`);const p=r.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${r.name}.${r.rpcEntrypoint}>`;return` readonly ${r.name}: ${p};`}).join(`
75
+ ${g.map(r=>{C(r.name,`service "${r.name}"`);const p=r.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${r.name}.${r.rpcEntrypoint}>`;return` readonly ${r.name}: ${p};`}).join(`
76
76
  `)}
77
- }`:"",Ne=G?`
77
+ }`:"",Ce=G?`
78
78
  readonly services: LunoraServices;`:"",H=t.length>0,De=H?`import type { AgentHandle } from "@lunora/agent/core";
79
79
  `:"",Ae=H?`
80
80
 
81
81
  /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
82
82
  export interface LunoraAgents {
83
- ${t.map(r=>(N(r.exportName,`agent export "${r.exportName}"`),` readonly ${r.exportName}: AgentHandle;`)).join(`
83
+ ${t.map(r=>(C(r.exportName,`agent export "${r.exportName}"`),` readonly ${r.exportName}: AgentHandle;`)).join(`
84
84
  `)}
85
85
  }`:"",ne=H?`
86
86
  readonly agents: LunoraAgents;`:"",Fe=m?`import type { InferIdentity } from "${u.server}";
@@ -153,7 +153,7 @@ export type {
153
153
  } from "${u.serverDataModel}";
154
154
 
155
155
  import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
156
- ${ve}${B}${we}${ke}${Me}${De}${Fe}${je}
156
+ ${ve}${B}${we}${ke}${Ne}${De}${Fe}${je}
157
157
  export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
158
158
 
159
159
  /**
@@ -206,14 +206,14 @@ export interface OrmReader {
206
206
 
207
207
  /** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
208
208
  export interface OrmWriter extends OrmReader {
209
- delete: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => Promise<void>;
209
+ delete: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => Promise<void>;
210
210
  insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
211
- replace: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmReplaceBuilder<T>;
212
- update: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmUpdateBuilder<T>;
211
+ replace: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => OrmReplaceBuilder<T>;
212
+ update: <T extends keyof DataModel>(table: T, id: NoInfer<IdOfTable<T>>) => OrmUpdateBuilder<T>;
213
213
  }
214
214
 
215
215
  /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
216
- export type StorageBucketName = ${O};${k}${$e}${Be}${Ce}${Ae}${We}${Ee}
216
+ export type StorageBucketName = ${O};${k}${$e}${Be}${Me}${Ae}${We}${Ee}
217
217
 
218
218
  /**
219
219
  * Project-typed contexts. The base contexts from \`@lunora/server\` are
@@ -249,7 +249,7 @@ type TypedTableQuery = (<T extends TableName>(
249
249
  * fixes \`T\`, so the id must be an \`Id<T>\` and the resolved document is typed
250
250
  * \`Doc<T>\` (or \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
251
251
  */
252
- type TypedTableGet = <T extends TableName>(table: T, id: IdOfTable<T>) => Promise<Doc<T> | null>;
252
+ type TypedTableGet = <T extends TableName>(table: T, id: NoInfer<IdOfTable<T>>) => Promise<Doc<T> | null>;
253
253
 
254
254
  /**
255
255
  * Resolves the \`asId\` table argument: a literal in {@link TableName} passes through, a
@@ -291,7 +291,7 @@ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${P}$
291
291
  export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${P}${Z}${K}${J}> {
292
292
  readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
293
293
  readonly orm: OrmWriter;
294
- readonly storage: StorageBase<StorageBucketName>;${X}${W}${R}${j}${E}${Ne}${z}${ee}${ae}${re}${ne}${U}
294
+ readonly storage: StorageBase<StorageBucketName>;${X}${W}${R}${j}${E}${Ce}${z}${ee}${ae}${re}${ne}${U}
295
295
  }
296
296
 
297
297
  /**
@@ -234,9 +234,9 @@ ${g()}
234
234
  await applyCdcChanges(writer, args.changes);
235
235
 
236
236
  return { applied: args.changes.length };
237
- }`,$r=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,agentsSchedulerSource:n,containersBuild:a,containersContextField:i,databaseOptions:u,everyContextBuild:h,everyContextField:m,facadeBlock:S,globalDatabaseLine:v,hasSensitiveArgs:R=!1,lazyFunctions:d=!1,notifyBuild:x,ormContextField:A,paymentsBuild:O,paymentsContextField:B,queuesBuild:j,queuesContextField:k,topicsBuild:W,topicsContextField:c,vectorsBuild:b,vectorsContextField:L,workflowsBuild:K,workflowsContextField:H})=>{const D=t.length>0,P=A===""?"{ db }":"{ db, orm: bindOrm(facade) }",V=A===""?"":`
237
+ }`,$r=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,agentsSchedulerSource:n,containersBuild:a,containersContextField:i,databaseOptions:u,everyContextBuild:h,everyContextField:m,facadeBlock:S,globalDatabaseLine:v,hasSensitiveArgs:R=!1,lazyFunctions:d=!1,notifyBuild:x,ormContextField:A,paymentsBuild:O,paymentsContextField:B,queuesBuild:j,queuesContextField:k,topicsBuild:W,topicsContextField:c,vectorsBuild:b,vectorsContextField:C,workflowsBuild:K,workflowsContextField:H})=>{const D=t.length>0,L=A===""?"{ db }":"{ db, orm: bindOrm(facade) }",V=A===""?"":`
238
238
  orm: databaseContext.orm,`,G=A===""?"":`
239
- orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,N=D?`
239
+ orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,P=D?`
240
240
  // ActionCtx-only helpers (external, non-deterministic I/O): constructed
241
241
  // and attached only for an \`action\` so query/mutation ctx never carry them.
242
242
  if (isAction) {
@@ -415,7 +415,7 @@ ${v} // \`ctx.db\`, wrapped in automatic instrumentation: by default
415
415
  // mutation must rebuild its DB and table/ORM views with its own queue.
416
416
  const makeDatabaseContext = (scheduler: SchedulerLike) => {
417
417
  const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${u}), logFunctionPath, traceAnchor, observability, options.sensitive);
418
- ${S} return ${P};
418
+ ${S} return ${L};
419
419
  };
420
420
  const databaseContext = makeDatabaseContext(scheduler);
421
421
  const db = databaseContext.db;
@@ -509,11 +509,11 @@ ${x}
509
509
  scheduler,
510
510
  span,
511
511
  storage: contextStorage,
512
- trace,${L}${m}${B}${i}${H}${k}${c}${o}${R?`
512
+ trace,${C}${m}${B}${i}${H}${k}${c}${o}${R?`
513
513
  [Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
514
514
  };
515
515
  ${D?` const isAction = contextKind === "action";
516
- `:""}${N}
516
+ `:""}${P}
517
517
  ${d?` const captureScope = (): (() => void) => {
518
518
  const requestScope = this.captureRequestScope();
519
519
  return () => this.restoreRequestScope(requestScope);
@@ -698,7 +698,7 @@ const dispatchRun = async (
698
698
  } finally {
699
699
  runDepth -= 1;
700
700
  }
701
- };`,Mr=r=>r?ge.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
701
+ };`,qr=r=>r?ge.replace(" runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,",` runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
702
702
  captureScope?: () => () => void,`).replace(` try {
703
703
  // A mutation composed from an action`,` try {
704
704
  let loaded = getLoadedFunction(functionPath);
@@ -719,7 +719,7 @@ const dispatchRun = async (
719
719
 
720
720
  const loadedFunction = loaded;
721
721
 
722
- // A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ge,qr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark, sensitive?: SensitiveScope): Promise<unknown> {
722
+ // A mutation composed from an action`).replaceAll("registered.handler","loadedFunction.handler"):ge,Mr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark, sensitive?: SensitiveScope): Promise<unknown> {
723
723
  // A dispatch that did not come through the shard's \`/rpc\` (a scheduled call,
724
724
  // a lifecycle hook, an admin run) has no scope of its own, so it opens one here
725
725
  // and releases it when the handler settles.
@@ -1008,7 +1008,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
1008
1008
  `:"",a=e?` const configured = config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
1009
1009
  return configured === undefined ? undefined : withAgentScheduleShard(configured, LUNORA_AGENTS, this.currentShardKey());
1010
1010
  `:` return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
1011
- `;return qr.replace("__COMMITTED_CATCH__",r?Fr:"").replace("__PREPARE_FUNCTION__",`${o}${n}`).replace("__OUTBOX_SCHEDULER__",a)},jr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,a]of Object.entries(e.shape)){const i=F(a);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},Wr=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,a]of Object.entries(e.shape))F(a).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Kr=r=>{const t={};for(const e of r.tables){const o=[...e.indexes.map(n=>({fields:[...n.fields],name:n.name,type:"index",...n.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(n=>({fields:[n.field,...n.filterFields??[]],name:n.name,type:"search"})),...(e.geoIndexes??[]).map(n=>({fields:[n.field],name:n.name,type:"geo"})),...e.rankIndexes.map(n=>({fields:n.sortBy.map(a=>a.field),name:n.name,type:"rank"})),...e.vectorIndexes.map(n=>({fields:n.field===void 0?[]:[n.field],name:n.name,type:"vector"}))];o.length>0&&(t[e.name]=o)}return t},Hr=r=>{const t=[];for(const e of r.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Vr=r=>{if(r.kind!=="union"||r.members===void 0||r.members.length===0)return;const t=[];for(const e of r.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const o=JSON.parse(e.literalValue);if(typeof o!="string")return;t.push(o)}catch{return}}return t},Gr=new Set(["bigint","boolean","date","number","timestamp"]),Qr=r=>{const[t,e]=r.kind==="union"?r.members??[]:[];if(t===void 0||e===void 0||r.members?.length!==2)return;const o=a=>a.kind==="null"||a.kind==="literal"&&a.literalValue==="null",n=F(o(e)?t:e);return o(t)!==o(e)&&Gr.has(n.kind)?n:void 0},zr=(r,t,e)=>{const o=F(t),n=Qr(o),a=n??o,i={name:r,optional:xr(t),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){i.ref=a.tableName;const h=e.get(r);h!==void 0&&(i.onDelete=h)}a.kind==="storage"&&(i.isStorage=!0,a.bucket!==void 0&&(i.bucket=a.bucket));const u=Vr(a);return u!==void 0&&(i.enumValues=u),(a.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Jr=r=>{const t={};for(const e of r.tables){const o=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],n=new Map(e.relations.flatMap(a=>a.kind==="one"?[[a.field,a.onDelete]]:[]));for(const[a,i]of Object.entries(e.shape))o.push(zr(a,i,n));t[e.name]=o}return t},Yr=({hasMutators:r,hasSensitiveShapes:t,hasShapes:e,rlsData:o})=>{const n="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",a=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {
1011
+ `;return Mr.replace("__COMMITTED_CATCH__",r?Fr:"").replace("__PREPARE_FUNCTION__",`${o}${n}`).replace("__OUTBOX_SCHEDULER__",a)},jr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,a]of Object.entries(e.shape)){const i=F(a);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},Wr=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,a]of Object.entries(e.shape))F(a).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Kr=r=>{const t={};for(const e of r.tables){const o=[...e.indexes.map(n=>({fields:[...n.fields],name:n.name,type:"index",...n.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(n=>({fields:[n.field,...n.filterFields??[]],name:n.name,type:"search"})),...(e.geoIndexes??[]).map(n=>({fields:[n.field],name:n.name,type:"geo"})),...e.rankIndexes.map(n=>({fields:n.sortBy.map(a=>a.field),name:n.name,type:"rank"})),...e.vectorIndexes.map(n=>({fields:n.field===void 0?[]:[n.field],name:n.name,type:"vector"}))];o.length>0&&(t[e.name]=o)}return t},Hr=r=>{const t=[];for(const e of r.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Vr=r=>{if(r.kind!=="union"||r.members===void 0||r.members.length===0)return;const t=[];for(const e of r.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const o=JSON.parse(e.literalValue);if(typeof o!="string")return;t.push(o)}catch{return}}return t},Gr=new Set(["bigint","boolean","date","number","timestamp"]),Qr=r=>{const[t,e]=r.kind==="union"?r.members??[]:[];if(t===void 0||e===void 0||r.members?.length!==2)return;const o=a=>a.kind==="null"||a.kind==="literal"&&a.literalValue==="null",n=F(o(e)?t:e);return o(t)!==o(e)&&Gr.has(n.kind)?n:void 0},zr=(r,t,e)=>{const o=F(t),n=Qr(o),a=n??o,i={name:r,optional:xr(t),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){i.ref=a.tableName;const h=e.get(r);h!==void 0&&(i.onDelete=h)}a.kind==="storage"&&(i.isStorage=!0,a.bucket!==void 0&&(i.bucket=a.bucket));const u=Vr(a);return u!==void 0&&(i.enumValues=u),(a.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Jr=r=>{const t={};for(const e of r.tables){const o=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],n=new Map(e.relations.flatMap(a=>a.kind==="one"?[[a.field,a.onDelete]]:[]));for(const[a,i]of Object.entries(e.shape))o.push(zr(a,i,n));t[e.name]=o}return t},Yr=({hasMutators:r,hasSensitiveShapes:t,hasShapes:e,rlsData:o})=>{const n="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",a=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {
1012
1012
  const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
1013
1013
 
1014
1014
  try {
@@ -1167,6 +1167,10 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(h)}, (schema as
1167
1167
  return undefined;
1168
1168
  }
1169
1169
 
1170
+ // A blocked unique index refuses user writes; ingest must not write rows the missing constraint would have rejected.
1171
+ // The alarm tier records the refusal and retries on its poll interval.
1172
+ this.ensureServable();
1173
+
1170
1174
  const shardKey = this.currentShardKey();
1171
1175
  const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
1172
1176
 
@@ -1353,14 +1357,14 @@ ${a} const vectors = createContextVectors(lunora${h});
1353
1357
  ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
1354
1358
  });
1355
1359
  }
1356
- `:"",vectorsBuild:m,vectorsStub:n}},bn=({advisories:r=[],advisorProcedures:t=[],agents:e=[],capabilities:o=new Set,containers:n=[],env:a,flagKeys:i=[],hasFlags:u=!1,hasNotify:h=!1,hasRooms:m=!1,hasSecretValues:S=!1,hasSensitiveArgs:v=!1,hasSockets:R=!1,lazyFunctions:d=!1,hasVectors:x=!0,liveStreamDeclarations:A=[],liveStreams:O=!1,maskMetadata:B,mutators:j=[],queues:k=[],rlsMetadata:W,schema:c,schemaSnapshot:b,shapes:L=[],storageRules:K,studioFeatures:H,hasIpReaders:D=!1,services:P=[],topics:V=[],useUmbrella:G=!1,workflowEvents:N=[],workflows:T=[]})=>{const l=Er(G),y=j.length>0,_=L.length>0,E=L.some(s=>Ar(s.args).length>0),Q=v||E,be=b===void 0?"":tr(b),ye=b===void 0?"":`
1360
+ `:"",vectorsBuild:m,vectorsStub:n}},wn=({advisories:r=[],advisorProcedures:t=[],agents:e=[],capabilities:o=new Set,containers:n=[],env:a,flagKeys:i=[],hasFlags:u=!1,hasNotify:h=!1,hasRooms:m=!1,hasSecretValues:S=!1,hasSensitiveArgs:v=!1,hasSockets:R=!1,lazyFunctions:d=!1,hasVectors:x=!0,liveStreamDeclarations:A=[],liveStreams:O=!1,maskMetadata:B,mutators:j=[],queues:k=[],rlsMetadata:W,schema:c,schemaSnapshot:b,shapes:C=[],storageRules:K,studioFeatures:H,hasIpReaders:D=!1,services:L=[],topics:V=[],useUmbrella:G=!1,workflowEvents:P=[],workflows:T=[]})=>{const l=Er(G),y=j.length>0,_=C.length>0,N=C.some(s=>Ar(s.args).length>0),Q=v||N,be=b===void 0?"":tr(b),ye=b===void 0?"":`
1357
1361
  /** 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. */
1358
1362
  const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(rr(b))}, json: ${JSON.stringify(be)} };
1359
- `,we=b===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",w=or(o),$=ir(u,l.flags),z=dr(i,u,l.flags),J=Rr(h),Y=cr(a),{build:ve,contextField:ke,importLines:Se,specs:Re}=lr(Ir(k)),{build:xe,contextField:Ae,importLines:Oe,specs:De}=ur(V,k),X=hr(P,l.server),{build:Te,contextField:_e,importLines:Ee,specs:Ie}=pr(n,c.jurisdiction),{build:Ce,contextField:Le,importLines:Pe,specs:Ne}=mr(T),{build:$e,contextField:Me,importLines:qe,schedulerSource:Ue,specs:Fe,stampsOutbox:Be}=fr(e,S&&e.length>0),{build:je,configField:We,contextField:Ke,imports:He,stub:Ve}=gr(o.has("payments")),Ge=r,{advisoryRules:Qe,advisoryRows:ze}=Lr(Ge),Je=t,se=W??{policies:[],roles:[]},Ye=B??{columns:[]},Xe=K??{rules:[]},Ze=H??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:et,override:tt}=br(T,N),{constant:rt,override:nt}=yr(T,N),{constant:at,override:st}=wr(k),f=x&&c.vectorIndexes.length>0,Z=new Set(c.tables.filter(s=>Cr(s)).map(s=>s.name)),oe=f&&c.vectorIndexes.some(s=>Z.has(s.table)),I=c.tables.some(s=>s.shardMode==="global"),ee=vr(Z),te=c.tables.some(s=>nr(s)),ie=c.tables.some(s=>ar(s)),M=c.tables.some(s=>s.externalSource!==void 0),de=c.tables.some(s=>s.memory===!0),re=c.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(ie&&te)throw new me("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const ne=c.tables.length>0,ot=jr(c),it=Kr(c),dt=Jr(c),ct=Wr(c),ce=Hr(c),ae=kr(f,T.length>0,k.length>0,u,re);_&&ae.push("WhereInput"),E&&ae.push("SensitiveScope");const le=Sr(I),{customMutatorOverride:lt,shapeGuardImport:ut,shapeReadPolicyAssertion:ht,shapeReadPolicyImport:pt,shapeResolveOverride:mt}=Yr({hasMutators:y,hasSensitiveShapes:E,hasShapes:_,rlsData:se}),C=O?A:[];for(const s of C)if(Or(s.exportName,"live stream export name"),!Dr.test(s.filePath))throw new me("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ft=d?[]:C.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),gt=` protected override liveStreams() {
1360
- return { ${C.map(s=>`${Tr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1363
+ `,we=b===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",w=or(o),$=ir(u,l.flags),z=dr(i,u,l.flags),J=Rr(h),Y=cr(a),{build:ve,contextField:ke,importLines:Se,specs:Re}=lr(Ir(k)),{build:xe,contextField:Ae,importLines:Oe,specs:De}=ur(V,k),X=hr(L,l.server),{build:Te,contextField:_e,importLines:Ee,specs:Ie}=pr(n,c.jurisdiction),{build:Ce,contextField:Le,importLines:Pe,specs:Ne}=mr(T),{build:$e,contextField:qe,importLines:Me,schedulerSource:Ue,specs:Fe,stampsOutbox:Be}=fr(e,S&&e.length>0),{build:je,configField:We,contextField:Ke,imports:He,stub:Ve}=gr(o.has("payments")),Ge=r,{advisoryRules:Qe,advisoryRows:ze}=Lr(Ge),Je=t,ae=W??{policies:[],roles:[]},Ye=B??{columns:[]},Xe=K??{rules:[]},Ze=H??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:et,override:tt}=br(T,P),{constant:rt,override:nt}=yr(T,P),{constant:at,override:st}=wr(k),f=x&&c.vectorIndexes.length>0,Z=new Set(c.tables.filter(s=>Cr(s)).map(s=>s.name)),se=f&&c.vectorIndexes.some(s=>Z.has(s.table)),E=c.tables.some(s=>s.shardMode==="global"),ee=vr(Z),te=c.tables.some(s=>nr(s)),oe=c.tables.some(s=>ar(s)),q=c.tables.some(s=>s.externalSource!==void 0),ie=c.tables.some(s=>s.memory===!0),re=c.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(oe&&te)throw new me("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const ne=c.tables.length>0,ot=jr(c),it=Kr(c),dt=Jr(c),ct=Wr(c),de=Hr(c),ce=kr(f,T.length>0,k.length>0,u,re);_&&ce.push("WhereInput");const le=Sr(E),{customMutatorOverride:lt,shapeGuardImport:ut,shapeReadPolicyAssertion:ht,shapeReadPolicyImport:pt,shapeResolveOverride:mt}=Yr({hasMutators:y,hasSensitiveShapes:N,hasShapes:_,rlsData:ae}),I=O?A:[];for(const s of I)if(Or(s.exportName,"live stream export name"),!Dr.test(s.filePath))throw new me("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const ft=d?[]:I.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),gt=` protected override liveStreams() {
1364
+ return { ${I.map(s=>`${Tr(s.id)}: liveStream_${s.exportName}`).join(", ")} };
1361
1365
  }
1362
1366
  `,bt=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
1363
- ${C.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1367
+ ${I.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
1364
1368
  `)}
1365
1369
  ]);
1366
1370
 
@@ -1381,11 +1385,11 @@ ${C.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1381
1385
  protected override liveStreams() {
1382
1386
  return Object.fromEntries(this.loadedLiveStreams);
1383
1387
  }
1384
- `;let ue="";C.length>0&&(ue=d?bt:gt);const q=[`import type { ${ae.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${re?"backfillSearchIndexes, ":""}${f?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${de?"clearMemoryTables, ":""}${ut}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${M?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${oe?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${le.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...M?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],_?`import { asBucketStorage, ${pt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];ne&&q.push(`import type { FacadeEntry } from "${l.server}";`,`import { bindOrm, defineLazyFacade } from "${l.server}";`),f&&q.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),q.push(...w.importLines,...$.importLines,...J.importLines,...Y.importLines,...Ee,...Pe,...Se,...Oe,...X.importLines,...qe,...He,...Q?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ft,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...d?["getLoadedFunction","loadFunction"]:[],...y?["LUNORA_MUTATOR_PATHS"]:[],...D?["LUNORA_IP_READER_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...R?["LUNORA_SOCKETS"]:[],..._?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const yt=f?`
1385
- vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",wt=ie?`
1388
+ `;let ue="";I.length>0&&(ue=d?bt:gt);const M=[`import type { ${ce.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${re?"backfillSearchIndexes, ":""}${f?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${ie?"clearMemoryTables, ":""}${ut}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${q?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${se?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${le.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...q?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],_?`import { asBucketStorage, ${pt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];ne&&M.push(`import type { FacadeEntry } from "${l.server}";`,`import { bindOrm, defineLazyFacade } from "${l.server}";`),f&&M.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),M.push(...w.importLines,...$.importLines,...J.importLines,...Y.importLines,...Ee,...Pe,...Se,...Oe,...X.importLines,...Me,...He,...Q?[`import { sensitiveArgumentNames } from "${l.values}";`]:[],"",'import schema from "../schema.js";',...ft,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...d?["getLoadedFunction","loadFunction"]:[],...y?["LUNORA_MUTATOR_PATHS"]:[],...D?["LUNORA_IP_READER_PATHS"]:[],...m?["LUNORA_ROOMS"]:[],...R?["LUNORA_SOCKETS"]:[],..._?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const yt=f?`
1389
+ vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",wt=oe?`
1386
1390
  d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",vt=te?`
1387
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",kt=M?`
1388
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",St="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",Rt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",xt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",At=I?U("globalDbStub: DatabaseWriterLike",St,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:Ot,vectorsBuild:Dt,vectorsStub:Tt}=en(f,oe?c.vectorIndexes.filter(s=>Z.has(s.table)).map(s=>s.name):[]),_t=`{
1391
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",kt=q?`
1392
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",St="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",Rt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",xt="ctx.storage: no storage configured. Pass `storage` to createShardDO().",At=E?U("globalDbStub: DatabaseWriterLike",St,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:Ot,vectorsBuild:Dt,vectorsStub:Tt}=en(f,se?c.vectorIndexes.filter(s=>Z.has(s.table)).map(s=>s.name):[]),_t=`{
1389
1393
  ...this.ctxDbTuning(),
1390
1394
  auth: {
1391
1395
  get identity() {
@@ -1444,11 +1448,11 @@ ${C.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1444
1448
  scheduler,
1445
1449
  schema: schema as unknown as SchemaLike,
1446
1450
  sql: this.sql as SqlExec,
1447
- storage,${I?`
1451
+ storage,${E?`
1448
1452
  globalDb,`:""}
1449
1453
  }`,Et=f?`
1450
1454
  vectors,`:"",It=ne?`
1451
- orm: bindOrm(facade),`:"",he=te?"config.hyperdriveGlobal":"config.d1",Ct=I?` const bookmark = this.getInboundBookmark();
1455
+ orm: bindOrm(facade),`:"",he=te?"config.hyperdriveGlobal":"config.d1",Ct=E?` const bookmark = this.getInboundBookmark();
1452
1456
  const globalRequest = {
1453
1457
  ...this.globalCdcOptions(config.cdc ?? false),
1454
1458
  ...(bookmark === undefined ? {} : { bookmark }),
@@ -1461,20 +1465,20 @@ ${C.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
1461
1465
  },
1462
1466
  };
1463
1467
  const globalDb: DatabaseWriterLike = ${he}?.(env, globalRequest) ?? globalDbStub;
1464
- `:"",Lt=Xr(_&&I,he),Pt=m?` protected override roomHandlerPath(topic: string): string | undefined {
1468
+ `:"",Lt=Xr(_&&E,he),Pt=m?` protected override roomHandlerPath(topic: string): string | undefined {
1465
1469
  // Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
1466
1470
  return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
1467
1471
  }
1468
1472
  `:"",Nt=R?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
1469
1473
  return LUNORA_SOCKETS[path];
1470
1474
  }
1471
- `:"",{externalSourceOverride:$t,sourceBootstrap:Mt,sourceClientCacheConst:qt}=Zr(M),Ut=`
1475
+ `:"",{externalSourceOverride:$t,sourceBootstrap:qt,sourceClientCacheConst:Mt}=Zr(q),Ut=`
1472
1476
  private shardInitDeferred = false;
1473
1477
  private deferredShardInit?: Promise<void>;
1474
1478
 
1475
1479
  protected override async runShardInit(): Promise<void> {
1476
1480
  this.ensureMigrated();
1477
- ${de?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1481
+ ${ie?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
1478
1482
  `:""}
1479
1483
  if (this.blockedUniqueIndexes.length > 0) {
1480
1484
  this.shardInitDeferred = true;
@@ -1514,7 +1518,7 @@ ${de?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1514
1518
 
1515
1519
  await this.deferredShardInit;
1516
1520
  }
1517
- `,Ft=ce.length>0?`
1521
+ `,Ft=de.length>0?`
1518
1522
  if (LUNORA_TTL_SWEEPS.length > 0) {
1519
1523
  void this.scheduleTtlSweep();
1520
1524
  }
@@ -1538,7 +1542,7 @@ ${de?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1538
1542
  ${D?` for (const path of LUNORA_IP_READER_PATHS) {
1539
1543
  this.ipKeyedFunctionPaths.add(path);
1540
1544
  }
1541
- `:""}${Mt}${Ft} }
1545
+ `:""}${qt}${Ft} }
1542
1546
 
1543
1547
  protected override isCacheableQuery(functionPath: string): boolean {
1544
1548
  // NOT \`kind === "query"\` alone. A cache hit answers without running
@@ -1582,9 +1586,9 @@ ${D?` for (const path of LUNORA_IP_READER_PATHS) {
1582
1586
  `:`${pe}
1583
1587
  `,Wt=Q?`
1584
1588
  protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
1585
- const registered = LUNORA_FUNCTIONS[functionPath];${E?`
1589
+ const registered = LUNORA_FUNCTIONS[functionPath];${N?`
1586
1590
  const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
1587
- const fromValidators = sensitiveArgumentNames(registered?.args ?? ${E?"shape?.args ?? ":""}{});
1591
+ const fromValidators = sensitiveArgumentNames(registered?.args ?? ${N?"shape?.args ?? ":""}{});
1588
1592
 
1589
1593
  if (registered?.sensitiveArgs === undefined) {
1590
1594
  return fromValidators;
@@ -1593,7 +1597,7 @@ ${D?` for (const path of LUNORA_IP_READER_PATHS) {
1593
1597
  return new Set([...registered.sensitiveArgs, ...fromValidators]);
1594
1598
  }
1595
1599
 
1596
- `:"",Kt=Mr(d),Ht=d?` const preparation = this.prepareFunction(functionPath, "subscription");
1600
+ `:"",Kt=qr(d),Ht=d?` const preparation = this.prepareFunction(functionPath, "subscription");
1597
1601
  if (preparation !== undefined) await preparation;
1598
1602
  `:"",Vt=Ur.replace("__PREPARE_FUNCTION__",Ht),Gt=Br(m,d,Be),Qt=ne?`
1599
1603
  const facade = db as unknown as Record<string, FacadeEntry>;
@@ -1608,7 +1612,7 @@ ${c.tables.map(s=>` defineLazyFacade(db, ${JSON.stringify(s.name)});`
1608
1612
  await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
1609
1613
  },
1610
1614
  };
1611
- `:"",Zt=[...w.actionFields,...P.length>0?["services"]:[],...O?["live"]:[]],er=`${w.actionBuild}${X.build}${Xt}`;return`${_r}${q.join(`
1615
+ `:"",Zt=[...w.actionFields,...L.length>0?["services"]:[],...O?["live"]:[]],er=`${w.actionBuild}${X.build}${Xt}`;return`${_r}${M.join(`
1612
1616
  `)}
1613
1617
 
1614
1618
  type FunctionKind = "action" | "mutation" | "query";
@@ -1644,7 +1648,7 @@ const LUNORA_TABLE_COLUMNS = ${p(dt,`Record<
1644
1648
  const LUNORA_STORAGE_COLUMNS = ${p(ct,"Record<string, string[]>")};
1645
1649
 
1646
1650
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1647
- const LUNORA_TTL_SWEEPS = ${sr(ce,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1651
+ const LUNORA_TTL_SWEEPS = ${sr(de,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
1648
1652
 
1649
1653
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1650
1654
  const LUNORA_ADVISORY_RULES = ${p(Qe,"Record<string, Partial<AdvisoryFinding>>")};
@@ -1661,7 +1665,7 @@ const LUNORA_ADVISORIES = ((): (() => AdvisoryFinding[]) => {
1661
1665
  const LUNORA_ADVISOR_PROCEDURES = ${p(Je,"AdvisorProcedure[]")};
1662
1666
 
1663
1667
  /** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
1664
- const LUNORA_RLS_METADATA = ${p(se,"RlsPoliciesResult")};
1668
+ const LUNORA_RLS_METADATA = ${p(ae,"RlsPoliciesResult")};
1665
1669
  ${ht}
1666
1670
  /** 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. */
1667
1671
  const LUNORA_MASK_METADATA = ${p(Ye,"MaskPoliciesResult")};
@@ -1693,7 +1697,7 @@ export interface ShardDOConfig {
1693
1697
  /** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
1694
1698
  storage?: (env: Record<string, unknown>, origin?: string) => unknown;${yt}${w.configFields}${$.configField}${We}${wt}${vt}${kt}${ee.configField}
1695
1699
  }
1696
- ${U("schedulerStub",Rt,["cancel","runAfter","runAt"])}${U("storageStub",xt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${At}${qt}${Tt}${w.stubs}${Ve}
1700
+ ${U("schedulerStub",Rt,["cancel","runAfter","runAt"])}${U("storageStub",xt,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${At}${Mt}${Tt}${w.stubs}${Ve}
1697
1701
  // \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
1698
1702
  // mutation may be replayed, so a network call in either returns a different answer
1699
1703
  // on each run. Refused at runtime, not only linted: the advisor sees just the call
@@ -1883,6 +1887,6 @@ ${re?`
1883
1887
  return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
1884
1888
  }
1885
1889
  `:""}${Ot}
1886
- ${$r({hasSensitiveArgs:Q,lazyFunctions:d,actionOnlyFields:Zt,agentsBuild:$e,agentsContextField:Me,agentsSchedulerSource:Ue,containersBuild:Te,containersContextField:_e,databaseOptions:_t,everyContextBuild:zt,everyContextField:Jt,facadeBlock:Qt,globalDatabaseLine:Ct,notifyBuild:Yt,ormContextField:It,paymentsBuild:je,paymentsContextField:Ke,queuesBuild:ve,queuesContextField:ke,topicsBuild:xe,topicsContextField:Ae,vectorsBuild:Dt,vectorsContextField:Et,workflowsBuild:Ce,workflowsContextField:Le,actionOnlyBuild:er})}
1890
+ ${$r({hasSensitiveArgs:Q,lazyFunctions:d,actionOnlyFields:Zt,agentsBuild:$e,agentsContextField:qe,agentsSchedulerSource:Ue,containersBuild:Te,containersContextField:_e,databaseOptions:_t,everyContextBuild:zt,everyContextField:Jt,facadeBlock:Qt,globalDatabaseLine:Ct,notifyBuild:Yt,ormContextField:It,paymentsBuild:je,paymentsContextField:Ke,queuesBuild:ve,queuesContextField:ke,topicsBuild:xe,topicsContextField:Ae,vectorsBuild:Dt,vectorsContextField:Et,workflowsBuild:Ce,workflowsContextField:Le,actionOnlyBuild:er})}
1887
1891
  };
1888
- `};export{Wr as b,bn as e};
1892
+ `};export{Wr as b,wn as e};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.396",
3
+ "version": "1.0.0-alpha.397",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,15 +50,15 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/advisor": "1.0.0-alpha.286",
54
- "@lunora/agent": "1.0.0-alpha.280",
53
+ "@lunora/advisor": "^1.0.0-alpha.287",
54
+ "@lunora/agent": "^1.0.0-alpha.281",
55
55
  "@lunora/container": "1.0.0-alpha.108",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
57
  "@lunora/platform": "1.0.0-alpha.80",
58
58
  "@lunora/queue": "1.0.0-alpha.143",
59
- "@lunora/scheduler": "1.0.0-alpha.168",
60
- "@lunora/values": "1.0.0-alpha.94",
61
- "@lunora/workflow": "1.0.0-alpha.110",
59
+ "@lunora/scheduler": "^1.0.0-alpha.169",
60
+ "@lunora/values": "^1.0.0-alpha.95",
61
+ "@lunora/workflow": "^1.0.0-alpha.111",
62
62
  "@visulima/fs": "7.0.0",
63
63
  "jiti": "^2.7.0",
64
64
  "quicktype-core": "^26.0.0",
@@ -1 +0,0 @@
1
- import{SyntaxKind as g,Node as m,ts as w,Project as R}from"ts-morph";import{CAPABILITIES as u}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{descendantsOfKind as l,bindingKeyName as y,listLunoraSourceFiles as D}from"./isTestPath-DrszPMtU.mjs";import{scanImportDeclaration as P,noSandboxUsage as v}from"./discoverSandboxUsage-CSt29RbS.mjs";const f="ctx",A=(e,t,s)=>{for(const n of l(e,g.ElementAccessExpression)){const r=n.getArgumentExpression();t(n.getExpression())&&r!==void 0&&(m.isStringLiteral(r)||m.isNoSubstitutionTemplateLiteral(r))&&s.add(r.getLiteralValue())}},L=e=>{const t=new Set,s=new Set,n=new Set(l(e,g.Parameter).map(o=>o.getName())),r=l(e,g.VariableDeclaration).some(o=>{const c=o.getInitializer();return o.getName()===f&&m.isIdentifier(c)&&n.has(c.getText())});(n.has(f)||r)&&s.add(f);const i=o=>{if(m.isObjectBindingPattern(o))for(const c of o.getElements()){const d=y(c);d&&t.add(d)}};for(const o of l(e,g.BindingElement)){if(y(o)!==f)continue;const c=o.getNameNode();m.isIdentifier(c)?s.add(c.getText()):i(c)}const a=o=>m.isIdentifier(o)&&s.has(o.getText());for(const o of l(e,g.PropertyAccessExpression))a(o.getExpression())&&t.add(o.getName());A(e,a,t);for(const o of l(e,g.VariableDeclaration)){const c=o.getInitializer();c!==void 0&&a(c)&&i(o.getNameNode())}return t},M=e=>{if(e.isTypeOnly())return!0;if(m.isExportDeclaration(e)){const s=e.getNamedExports();return!e.isNamespaceExport()&&s.length>0&&s.every(n=>n.isTypeOnly())}const t=e.getNamedImports();return e.getDefaultImport()===void 0&&e.getNamespaceImport()===void 0&&t.length>0&&t.every(s=>s.isTypeOnly())},C=new Map(u.flatMap(({bindingFreeExports:e,moduleSpecifier:t})=>e===void 0?[]:[[t,new Set(e)]])),V=(e,t)=>{const s=C.get(t);if(s===void 0||m.isImportDeclaration(e)&&(e.getDefaultImport()!==void 0||e.getNamespaceImport()!==void 0))return!1;const n=m.isExportDeclaration(e)?e.getNamedExports():e.getNamedImports();return n.length>0&&n.every(r=>r.isTypeOnly()||s.has(r.getName()))},F=e=>{const t=new Set;for(const s of l(e,g.CallExpression)){const[n]=s.getArguments();s.getExpression().getKind()===g.ImportKeyword&&(m.isStringLiteral(n)||m.isNoSubstitutionTemplateLiteral(n))&&t.add(n.getLiteralValue())}return t},N="@lunora/agent",E="requestSecretTool",I=e=>e.startsWith("./")||e.startsWith("../"),S=e=>e.getAliasNode()?.getText()??e.getNameNode().getText(),z=(e,t)=>{const s=e!==void 0&&m.isCallExpression(e)?e.getExpression():e;return s!==void 0&&m.isIdentifier(s)&&t.has(s.getText())},_=e=>{const t=new Set;for(const s of e.getImportDeclarations())if(!(s.getModuleSpecifierValue()!==N||s.isTypeOnly()))for(const n of s.getNamedImports())!n.isTypeOnly()&&n.getNameNode().getText()===E&&t.add(S(n));return t},p=e=>({names:new Set(e),namespaces:new Map}),x=()=>({projects:new Map,origins:new Map}),k=(e,t)=>{if(e.origins.has(t))return t;let s=e.projects.get(t);return s===void 0&&(s=new R({compilerOptions:{...t.getCompilerOptions(),allowJs:!0},fileSystem:t.getFileSystem(),skipAddingFilesFromTsConfig:!0,skipFileDependencyResolution:!0,skipLoadingLibFiles:!0}),e.projects.set(t,s),e.origins.set(s,t)),s},b=(e,t,s)=>{const n=t.getSourceFile(),r=n.getProject(),i=e.origins.get(r)??r,{resolvedModule:a}=w.resolveModuleName(s,n.getFilePath(),i.getCompilerOptions(),i.getModuleResolutionHost()),o=a?.resolvedFileName;if(o===void 0)return;const c=i.getSourceFile(o)??r.getSourceFile(o);if(c!==void 0)return c;const d=k(e,r);return d.getSourceFile(o)??d.addSourceFileAtPath(o)},B=(e,t,s)=>{const n=e.getNamespaceExport();if(n!==void 0){const r=new Set(t.names);t.namespaces.forEach((i,a)=>{i.forEach(o=>{r.add(`${a}.${o}`)})}),r.size>0&&s.namespaces.set(n.getName(),r);return}if(!e.hasNamedExports()){t.names.forEach(r=>s.names.add(r)),t.namespaces.forEach((r,i)=>s.namespaces.set(i,r));return}for(const r of e.getNamedExports()){if(r.isTypeOnly())continue;const i=r.getNameNode().getText(),a=S(r);t.names.has(i)&&s.names.add(a);const o=t.namespaces.get(i);o!==void 0&&s.namespaces.set(a,o)}},K=(e,t,s,n)=>{const r=t.getModuleSpecifierValue();if(r===void 0)return p(s);if(r===N)return p([E]);const i=I(r)?b(e,t,r):void 0;return i===void 0?p([]):n(i)},h=(e,t,s)=>{const n=p([]),r=e.getFilePath();if(t.has(r))return n;t.add(r);const i=_(e);for(const a of e.getExportDeclarations())a.isTypeOnly()||B(a,K(s,a,i,o=>h(o,t,s)),n);for(const a of e.getVariableStatements())if(a.hasExportKeyword())for(const o of a.getDeclarations())z(o.getInitializer(),i)&&n.names.add(o.getName());return t.delete(r),n},W=(e,t,s)=>{const n=e.getModuleSpecifierValue();if(n===N)return p([E]);const r=I(n)?b(s,e,n):void 0;return r===void 0?p([]):h(r,new Set([t.getFilePath()]),s)},$=e=>{const t=e.getPropertyNameNode();return t===void 0?e.getName():m.isStringLiteral(t)?t.getLiteralValue():t.getText()},T=(e,t,s)=>{const n=(o,c)=>o===t?s.has(c):o.startsWith(`${t}.`)&&s.has(`${o.slice(t.length+1)}.${c}`),r=e.getDescendantsOfKind(g.PropertyAccessExpression).some(o=>n(o.getExpression().getText(),o.getName())),i=l(e,g.ElementAccessExpression).some(o=>{const c=o.getArgumentExpression();return m.isStringLiteral(c)&&n(o.getExpression().getText(),c.getLiteralValue())}),a=l(e,g.VariableDeclaration).some(o=>{const c=o.getInitializer(),d=o.getNameNode();return c!==void 0&&m.isObjectBindingPattern(d)&&d.getElements().some(O=>n(c.getText(),$(O)))});return r||i||a},j=(e,t,s)=>{if(s.names.has(t.getNameNode().getText()))return!0;const n=s.namespaces.get(t.getNameNode().getText());return n!==void 0&&T(e,S(t),n)},q=(e,t=x())=>e.getImportDeclarations().some(s=>{if(s.isTypeOnly())return!1;const n=W(s,e,t);if(n.names.size===0&&n.namespaces.size===0)return!1;const r=s.getDefaultImport(),i=s.getNamespaceImport();return r!==void 0&&(n.names.has("default")||T(e,r.getText(),n.namespaces.get("default")??new Set))||s.getNamedImports().some(o=>!o.isTypeOnly()&&j(e,o,n))||i!==void 0&&T(e,i.getText(),n.names)}),U=(e,t=x())=>{const s=e.getImportDeclarations(),n=v();for(const r of s){const i=P(r);for(const a of Object.keys(n))n[a]||=i[a]}return{contextReads:L(e),dynamicImports:F(e),requestSecretTool:q(e,t),sandboxTools:n,valueImports:new Set([...s,...e.getExportDeclarations()].flatMap(r=>{const i=r.getModuleSpecifierValue();return i===void 0||M(r)||V(r,i)?[]:[i]}))}},X=e=>{const t=new Set,s=new Set,n=v(),r=new Set;let i=!1;for(const a of e){i||=a.requestSecretTool;for(const o of a.contextReads)t.add(o);for(const o of a.dynamicImports)s.add(o);for(const o of a.valueImports)r.add(o);for(const o of Object.keys(n))n[o]||=a.sandboxTools[o]}return{contextReads:t,dynamicImports:s,requestSecretTool:i,sandboxTools:n,valueImports:r}},G=e=>new Set(u.filter(({contextProperty:t,moduleSpecifier:s})=>e.valueImports.has(s)||t!==void 0&&e.contextReads.has(t)).map(({key:t})=>t)),H=new RegExp(String.raw`\b${f}\b`,"u"),J=new RegExp(String.raw`\b(?:${u.flatMap(({contextProperty:e})=>e===void 0?[]:[e]).join("|")})\b`,"u"),te=e=>H.test(e)&&J.test(e),se=(e,t)=>{const s=x(),n=X(D(t).map(i=>U(e.getSourceFile(i)??e.addSourceFileAtPath(i),s))),r=G(n);return Object.fromEntries(u.map(({key:i})=>[i,r.has(i)]))};export{G as capabilitiesUsedBy,L as contextPropertiesRead,x as createTargetScope,se as discoverFeatureUsage,q as fileWiresRequestSecretTool,X as foldCapabilitySignals,te as mayReadCapabilityContext,U as sourceCapabilitySignals};
@@ -1 +0,0 @@
1
- import{Node as r,SyntaxKind as s}from"ts-morph";import{listLunoraSourceFiles as l,lunoraRelativePath as c,handlerOf as d,descendantsOfKind as a}from"./isTestPath-DrszPMtU.mjs";import{j as f,h as m}from"./attribution-7Qs8xFmy.mjs";import{c as u}from"./classify-procedure-call-D7XTLd8w.mjs";const p={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},x=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),h=e=>{if(r.isIdentifier(e))return e.getText();if(r.isPropertyAccessExpression(e)){const t=e.getExpression();if(r.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},N=e=>{const t=e.getExpression();if(r.isIdentifier(t)){const i=t.getText();return i==="fetch"||i==="Date"?i:void 0}if(!r.isPropertyAccessExpression(t))return;const n=t.getName(),o=h(t.getExpression());if(o!==void 0)return n==="fetch"&&x.has(o)?"fetch":p[`${o}.${n}`]},E=e=>{const t=e.getExpression();if(!r.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),o=n.every(i=>r.isNumericLiteral(i)||r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i));return n.length>0&&o?void 0:"new Date"},S=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const n=u(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const o=d(t,n.receiver);return o?{exportName:m(e)??e.getName(),handler:o,kind:n.kind}:void 0},v=(e,t)=>{const n=[];for(const o of a(e.handler,s.CallExpression)){const i=e.kind==="query"&&o.getExpression().getText()==="ctx.random"?"ctx.random":N(o);i!==void 0&&n.push({callee:i,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}for(const o of a(e.handler,s.NewExpression)){const i=E(o);i!==void 0&&n.push({callee:i,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}return n},L=(e,t)=>{const n=[];for(const o of f(e)){const i=S(o);i&&n.push(...v(i,t))}return n},O=(e,t)=>{const n=[];for(const o of l(t)){const i=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...L(i,c(t,o)))}return n};export{O as default};