@lunora/codegen 1.0.0-alpha.361 → 1.0.0-alpha.363

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
@@ -1668,11 +1668,11 @@ interface MutatorIR {
1668
1668
  returnType: string;
1669
1669
  }
1670
1670
  /**
1671
- * A whole-row `ctx.db.replace(id, document)` write discovered inside a custom
1671
+ * A whole-row `ctx.db.replace("table", id, document)` write discovered inside a custom
1672
1672
  * mutator's inline `server` impl (`lunora/mutators.ts`) — the input the
1673
1673
  * `mutator_full_row_replace` advisor lint consumes. A `replace` overwrites the
1674
1674
  * entire row, so a concurrent edit to a different column on a synced table is
1675
- * clobbered; `ctx.db.patch(id, { field })` merges at the column level instead.
1675
+ * clobbered; `ctx.db.patch("table", id, { field })` merges at the column level instead.
1676
1676
  * Structurally identical to `AdvisorMutatorWrite` so it passes straight through
1677
1677
  * to the advisor without conversion, exactly as `InsertWriteIR` does for
1678
1678
  * `AdvisorInsertWrite`.
package/dist/index.d.ts CHANGED
@@ -1668,11 +1668,11 @@ interface MutatorIR {
1668
1668
  returnType: string;
1669
1669
  }
1670
1670
  /**
1671
- * A whole-row `ctx.db.replace(id, document)` write discovered inside a custom
1671
+ * A whole-row `ctx.db.replace("table", id, document)` write discovered inside a custom
1672
1672
  * mutator's inline `server` impl (`lunora/mutators.ts`) — the input the
1673
1673
  * `mutator_full_row_replace` advisor lint consumes. A `replace` overwrites the
1674
1674
  * entire row, so a concurrent edit to a different column on a synced table is
1675
- * clobbered; `ctx.db.patch(id, { field })` merges at the column level instead.
1675
+ * clobbered; `ctx.db.patch("table", id, { field })` merges at the column level instead.
1676
1676
  * Structurally identical to `AdvisorMutatorWrite` so it passes straight through
1677
1677
  * to the advisor without conversion, exactly as `InsertWriteIR` does for
1678
1678
  * `AdvisorInsertWrite`.
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-SplX7j_9.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-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as g}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BedyJsOT.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-JdN4KXhV.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-Ce3BdKQr.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-T1v8pyHN.mjs";import{default as P}from"./packem_shared/discoverCrons-D-vJXsgx.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-Xncj__oq.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BEMyglH0.mjs";import{default as K}from"./packem_shared/discoverFunctions-BdEY3nbv.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-Hy2UrcrN.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-Cn3087D8.mjs";import{default as J}from"./packem_shared/discoverInserts-DIzIGlyG.mjs";import{d as X}from"./packem_shared/index-Cm7HdvL5.mjs";import{default as $}from"./packem_shared/discoverMigrations-Bv8kNIgy.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-PNPCtUl2.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-DZ_kIie5.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-HXIKioYv.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-KjOdhrk6.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Dt5RG_P0.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-B4N8iXlU.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-DhOEyJLg.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Dq6iSXnC.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CdGRnVU2.mjs";import{default as he}from"./packem_shared/discoverSchema-B6yDZ9Bb.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-mgEi072Z.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{emitApp as je}from"./packem_shared/emitApp-CT7iAjam.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ve,emitOpenApi as ze,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-Cju685VK.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-CTR_g_IE.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir}from"./packem_shared/loadProjectConfig-B7RmxIeD.mjs";import{PROJECT_CONFIG_FILENAMES as fr,findCodegenConfigFile as mr,findProjectConfigFile as dr,projectConfigCandidatePaths as pr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-szOu1Xod.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs";import{default as vr}from"./packem_shared/fingerprintSchemaSources-DIYx5eO0.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CIAJQeKB.mjs";import{SDK_LANGUAGES as Ir,SDK_TARGETS as _r,generateSdk as Fr}from"./sdk/index.mjs";import{redact as Mr,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as br}from"./packem_shared/emitDrizzleSchema-CD4hPtUP.mjs";import{e as Ur}from"./packem_shared/server-DCjunXFf.mjs";import{e as Hr}from"./packem_shared/shard-gWobaDx2.mjs";import{G as Br}from"./packem_shared/shared-Br_OnErI.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-DmXl8m_P.mjs";import{s as Yr,t as Xr,u as Zr}from"./packem_shared/shard-runtime-DXlpfT3P.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-CCjh0ICg.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-CY8IQfAI.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-Bba2y2yt.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-C3WOlVN0.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,g as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z 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,ve as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,vr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as i}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.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-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as g}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-BedyJsOT.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-JdN4KXhV.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-Ce3BdKQr.mjs";import{CONTAINERS_FILENAME as F,discoverContainers as L}from"./packem_shared/CONTAINERS_FILENAME-T1v8pyHN.mjs";import{default as P}from"./packem_shared/discoverCrons-D-vJXsgx.mjs";import{capabilitiesUsedBy as b,createTargetScope as y,foldCapabilitySignals as U,mayReadCapabilityContext as G,sourceCapabilitySignals as H}from"./packem_shared/capabilitiesUsedBy-Xncj__oq.mjs";import{FLAGS_FILENAME as B,discoverFlags as k}from"./packem_shared/FLAGS_FILENAME-BEMyglH0.mjs";import{default as K}from"./packem_shared/discoverFunctions-BdEY3nbv.mjs";import{default as z}from"./packem_shared/discoverHttpRoutes-Hy2UrcrN.mjs";import{default as q}from"./packem_shared/discoverHyperdriveCalls-Cn3087D8.mjs";import{default as J}from"./packem_shared/discoverInserts-DIzIGlyG.mjs";import{d as X}from"./packem_shared/index-Cm7HdvL5.mjs";import{default as $}from"./packem_shared/discoverMigrations-Bv8kNIgy.mjs";import{MUTATORS_FILENAME as re,discoverMutators as oe}from"./packem_shared/MUTATORS_FILENAME-PNPCtUl2.mjs";import{default as ae}from"./packem_shared/discoverNondeterministicCalls-DZ_kIie5.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as fe,discoverNotifyChannels as me,discoverNotifyConfig as de}from"./packem_shared/NOTIFY_FILENAME-HXIKioYv.mjs";import{default as ne}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-KjOdhrk6.mjs";import{QUEUES_FILENAME as Se,discoverQueues as Ee}from"./packem_shared/QUEUES_FILENAME-Dt5RG_P0.mjs";import{default as Ae}from"./packem_shared/discoverR2sqlCalls-B4N8iXlU.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-DhOEyJLg.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Dq6iSXnC.mjs";import{discoverSandboxUsage as Re}from"./packem_shared/discoverSandboxUsage-CdGRnVU2.mjs";import{default as he}from"./packem_shared/discoverSchema-DmkjooXZ.mjs";import{readServiceBindings as _e,resolveServiceBindings as Fe}from"./packem_shared/readServiceBindings-BA49C6aN.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Pe}from"./packem_shared/SHAPES_FILENAME-mgEi072Z.mjs";import{default as be}from"./packem_shared/discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{WORKFLOWS_FILENAME as Ue,discoverWorkflows as Ge}from"./packem_shared/WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{emitApp as je}from"./packem_shared/emitApp-CT7iAjam.mjs";import{isD1GlobalTable as ke,isHyperdriveGlobalTable as We}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ve,emitOpenApi as ze,emitOpenApiModule as Qe}from"./packem_shared/buildOpenApiDocument-Cju685VK.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as Je,emitOpenRpc as Ye,emitOpenRpcModule as Xe}from"./packem_shared/OPENRPC_VERSION-CTR_g_IE.mjs";import{DEFAULT_TARGET as $e,platformMatrixIds as er,readProjectTarget as rr,resolveCodegenTarget as or}from"./packem_shared/DEFAULT_TARGET-3OLdJhTj.mjs";import{loadProjectConfig as ar,readProjectConfigLiterals as ir}from"./packem_shared/loadProjectConfig-B7RmxIeD.mjs";import{PROJECT_CONFIG_FILENAMES as fr,findCodegenConfigFile as mr,findProjectConfigFile as dr,projectConfigCandidatePaths as pr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,runCodegen as lr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bmny8aw5.mjs";import{SchemaSnapshotParseError as Sr,buildSchemaSnapshot as Er,evaluateSchemaDrift as ur,parseSchemaSnapshot as Ar}from"./packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs";import{default as vr}from"./packem_shared/fingerprintSchemaSources-DIYx5eO0.mjs";import{schemaFromIr as Nr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Tr}from"./packem_shared/LUNORA_ERROR_CODES-CIAJQeKB.mjs";import{SDK_LANGUAGES as Ir,SDK_TARGETS as _r,generateSdk as Fr}from"./sdk/index.mjs";import{redact as Mr,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as br}from"./packem_shared/emitDrizzleSchema-CD4hPtUP.mjs";import{e as Ur}from"./packem_shared/server-8wMiVU6J.mjs";import{e as Hr}from"./packem_shared/shard-wyX4XRYk.mjs";import{G as Br}from"./packem_shared/shared-Br_OnErI.mjs";import{MESSAGE_SOLUTIONS as Wr,findSolutionByMessage as Kr}from"@lunora/errors";import{createCodegenProject as zr,findTsconfig as Qr,refreshCodegenProject as qr,tsconfigFingerprint as wr}from"./packem_shared/createCodegenProject-DmXl8m_P.mjs";import{s as Yr,t as Xr,u as Zr}from"./packem_shared/shard-runtime-DXlpfT3P.mjs";import{emitApi as eo,emitCollections as ro,emitInternalApi as oo}from"./packem_shared/emitApi-CCjh0ICg.mjs";import{emitCrons as ao,emitScheduler as io,emitVectors as so,emitWranglerCronTriggers as fo}from"./packem_shared/emitCrons-CY8IQfAI.mjs";import{emitDataModel as po}from"./packem_shared/emitDataModel-Bba2y2yt.mjs";import{emitFunctions as co}from"./packem_shared/emitFunctions-C3WOlVN0.mjs";import{isTypedSchema as xo}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,F as CONTAINERS_FILENAME,A as CodegenDiagnosticError,$e as DEFAULT_TARGET,B as FLAGS_FILENAME,Br as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Wr as LUNORA_SOLUTION_RULES,re as MUTATORS_FILENAME,se as NOTIFY_FILENAME,we as OPENRPC_VERSION,fr as PROJECT_CONFIG_FILENAMES,Se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Ir as SDK_LANGUAGES,_r as SDK_TARGETS,Me as SHAPES_FILENAME,Sr as SchemaSnapshotParseError,e as VERSION,Ue as WORKFLOWS_FILENAME,Ve as buildOpenApiDocument,Je as buildOpenRpcDocument,Er as buildSchemaSnapshot,b as capabilitiesUsedBy,zr as createCodegenProject,y as createTargetScope,n as describeErrorLevelFindings,g as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,I as discoverAuthApiCalls,L as discoverContainers,P as discoverCrons,k as discoverFlags,K as discoverFunctions,z 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,ve as discoverRlsProcedures,Re as discoverSandboxUsage,he as discoverSchema,Pe as discoverShapes,be as discoverStorageRulesMetadata,Ge as discoverWorkflows,Yr as emitAgents,eo as emitApi,je as emitApp,ro as emitCollections,Xr as emitContainers,ao as emitCrons,po as emitDataModel,br as emitDrizzleSchema,co as emitFunctions,oo as emitInternalApi,ze as emitOpenApi,Qe as emitOpenApiModule,Ye as emitOpenRpc,Xe as emitOpenRpcModule,io as emitScheduler,Ur as emitServer,Hr as emitShard,so as emitVectors,Zr as emitWorkflows,fo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,ur as evaluateSchemaDrift,mr as findCodegenConfigFile,Kr as findLunoraSolution,dr as findProjectConfigFile,Qr as findTsconfig,vr as fingerprintSchemaSources,U as foldCapabilitySignals,f as formatAdvisories,Fr as generateSdk,ke as isD1GlobalTable,We as isHyperdriveGlobalTable,R as isTestPath,xo as isTypedSchema,m as lintSchema,T as listLunoraSourceFiles,ar as loadProjectConfig,G as mayReadCapabilityContext,Ar as parseSchemaSnapshot,er as platformMatrixIds,pr as projectConfigCandidatePaths,ne as readPackageDependencies,ir as readProjectConfigLiterals,rr as readProjectTarget,_e as readServiceBindings,Mr as redact,qr as refreshCodegenProject,or as resolveCodegenTarget,Fe as resolveServiceBindings,lr as runCodegen,Nr as schemaFromIr,Pr as secretKindOf,i as serializeSchemaSnapshot,x as sortedUniqueNames,H as sourceCapabilitySignals,d as toAdvisorContext,wr as tsconfigFingerprint,Tr as validatorIrToJsonSchema};
@@ -1,10 +1,10 @@
1
- import{existsSync as _,readFileSync as Qe,mkdirSync as Vt,writeFileSync as hr,rmSync as Ne,readdirSync as On}from"node:fs";import{dirname as Ut,join as E,relative as kn}from"node:path";import{performance as vt}from"node:perf_hooks";import{runAdvisor as vr}from"@lunora/advisor";import{LunoraError as z}from"@lunora/errors";import{serializeSchemaSnapshot as Er}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{toAdvisorContext as xr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Wt,ts as Sr,VariableDeclarationKind as Ar}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as I,descendantsOfKind as x,bindingKeyName as le,collectCallRows as C,findObjectProperty as U,collectSecurityCallRows as yr,propertyInitializer as F,listSecurityScanFiles as Xe,objectLiteralFromCallbackBody as Rn,limitNameOf as Fn,optionsObjectLiteral as Ln,handlerOf as br,collectNodeRows as ie,chainRootOf as Je,outermostValueWrapper as T,isWriteTarget as Ze,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as qt,returningFunctionOf as It,walkChain as Nr,RUN_METHODS as Dn,functionReferenceSegments as Pr,isTestPath as wr,isFunctionLike as oe,functionKeyOf as Mn,withSourceListMemo as Ir}from"./isTestPath-JdN4KXhV.mjs";import{b as X,d as H,f as D,g as jt,c as S,a as Ht,w as Gt,k as Tr,l as Cr,h as Or,m as kr,j as Tt,i as Rr}from"./attribution-DUbGYT4N.mjs";import{a as Ls,r as Et,i as Y,b as Fr,m as _n,c as et,e as Yt,E as zn,C as Kn,d as Lr,f as Dr,g as Mr}from"./context-root-Bd08qiVR.mjs";import{a as w,i as _r,c as te,d as $n,e as zr,f as Kr,g as Bn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as $r}from"./property-name-7cBlgK_O.mjs";import{b as Br,a as tt}from"./module-specifiers-BctA0m_p.mjs";import{r as st,s as Vr}from"./parse-validator-CP5CL6Q7.mjs";import Ur from"./discoverAuthApiCalls-Ce3BdKQr.mjs";import{i as $,r as Vn}from"./database-calls-BSyvN1No.mjs";import Wr from"./discoverHyperdriveCalls-Cn3087D8.mjs";import{diagnosticAt as ue}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Qt,a as Ue,s as Un,d as qr}from"./index-Cm7HdvL5.mjs";import{MUTATORS_FILENAME as jr,isDefineMutatorCallee as Hr,mutatorServerImplOf as Gr,discoverMutators as Yr}from"./MUTATORS_FILENAME-PNPCtUl2.mjs";import Qr from"./discoverNondeterministicCalls-DZ_kIie5.mjs";import{discoverNotifyConfig as Xr,discoverNotifyCalls as Jr}from"./NOTIFY_FILENAME-HXIKioYv.mjs";import Zr from"./discoverR2sqlCalls-B4N8iXlU.mjs";import eo from"./discoverRlsProcedures-DhOEyJLg.mjs";import{s as Xt,n as to}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as so,redact as no,isHeuristicSecretKind as io,isSecretishName as ro}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Wn,readMergeDurableObjects as oo}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Me,d as ao,r as co}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as lo,discoverWorkflows as uo}from"./WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{r as fo}from"./json-data-Chfs2Cz5.mjs";import{a as go,I as po,g as mo,G as qn,d as ho,i as vo}from"./shared-Br_OnErI.mjs";import{createCodegenProject as Eo}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as kE,refreshCodegenProject as RE,tsconfigFingerprint as FE}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as xo,usedCapabilities as So}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as jn,isHyperdriveGlobalTable as Hn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Ao}from"./AGENTS_FILENAME-BedyJsOT.mjs";import{discoverContainers as yo}from"./CONTAINERS_FILENAME-T1v8pyHN.mjs";import bo from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as No,fileWiresRequestSecretTool as Po,createTargetScope as wo,discoverFeatureUsage as Io}from"./capabilitiesUsedBy-Xncj__oq.mjs";import Gn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as To,findProjectConfigFile as Co}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Oo}from"./QUEUES_FILENAME-Dt5RG_P0.mjs";import{discoverSandboxUsage as ko}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as Ro}from"./readServiceBindings-BA49C6aN.mjs";import Fo from"./discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{resolveCodegenTarget as Ct,gatePlatformFeatures as Lo,readTargetDiagnostics as Do,vectorizeDimensionDiagnostics as Mo,liveStreamsDeliveryAuthorizationDiagnostic as _o,socketRoutesDeliveryAuthorizationDiagnostic as zo,studioPlatformFor as Ko,platformFeatureAvailable as $o}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Bo}from"./schema-BgM8A3XV.mjs";import{b as Yn,e as Vo}from"./shard-gWobaDx2.mjs";import{e as Uo,a as Wo}from"./server-DCjunXFf.mjs";import{emitDataModel as qo}from"./emitDataModel-Bba2y2yt.mjs";import{i as jo,a as Ho,e as Go,b as Yo,d as Qo,c as Xo}from"./unwrap-handler-return-DTcee6Ng.mjs";import Jo from"./discoverFunctions-BdEY3nbv.mjs";import Zo from"./discoverHttpRoutes-Hy2UrcrN.mjs";import ea from"./discoverInserts-DIzIGlyG.mjs";import{e as Qn}from"./exported-procedure-chains-BaCIhnJ7.mjs";import ta from"./discoverMigrations-Bv8kNIgy.mjs";import sa from"./discoverQueries-KjOdhrk6.mjs";import na from"./discoverRlsMetadata-Dq6iSXnC.mjs";import ia from"./discoverSchema-B6yDZ9Bb.mjs";import{discoverShapes as ra}from"./SHAPES_FILENAME-mgEi072Z.mjs";import{i as oa}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as aa}from"./emitApp-CT7iAjam.mjs";import{readJsonSync as ca}from"@visulima/fs";import{buildSchemaSnapshot as la}from"./SchemaSnapshotParseError-CjKSMuex.mjs";import{buildOpenApiDocument as da,emitOpenApiModule as ua}from"./buildOpenApiDocument-Cju685VK.mjs";import{buildOpenRpcDocument as fa,emitOpenRpcModule as ga}from"./OPENRPC_VERSION-CTR_g_IE.mjs";import{v as pa,t as ma,u as ha,s as va,w as Ea}from"./shard-runtime-DXlpfT3P.mjs";import{emitCollections as xa,emitSeed as Sa,emitApi as Aa,emitInternalApi as ya}from"./emitApi-CCjh0ICg.mjs";import{emitCrons as ba,emitScheduler as Na,emitShardRegistry as Pa,emitDurableObjects as wa,emitVectors as Ia,emitWranglerCronTriggers as Ta}from"./emitCrons-CY8IQfAI.mjs";import Ca from"./emitDrizzleSchema-CD4hPtUP.mjs";import{LAZY_FUNCTION_DIRECTORY as Xn,emitFunctions as Oa,emitLazyFunctionModules as ka}from"./emitFunctions-C3WOlVN0.mjs";const Ra=(e,t=!1)=>{if(e.length===0)return"";const s=ho(t),n=e.map(c=>{if(go(c.exportName,"live stream export name"),!po.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=>{mo(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 v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
1
+ import{existsSync as _,readFileSync as Xe,mkdirSync as Wt,writeFileSync as vr,rmSync as Ne,readdirSync as kn}from"node:fs";import{dirname as qt,join as E,relative as Rn}from"node:path";import{performance as Et}from"node:perf_hooks";import{runAdvisor as Er}from"@lunora/advisor";import{LunoraError as z}from"@lunora/errors";import{serializeSchemaSnapshot as xr}from"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import{toAdvisorContext as Sr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as jt,ts as Ar,VariableDeclarationKind as Ht}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as I,descendantsOfKind as x,bindingKeyName as le,collectCallRows as C,findObjectProperty as U,collectSecurityCallRows as yr,propertyInitializer as F,listSecurityScanFiles as Je,objectLiteralFromCallbackBody as Fn,limitNameOf as Ln,optionsObjectLiteral as Dn,handlerOf as br,collectNodeRows as ie,chainRootOf as Ze,outermostValueWrapper as T,isWriteTarget as et,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Gt,returningFunctionOf as Ct,walkChain as Nr,RUN_METHODS as Mn,functionReferenceSegments as Pr,isTestPath as wr,isFunctionLike as oe,functionKeyOf as _n,withSourceListMemo as Ir}from"./isTestPath-JdN4KXhV.mjs";import{b as X,d as H,f as D,g as Yt,c as S,a as Qt,w as Xt,k as Tr,l as Cr,h as Or,m as kr,j as Ot,i as Rr}from"./attribution-DUbGYT4N.mjs";import{a as _s,r as xt,i as Y,b as Fr,m as zn,c as tt,e as Jt,E as Kn,C as $n,d as Lr,f as Dr,g as Mr}from"./context-root-Bd08qiVR.mjs";import{a as w,i as _r,c as te,d as Bn,e as zr,f as Kr,g as Vn}from"./classify-procedure-call-DtqiTjPg.mjs";import{a as A,s as $r}from"./property-name-7cBlgK_O.mjs";import{b as Br,a as st}from"./module-specifiers-BctA0m_p.mjs";import{r as nt,s as Vr}from"./parse-validator-CP5CL6Q7.mjs";import Ur from"./discoverAuthApiCalls-Ce3BdKQr.mjs";import{i as K,r as Un}from"./database-calls-BSyvN1No.mjs";import Wr from"./discoverHyperdriveCalls-Cn3087D8.mjs";import{diagnosticAt as ue}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Zt,a as We,s as Wn,d as qr}from"./index-Cm7HdvL5.mjs";import{MUTATORS_FILENAME as jr,isDefineMutatorCallee as Hr,mutatorServerImplOf as Gr,discoverMutators as Yr}from"./MUTATORS_FILENAME-PNPCtUl2.mjs";import Qr from"./discoverNondeterministicCalls-DZ_kIie5.mjs";import{discoverNotifyConfig as Xr,discoverNotifyCalls as Jr}from"./NOTIFY_FILENAME-HXIKioYv.mjs";import Zr from"./discoverR2sqlCalls-B4N8iXlU.mjs";import eo from"./discoverRlsProcedures-DhOEyJLg.mjs";import{s as es,n as to}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as so,redact as no,isHeuristicSecretKind as io,isSecretishName as ro}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as qn,readMergeDurableObjects as oo}from"./loadProjectConfig-B7RmxIeD.mjs";import{a as Me,d as ao,r as co}from"./modules-DEBCI7Gm.mjs";import{WORKFLOWS_FILENAME as lo,discoverWorkflows as uo}from"./WORKFLOWS_FILENAME-VAXgqqP-.mjs";import{r as fo}from"./json-data-Chfs2Cz5.mjs";import{a as go,I as po,g as mo,G as jn,d as ho,i as vo}from"./shared-Br_OnErI.mjs";import{createCodegenProject as Eo}from"./createCodegenProject-DmXl8m_P.mjs";import{findTsconfig as kE,refreshCodegenProject as RE,tsconfigFingerprint as FE}from"./createCodegenProject-DmXl8m_P.mjs";import{CAPABILITIES as xo,usedCapabilities as So}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Hn,isHyperdriveGlobalTable as Gn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Ao}from"./AGENTS_FILENAME-BedyJsOT.mjs";import{discoverContainers as yo}from"./CONTAINERS_FILENAME-T1v8pyHN.mjs";import bo from"./discoverCrons-D-vJXsgx.mjs";import{contextPropertiesRead as No,fileWiresRequestSecretTool as Po,createTargetScope as wo,discoverFeatureUsage as Io}from"./capabilitiesUsedBy-Xncj__oq.mjs";import Yn from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as To,findProjectConfigFile as Co}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Oo}from"./QUEUES_FILENAME-Dt5RG_P0.mjs";import{discoverSandboxUsage as ko}from"./discoverSandboxUsage-CdGRnVU2.mjs";import{resolveServiceBindings as Ro}from"./readServiceBindings-BA49C6aN.mjs";import Fo from"./discoverStorageRulesMetadata-CJ7h6SPK.mjs";import{resolveCodegenTarget as kt,gatePlatformFeatures as Lo,readTargetDiagnostics as Do,vectorizeDimensionDiagnostics as Mo,liveStreamsDeliveryAuthorizationDiagnostic as _o,socketRoutesDeliveryAuthorizationDiagnostic as zo,studioPlatformFor as Ko,platformFeatureAvailable as $o}from"./DEFAULT_TARGET-3OLdJhTj.mjs";import{i as Bo}from"./schema-BgM8A3XV.mjs";import{b as Qn,e as Vo}from"./shard-wyX4XRYk.mjs";import{e as Uo,a as Wo}from"./server-8wMiVU6J.mjs";import{emitDataModel as qo}from"./emitDataModel-Bba2y2yt.mjs";import{i as jo,a as Ho,e as Go,b as Yo,d as Qo,c as Xo}from"./unwrap-handler-return-DTcee6Ng.mjs";import Jo from"./discoverFunctions-BdEY3nbv.mjs";import Zo from"./discoverHttpRoutes-Hy2UrcrN.mjs";import ea from"./discoverInserts-DIzIGlyG.mjs";import{e as Xn}from"./exported-procedure-chains-BaCIhnJ7.mjs";import ta from"./discoverMigrations-Bv8kNIgy.mjs";import sa from"./discoverQueries-KjOdhrk6.mjs";import na from"./discoverRlsMetadata-Dq6iSXnC.mjs";import ia from"./discoverSchema-DmkjooXZ.mjs";import{discoverShapes as ra}from"./SHAPES_FILENAME-mgEi072Z.mjs";import{i as oa}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as aa}from"./emitApp-CT7iAjam.mjs";import{readJsonSync as ca}from"@visulima/fs";import{buildSchemaSnapshot as la}from"./SchemaSnapshotParseError-CjKSMuex.mjs";import{buildOpenApiDocument as da,emitOpenApiModule as ua}from"./buildOpenApiDocument-Cju685VK.mjs";import{buildOpenRpcDocument as fa,emitOpenRpcModule as ga}from"./OPENRPC_VERSION-CTR_g_IE.mjs";import{v as pa,t as ma,u as ha,s as va,w as Ea}from"./shard-runtime-DXlpfT3P.mjs";import{emitCollections as xa,emitSeed as Sa,emitApi as Aa,emitInternalApi as ya}from"./emitApi-CCjh0ICg.mjs";import{emitCrons as ba,emitScheduler as Na,emitShardRegistry as Pa,emitDurableObjects as wa,emitVectors as Ia,emitWranglerCronTriggers as Ta}from"./emitCrons-CY8IQfAI.mjs";import Ca from"./emitDrizzleSchema-CD4hPtUP.mjs";import{LAZY_FUNCTION_DIRECTORY as Jn,emitFunctions as Oa,emitLazyFunctionModules as ka}from"./emitFunctions-C3WOlVN0.mjs";const Ra=(e,t=!1)=>{if(e.length===0)return"";const s=ho(t),n=e.map(c=>{if(go(c.exportName,"live stream export name"),!po.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=>{mo(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 v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
2
  __lunoraLive: ${m},
3
3
  topic: \`${u.name}:${v}\`,
4
4
  }),`});return` ${c.exportName}: {
5
5
  ${l.join(`
6
6
  `)}
7
- },`}),a=e.some(c=>c.topics.some(l=>l.fields.length>0))?"LiveTopicKey, LiveTopicPayload, LiveTopicRef":"LiveTopicPayload, LiveTopicRef";return`${qn}import type { ${a} } from "${s.server}";
7
+ },`}),a=e.some(c=>c.topics.some(l=>l.fields.length>0))?"LiveTopicKey, LiveTopicPayload, LiveTopicRef":"LiveTopicPayload, LiveTopicRef";return`${jn}import type { ${a} } from "${s.server}";
8
8
 
9
9
  ${n.join(`
10
10
  `)}
@@ -18,14 +18,14 @@ export const live = {
18
18
  ${i.join(`
19
19
  `)}
20
20
  };
21
- `},Jn=new Set(["delete","get","head","options","patch","post","put"]),Fa=new Set(["handler","stream"]),La=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ds=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Da=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Jn.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Ma=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||Jn.has(n.getName()))break;s=n.getExpression()}return Da(s)},_a=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Ds.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Ds.has(s.getText()))return!0}return!1},za=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Fa.has(n.getName()))return;const i=Ma(s);if(!i||!La.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&_a(o);return{exportName:H(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Ka=(e,t)=>{const s=[];for(const n of X(e)){const i=za(n,t);i&&s.push(i)}return s},$a=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ka(i,I(t,n)))}return s},Ba=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Va=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?le(t):void 0}},Ua=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Ls(a)}))return!1;const n=D(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Ls(i)},Ms=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Ba(e);return n!==void 0&&Va(n)===t?!0:t==="args"&&Ua(e)},Zn=(e,t)=>r.isIdentifier(e)?Ms(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Ms(s,t)),Wa=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},_s=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!jt(t)?t.getInitializer():void 0},Ot=e=>Zn(e,"args"),Q=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of x(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},j=e=>{if(Ot(e))return!0;const t=Q(e);return t!==void 0&&Ot(t)},qa=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=Q(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},de=e=>{if(Et(e))return!0;const t=_s(e);if(t!==void 0&&Et(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=_s(i);return o!==void 0&&Et(o)})},_e=(e,t)=>Zn(e,t),ja=(e,t)=>{if(_e(e,t))return!0;const s=Q(e);if(s!==void 0&&_e(s,t))return!0;const n=Wa(e);if(n!==void 0){const i=Q(n);return i!==void 0&&_e(i,t)}return!1},Ha=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Y(e.getExpression(),["ai"]),Ga=(e,t)=>{if(!Ha(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)||de(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Ya=(e,t)=>C(e,t,Ga),Qa=new Set(["generateText","streamText"]),Xa=new Set(["messages","prompt","system"]),Ja=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Za=(e,t)=>Ja.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ec=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Fr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Za(i,s));return n===void 0?void 0:`${n}.${s}`},tc=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ec(t);if(s!==void 0)return s}},sc=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=le(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},nc=e=>{if(Ot(e))return!0;const t=sc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},ic=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!Xa.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&nc(s))return!0}return!1},rc=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=w(n.getExpression());if(i===void 0||!Qa.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(w(c.getExpression())==="tool"&&(a=tc(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:ic(o)})}return s},oc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...rc(i,I(t,n)))}return s},ac=e=>Y(e,["fetch"]),cc=(e,t)=>{if(!ac(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},lc=(e,t)=>C(e,t,cc),Jt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=st(s.getExpression());return n===void 0||Jt(n,t)})}finally{t.delete(e)}},dc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=U(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:st(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Jt(i)}},uc=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?st(o):void 0;a===void 0?s=!0:(t.push(a),s||=Jt(a))}n=i.getExpression()}return{objects:t,opaque:s}},Zt=(e,t)=>t?uc(t):dc(e),ei=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=st(s.getExpression());return n===void 0?[]:ei(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},fc=e=>e.flatMap(t=>ei(t,new Set)),gc=new Set(["check","length","max"]),kt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(gc.has(s.getName()))return!0;t=n}},Rt=e=>Br(e)||e==="@lunora/values",pc=e=>{const t=new Set(["v"]);for(const s of _r(e,"v",Rt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Rt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},mc=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},hc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),vc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Rt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),es=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return hc(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&vc(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Ec=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},xc=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Sc=e=>r.isReturnStatement(e)?e.getExpression():void 0,Ac=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>xc(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Sc(t);return s?[s]:[]}),ti=(e,t)=>{if(es(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return ti(e.getExpression(),t)},yc=(e,t)=>{const s=Ec(e.getExpression(),e.getSourceFile());if(!s)return[];const n=kt(e),i=new Set(Ac(s).map(o=>ti(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=es(o,t);return a===void 0?[]:[{bounded:kt(o)||n&&i.has(o),factory:a}]})},bc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=es(s,t),i=n===void 0?[]:[{bounded:kt(s),factory:n}];return r.isCallExpression(s)?[...i,...yc(s,t)]:i}),Nc=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=bc(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Pc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=te(n);if(i?.visibility!=="public")return;const{objects:o}=Zt(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Nc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:H(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},wc=(e,t)=>{const s=[],n=pc(e),i={destructured:mc(e,n),namespaces:n};for(const o of X(e)){const a=Pc(o,t,i);a&&s.push(a)}return s},Ic=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wc(i,I(t,n)))}return s},xt=e=>e?.getKind()===d.TrueKeyword,Tc=e=>e?.getKind()===d.FalseKeyword,Cc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Oc=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),kc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&w(t.getExpression())==="scim"),Rc=e=>e!==void 0&&r.isCallExpression(e)&&Oc.has(w(e.getExpression())??""),Fc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),Lc=e=>{const t=F(e,"advanced"),s=F(e,"emailAndPassword"),n=F(e,"session");return{analyzable:!0,disableCsrfCheck:xt(F(t,"disableCSRFCheck")),emailPasswordEnabled:xt(F(s,"enabled")),requireEmailVerification:xt(F(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:kc(F(e,"plugins"))&&Rc(F(e,"database")),secureCookiesDisabled:Tc(F(t,"useSecureCookies")),sessionFreshAgeZero:Cc(F(n,"freshAge")),trustedOriginsWildcard:Fc(F(e,"trustedOrigins"))}},Dc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Mc=(e,t)=>{if(w(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?Lc(s):Dc();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},_c=(e,t)=>yr(e,t,Mc),zc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return _n(e.getExpression(),t.matchReceiver)?s:void 0},Kc=(e,t,s)=>{const n=zc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!j(i)||de(i))&&!(s.requireUnmodifiedReach===!0&&!qa(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},nt=(e,t,s)=>C(e,t,(n,i)=>Kc(n,i,s)),$c=new Set(["content","pdf","scrape","screenshot"]),Bc=(e,t)=>nt(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:$c}),Vc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Uc=new Set(["RateLimiter"]),Wc=new Set(["extend"]),zs="lunora",qc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],si=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Ft=e=>e&&r.isObjectLiteralExpression(e)?si(e):{analyzable:!1,presentKeys:[],trueKeys:[]},jc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Rn(t.getBody());return s?si(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Hc=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=w(n.getExpression());i!==void 0&&(Vc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Ft(n.getArguments()[0])}):Wc.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...jc(n.getArguments()[0])}))}for(const n of x(e,d.NewExpression)){const i=w(n.getExpression());i===void 0||!Uc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Ft(n.getArguments()[0])})}return s},Gc=e=>{for(const t of qc){const s=E(e,t);if(!_(s))continue;const n=new Wt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Qe(s,"utf8")),i=[];for(const o of x(n,d.CallExpression))w(o.getExpression())===zs&&i.push({callee:zs,file:t,line:o.getStartLineNumber(),...Ft(o.getArguments()[0])});return i}return[]},Yc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Xe(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Hc(o,n))}return s.push(...Gc(Ut(t))),s},Ks="ctx.containers.",Qc=e=>{if(!e.startsWith(Ks))return!1;const t=e.slice(Ks.length);return t.length>0&&!t.includes(".")},Xc=(e,t)=>nt(e,t,{argIndex:0,matchReceiver:Qc,methods:new Set(["get"])}),Jc=new Set(["allow","deny","setAllowed"]),Zc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=U(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},el=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Zc(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},tl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Jc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},sl=(e,t)=>el(e,t)??tl(e,t),nl=(e,t)=>C(e,t,sl),il=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&$(s.getExpression())?s.getName():void 0},rl=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&$(s)?1:0]},ol=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),al=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>ol.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},cl=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return C(e,t,(i,o)=>{const a=il(i);if(a===void 0)return;const c=al(rl(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},ll=new Set(["defineExportSink","r2Sink","webhookExportSink"]),dl=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return ll.has(s)?s:void 0},ul=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},fl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Xe(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of x(o,d.CallExpression)){const c=dl(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?ul(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},gl=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),pl=new Set(["dbRateLimit","rateLimit"]),ml=e=>{const t=Ln(e);if(!t)return!1;const s=U(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},hl=(e,t)=>{const s=w(e.getExpression());if(s===void 0)return;const n=gl.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:ml(e.getArguments()[n]),file:t,limitName:pl.has(s)?Fn(e):"",line:e.getStartLineNumber()}},vl=(e,t)=>C(e,t,hl),El=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=te(t);if(s?.kind!=="query")return;const n=br(t,s.receiver);return n?{exportName:H(e)??e.getName(),handler:n}:void 0},$s=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},xl=e=>{const t=$s(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=$s(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Sl=(e,t)=>{const s=[];for(const n of et(e.handler,"flags"))s.push({callee:xl(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Al=(e,t)=>{const s=[];for(const n of X(e)){const i=El(n);i&&s.push(...Sl(i,t))}return s},yl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Al(i,I(t,n)))}return s},bl=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Y(e.getExpression(),["flags"]),Nl=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Pl=(e,t)=>{if(!bl(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Nl(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},wl=(e,t)=>C(e,t,Pl),Il=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Tl=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Cl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of x(i,d.CallExpression))Il(a)&&s.push({file:o,indexName:Tl(a),line:a.getStartLineNumber()})}return s},Pe=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,ni=e=>{const t=e.getArguments()[0],s=Pe(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=U(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?Pe(n.getInitializer()):void 0},Ol=new Set(["delete","get","head","options","patch","post","put"]),kl=new Set(["handler","stream"]),Rl=new Set(["runAction","runMutation"]),Fl=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),we=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,ii=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(le(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Bs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:ii(s,"ctx")},Vs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:ii(s,"request")},Us=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Rl.has(a)&&we(c,t))return a;if(Fl.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&we(c.getExpression(),t))return`db.${a}`}},Ws=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&we(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!we(n.getInitializer(),t))){for(const o of i.getElements())if(le(o)==="auth")return!0}}return!1},Ll=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Dl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&we(n.getExpression(),t)},Ml=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],ri=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Ml(s)},_l=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?ri(t,a.getText()):[]}return[]},zl=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=ri(s,t.getText());return n.length>0?n:_l(t,s)},qs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>Dl(i,t)&&zl(i).some(o=>Ll.test(o)))},Kl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!kl.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Ol.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},$l=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Pe(e.getArguments()[0]),l=c&&Bs(c,!0);if(!c||l===void 0||qs(c,Vs(c,!0)))return;const u=Us(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Ws(c,l),sideEffect:u}}const n=Kl(e);if(n===void 0)return;const i=Pe(e.getArguments()[0]),o=i&&Bs(i,!1);if(!i||o===void 0||qs(i,Vs(i,!1)))return;const a=Us(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Ws(i,o),sideEffect:a}},Bl=(e,t)=>C(e,t,$l),Vl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Ul=new Set(["append","set"]),oi=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",js=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Vl.has(w(n.getExpression())??"")&&_e(n,t)),Wl=(e,t)=>{if(js(e,t))return!0;const s=Q(e);return s!==void 0&&js(s,t)},Lt=(e,t)=>ja(e,t)&&!Wl(e,t),ql=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&r.isNewExpression(t)&&w(t.getExpression())==="Headers"},We=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},ts=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Lt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:oi(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Lt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=We(n.getExpression());i!==void 0&&ts(i,t,s)}},ai=(e,t)=>{const s=We(e);if(s===void 0)return;const n=U(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=We(n.getInitializer());i!==void 0&&ts(i,"response-init",t)},jl=(e,t)=>{const s=w(e.getExpression());if(s==="Response")ai(e.getArguments()[1],t);else if(s==="Headers"){const n=We(e.getArguments()[0]);n!==void 0&&ts(n,"headers-ctor",t)}},Hl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){ai(e.getArguments()[1],t);return}if(Ul.has(n)&&ql(i)){const o=e.getArguments()[1];o!==void 0&&Lt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:oi(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Gl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))jl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Hl(s,t)},Yl=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Pe(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return Gl(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},Ql=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression))s.push(...Yl(n,t));return s},Xl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ql(i,I(t,n)))}return s},ci="identity.ts",Jl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return tt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Zl=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&&tt(n.getModuleSpecifierValue())}return!1},ed=e=>{if(r.isIdentifier(e))return Jl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Zl(t)}return!1},td=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!ed(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ue(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Ht(s,"member");a!==void 0&&t.push({exportName:a})}return t},sd=(e,t)=>{const s=E(t,ci);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=td(n);if(i.length!==0){if(i.length>1)throw ue(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},nd=new Set(["auth","context.auth"]),id="userId",rd=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},od=(e,t)=>{const s=E(t,ci);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(w(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?rd(o):void 0}},Hs=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return nd.has(t.getText())||Y(t,["auth"])?e:void 0},ad=e=>{if(r.isPropertyAccessExpression(e)&&Hs(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Hs(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},Gs=(e,t,s)=>{const n=ad(e);return n===void 0?void 0:{declared:n===id||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},cd=(e,t)=>{const s=od(e,t);return s===void 0?[]:[...ie(e,t,d.PropertyAccessExpression,(n,i)=>Gs(n,i,s)),...ie(e,t,d.ElementAccessExpression,(n,i)=>Gs(n,i,s))]},ld=(e,t)=>{if(w(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=F(s,"key");if(!(!n||!j(n)||de(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},dd=(e,t)=>C(e,t,ld),ud=new Set(["delete","get","getRaw","getWithMetadata","put"]),fd=(e,t,s=[])=>{const n=nt(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ud});return Gt(n,s)},gd=new Set(["queue","send"]),Ys=new Set(["bcc","cc","to"]),pd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!gd.has(t))return;const s=e.getExpression();return Y(s,["mail"])||Y(s,["email"])?t:void 0},md=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ys.has(A(t))&&j(n)&&!de(n)}if(!r.isPropertyAssignment(t)||!Ys.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&j(s)&&!de(s)}):!1,hd=(e,t)=>{const s=pd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!md(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},vd=(e,t)=>C(e,t,hd),Ed=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Ue(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Ue(l);if(u===void 0)continue;const f=Un(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},xd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;return n?.receiver?Qt(n.receiver).flatMap(i=>Ed(i,H(e)??e.getName(),t)):[]},Sd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...xd(a,o))}return s},Ad=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},yd=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=U(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},bd=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Hr(s.getExpression())?s:void 0},Nd=e=>{const t=bd(e),s=t===void 0?void 0:yd(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?H(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Ad(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Pd=e=>e.getVariableDeclarations().flatMap(t=>Nd(t)),wd=(e,t)=>{const s=E(t,jr);if(!_(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Pd(n)},Id=new Set(["delete","get","patch"]),Td=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Cd=new Set(["auth","identity","session","user"]),Od=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),kd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!$(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Rd=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},Fd=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Ld=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Dd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Fd(s.getExpression(),t)&&Ld(s.getThenStatement())),Md=(e,t)=>{for(const s of x(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Id.has(i))continue;const o=n.getExpression(),a=$(o);if(!(a||r.isPropertyAccessExpression(o)&&$(o.getExpression())))continue;const l=a&&i==="get"?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},_d=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Yt(Je(s))!==void 0)),zd=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Od.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Kd=e=>{for(const t of x(e,d.Identifier))if(Td.has(t.getText()))return!0;return[...Cd].some(t=>et(e,t).length>0)?!0:_d(e)||zd(e)},$d=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=ni(s);if(i===void 0)return[];const o=n.receiver!==void 0&&$n(n.receiver,"use","rls"),a=Kd(i),c=new Set,l=[];for(const u of x(i,d.CallExpression)){const f=kd(u);if(f===void 0)continue;const g=Rd(u);if(g===void 0||c.has(g)||!Dd(i,g))continue;const m=Md(i,g);m!==void 0&&(c.add(g),l.push({exportName:H(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},Bd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...$d(a,o))}return s},li=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?D(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Vd=e=>{const t=T(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!Ze(s)},Ud=e=>{const t=T(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Wd=e=>{const s=T(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!Ze(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},qe=e=>{const t=D(e);return t===void 0||Cr(t.getSourceFile())},Dt=(e,t)=>{const s=T(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&qe(o);if(li(Je(o),t))return!(r.isPropertyAccessExpression(o)&&zn.has(o.getName()))||r.isExpressionStatement(T(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!qe(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},ze={kind:"opaque"},qd={kind:"unreached"},jd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Mt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?D(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=jd(s);return i===void 0||jt(i)?void 0:i}const n=re(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},di=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?ze:c===void 0?a.some(l=>l.isRestParameter())?ze:qd:c.isRestParameter()?ze:{kind:"parameter",parameter:c}},Hd=e=>{const t=T(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Mt(s.getExpression());return n===void 0?ze:di(n,s,t)},Gd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Yd=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,ui=e=>{const t=T(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=Yd(s);if(n!==void 0)return b(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},Qd=4,fi=(e,t,s=0)=>{if(Tr(e))return!0;if(Vd(e)){const i=T(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!Gd.has(c)}if(Ud(e)||Wd(e)||ui(e)||Dt(e,t))return!0;const n=Hd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Xd(n.parameter,s+1)},Qs=new WeakMap,Xd=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Qs.get(e.compilerNode);if(n!==void 0)return n;if(t>Qd)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||D(a)?.compilerNode!==e.compilerNode||fi(a,void 0,t));return(o||t===0)&&Qs.set(e.compilerNode,o),o},Xs=new WeakMap,Jd=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=D(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Zd=(e,t,s)=>{const{context:n,impl:i}=e,o=Xs.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const m=g.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?fi(g,n):!Ze(g),f=!Jd(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const m=g.getText();if(m==="arguments")return!1;const v=l.get(m);return v===void 0||c.includes(g)||D(g)?.compilerNode!==v?!0:u(g)});return Xs.set(i.compilerNode,f),f},Js=new WeakMap,eu=e=>{let t=Js.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Gr(s);return n===void 0?[]:[[n.compilerNode,s]]})),Js.set(e.compilerNode,t)),t},tu=e=>{const t=eu(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:H(n)??n.getName()};return a!==void 0&&Zd(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},St="args",Se=e=>{const t=qt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===St?t.member:void 0}if(!r.isIdentifier(e))return;const s=D(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=re(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&le(i)===St||r.isIdentifier(o)&&o.getText()===St?le(s):void 0},su=new Set(["auth","identity","user"]),_t=e=>{const t=i=>{const o=Yt(i);return o!==void 0&&o.length>0&&su.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=Q(s);return n!==void 0&&t(n)},gi=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Se(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?Q(n):void 0;if(o!==void 0)for(const a of gi(o,t-1))s.add(a)}return s},Ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Ke(n),...Ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=Se(h(u)??u);return g===void 0?[]:Ke(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Se(h(n)??n),c=Se(h(i)??i);return a!==void 0&&_t(i)&&o.push(a),c!==void 0&&_t(n)&&o.push(c),o},nu=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&zr(i.getExpression(),"defineIdentityGuard")},iu=e=>{if(!nu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Se(h(s)??s),o=t.some((a,c)=>c!==n&&_t(a));return i!==void 0&&o?[i]:[]})},ru=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},ou=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Zs=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},au=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),cu=(e,t)=>{const s=new Set;for(const n of x(e,d.IfStatement))if(n.getEnd()<=t&&Zs(n,e)&&ru(n.getThenStatement()))for(const i of Ke(n.getExpression()))s.add(i);for(const n of x(e,d.CallExpression))if(n.getEnd()<=t&&au(n)&&Zs(n,e))for(const i of iu(n))s.add(i);return s},lu=(e,t)=>{const s=gi(t);if(s.size===0)return!1;const n=e.getFirstAncestor(ou);if(n===void 0)return!1;const i=cu(n,e.getStart());return[...s].every(o=>i.has(o))},du=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),uu=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),zt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),pi=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),fu=e=>{const t=T(e),s=t.getParent();if(r.isVariableDeclaration(s))return b(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},gu=e=>{const t=fu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||re(t)?[t]:void 0:pi(t)},Ae=e=>e.isUnion()?e.getUnionTypes().every(t=>Ae(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Ae(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),je=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},$e=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},pu=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&uu.get(s.getText())?.has(t.getName())===!0&&qe(s)},mu=e=>{const t=It(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=T(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&je(n,Kn)?n:void 0},hu=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=T(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:je(n,du,t)?n:void 0},vu=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Eu=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&b(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},en=e=>{const t=T(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&pu(s);return hu(s,t)??vu(s,t)??Eu(s,t)??(n?s:mu(t))},xu=5e4,mi=()=>({inProgress:new Set,verdicts:new Map});class Su{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>xu&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Au=8,yu=8;class bu{budget;scope;taint;verdicts=mi();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Ae(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?pi(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Au?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(T(l),!0,a,0))&&(t===n||!Ae(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=en(o);m!==void 0;m=en(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=T(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Ae(o.getType());if(Ze(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=gu(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=T(t).getParent();if(n>=yu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===T(t)?this.valueCompromises(i,!1,s,n+1):!je(i,zt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||re(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=T(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>$e(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=je(t,zt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Mt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!Dt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(Dt(s,this.scope.context))return!1;const i=Mt(t.getExpression()),o=i===void 0?void 0:di(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||ui(t)||b(It(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=It(t);return b(s,this.scope.impl)?void 0:s}}const Nu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Pu=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=D(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},wu=new Set(["all","allSettled","any","race"]),tn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,At=8;class Iu{budget=new Su;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=mi();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new bu(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,At)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>Or(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=D(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=T(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!zt.has(g.getName()))return!0;const m=a.getArguments().filter(v=>v!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(v=>this.isTaintedValue(v,!1))}const c=r.isVariableDeclaration(a)&&re(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const m=T(g),v=m.getParent();return!r.isCallExpression(v)||v.getExpression()!==m||this.isCallSiteTainted(v,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&qe(i)&&wu.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:$e(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=D(t),i=tn(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&zn.has(i)?!1:i!==void 0&&Kn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>$e(a)!==void 0)&&(i===void 0||!Nu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Je(i),c=r.isIdentifier(a)?tn(D(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=$e(i);if(o===void 0)return!Pu(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Nr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(li(i,this.scope.context))return!0;const o=r.isIdentifier(i)?D(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=re(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=jt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,At))return!1;if(this.variableDepth>=At)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const sn=new WeakMap,Tu=e=>{const t=sn.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Iu(e);return sn.set(e.impl.compilerNode,s),s},Cu=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Ou=new Set(["insert","insertManyUnsafe","patch","replace"]),ku=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Ou.has(t)&&Lr(e.getExpression())?t:void 0},Ru=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},Fu=(e,t)=>{const s=qt(e);return s?.member===t?h(s.object):void 0},nn=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,hi=(e,t,s,n=1)=>{const i=Fu(e,s);if(i!==void 0)return nn(i,t);const o=r.isIdentifier(e)?D(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&le(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||re(l)&&nn(h(l.getInitializer()),t))}const a=re(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&hi(a,t,s,n-1)},Kt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Kt(t.getWhenTrue()),...Kt(t.getWhenFalse())]:[t]},Lu=(e,t,s)=>{const n=[],i=s===void 0?void 0:Tu(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!Cu.has(a))continue;const l=Kt(c).filter(f=>i===void 0?j(f)&&!Dr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&hi(c,s.parameter,a),g=l.every(m=>lu(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Du=(e,t,s)=>{const n=ku(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=Ru(i,n);if(o.length===0)return[];const a=S(e),c=tu(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Lu(u,l,c))},Mu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=C(e,t,(c,l)=>Du(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Gt(o,s).map(c=>kr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},_u=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),zu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Ku=e=>{const t=U(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?zu(t.getInitializer()):void 0},$u=(e,t)=>{const s=w(e.getExpression());if(s===void 0||!_u.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Ku(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Bu=(e,t)=>C(e,t,$u),Vu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Uu=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Wu=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=U(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},vi=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Ei=(e,t)=>e===t||e.startsWith(`${t}.`),xi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},rn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},Si=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>rn(s));return r.isIdentifier(e)&&rn(e)&&t.push(e),t},qu=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},ju=e=>{const t=vi(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Hu=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:ju(e),i=new Set,o=a=>xi(a).some(c=>n.some(l=>Ei(c.getText(),l)))?!0:Si(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of qu(a))i.add(l)}return{names:i,prefixes:n}},Gu=(e,t)=>xi(e).some(s=>t.prefixes.some(n=>Ei(s.getText(),n)))?!0:Si(e).some(s=>t.names.has(s.getText())),Yu=e=>{const t=Pr(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Qu=(e,t,s)=>{const n=vi(e,0);if(n===void 0)return[];const i=Hu(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!Dn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Gu(u,i))continue;const f=Yu(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:S(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Xu=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=Uu(n),o=i===void 0?void 0:Vu.get(i);if(o===void 0)continue;const a=Wu(n,o);a!==void 0&&s.push(...Qu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Ju=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xu(i,I(t,n)))}return s},on={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},an=new Set(["account","credential","member","passkey","session","user"]),Zu=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ef=e=>{const s=Zu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return an.has(s)||an.has(n)},tf=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},sf=(e,t)=>{const{objects:s,opaque:n}=Zt(e,t);return fc(s).some(i=>tf(i))?!0:n?void 0:!1},nf=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!U(t,"captcha"),usesRateLimit:!!U(t,"rateLimit")}},rf=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Be={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},of=e=>{const t=rf(e),s=t?w(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=nf(t);return{...Be,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in on?{...Be,[on[s]]:!0}:Be},af=e=>{const t={...Be};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=of(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},cf=new Set(["insert","insertMany","insertManyUnsafe","replace"]),lf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!cf.has(t.getName()))return!1;const s=t.getExpression();if(!$(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:ef(i.getLiteralText())},df=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),cn=new Set(["queues","scheduler","topics","workflows"]),uf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!df.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&cn.has(s.getName())&&Mr(s.getExpression()))return!0;s=s.getExpression()}const n=Yt(s);return n?.length===1&&cn.has(n[0]??"")},ff=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},Ai=new Set(["generateObject","generateText","streamObject","streamText"]),gf=e=>{const t=w(e.getExpression());return t!==void 0&&Ai.has(t)},pf=e=>{const t=w(e.getExpression());if(t===void 0||!Ai.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!U(s,"maxOutputTokens")},mf=new Set(["log","span","trace"]),hf=new Set(["ai"]),vf=new Set(["email","mail"]),Ef=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),yt=(e,t)=>[...t].some(s=>et(e,s).length>0),yi=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),xf=new Set(["every","filter","flatMap","forEach","map","some"]),Sf=new Set(["all","allSettled","race"]),bi=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(xf.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Sf.has(n))return t},Af=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(yi.has(t.getKind())){const s=bi(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},yf=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(yi.has(t.getKind())){if(t=bi(t),t===void 0)return!1;continue}t=t.getParent()}return!1},bf=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const v=m.getExpression();return r.isIdentifier(v)&&v.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Nf=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Pf=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},wf=e=>{let t=!1,s=!0;for(const n of[...Ef].flatMap(i=>et(e,i))){const i=Pf(n);i&&(t=!0,!Af(i)&&!Nf(i)&&!bf(i)&&!yf(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},If=e=>x(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),ln="lunora-advisor-exempt",Tf=/^[\s*/]+/u,Cf=/[\w-]/u,Of=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
21
+ `},Zn=new Set(["delete","get","head","options","patch","post","put"]),Fa=new Set(["handler","stream"]),La=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,zs=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Da=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Zn.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Ma=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||Zn.has(n.getName()))break;s=n.getExpression()}return Da(s)},_a=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(zs.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&zs.has(s.getText()))return!0}return!1},za=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Fa.has(n.getName()))return;const i=Ma(s);if(!i||!La.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&_a(o);return{exportName:H(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Ka=(e,t)=>{const s=[];for(const n of X(e)){const i=za(n,t);i&&s.push(i)}return s},$a=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ka(i,I(t,n)))}return s},Ba=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Va=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?le(t):void 0}},Ua=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&_s(a)}))return!1;const n=D(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&_s(i)},Ks=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Ba(e);return n!==void 0&&Va(n)===t?!0:t==="args"&&Ua(e)},ei=(e,t)=>r.isIdentifier(e)?Ks(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Ks(s,t)),Wa=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},$s=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Yt(t)?t.getInitializer():void 0},Rt=e=>ei(e,"args"),Q=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of x(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},j=e=>{if(Rt(e))return!0;const t=Q(e);return t!==void 0&&Rt(t)},qa=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=Q(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},de=e=>{if(xt(e))return!0;const t=$s(e);if(t!==void 0&&xt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=$s(i);return o!==void 0&&xt(o)})},_e=(e,t)=>ei(e,t),ja=(e,t)=>{if(_e(e,t))return!0;const s=Q(e);if(s!==void 0&&_e(s,t))return!0;const n=Wa(e);if(n!==void 0){const i=Q(n);return i!==void 0&&_e(i,t)}return!1},Ha=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Y(e.getExpression(),["ai"]),Ga=(e,t)=>{if(!Ha(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)||de(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Ya=(e,t)=>C(e,t,Ga),Qa=new Set(["generateText","streamText"]),Xa=new Set(["messages","prompt","system"]),Ja=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Za=(e,t)=>Ja.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ec=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Fr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Za(i,s));return n===void 0?void 0:`${n}.${s}`},tc=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ec(t);if(s!==void 0)return s}},sc=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=le(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},nc=e=>{if(Rt(e))return!0;const t=sc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},ic=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!Xa.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&nc(s))return!0}return!1},rc=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=w(n.getExpression());if(i===void 0||!Qa.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(w(c.getExpression())==="tool"&&(a=tc(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:ic(o)})}return s},oc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...rc(i,I(t,n)))}return s},ac=e=>Y(e,["fetch"]),cc=(e,t)=>{if(!ac(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},lc=(e,t)=>C(e,t,cc),ts=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=nt(s.getExpression());return n===void 0||ts(n,t)})}finally{t.delete(e)}},dc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=U(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:nt(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:ts(i)}},uc=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?nt(o):void 0;a===void 0?s=!0:(t.push(a),s||=ts(a))}n=i.getExpression()}return{objects:t,opaque:s}},ss=(e,t)=>t?uc(t):dc(e),ti=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=nt(s.getExpression());return n===void 0?[]:ti(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},fc=e=>e.flatMap(t=>ti(t,new Set)),gc=new Set(["check","length","max"]),Ft=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(gc.has(s.getName()))return!0;t=n}},Lt=e=>Br(e)||e==="@lunora/values",pc=e=>{const t=new Set(["v"]);for(const s of _r(e,"v",Lt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Lt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},mc=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},hc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),vc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Lt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),ns=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return hc(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&vc(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Ec=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},xc=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Sc=e=>r.isReturnStatement(e)?e.getExpression():void 0,Ac=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>xc(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Sc(t);return s?[s]:[]}),si=(e,t)=>{if(ns(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return si(e.getExpression(),t)},yc=(e,t)=>{const s=Ec(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Ft(e),i=new Set(Ac(s).map(o=>si(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=ns(o,t);return a===void 0?[]:[{bounded:Ft(o)||n&&i.has(o),factory:a}]})},bc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=ns(s,t),i=n===void 0?[]:[{bounded:Ft(s),factory:n}];return r.isCallExpression(s)?[...i,...yc(s,t)]:i}),Nc=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=bc(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Pc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=te(n);if(i?.visibility!=="public")return;const{objects:o}=ss(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Nc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:H(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},wc=(e,t)=>{const s=[],n=pc(e),i={destructured:mc(e,n),namespaces:n};for(const o of X(e)){const a=Pc(o,t,i);a&&s.push(a)}return s},Ic=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wc(i,I(t,n)))}return s},St=e=>e?.getKind()===d.TrueKeyword,Tc=e=>e?.getKind()===d.FalseKeyword,Cc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Oc=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),kc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&w(t.getExpression())==="scim"),Rc=e=>e!==void 0&&r.isCallExpression(e)&&Oc.has(w(e.getExpression())??""),Fc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),Lc=e=>{const t=F(e,"advanced"),s=F(e,"emailAndPassword"),n=F(e,"session");return{analyzable:!0,disableCsrfCheck:St(F(t,"disableCSRFCheck")),emailPasswordEnabled:St(F(s,"enabled")),requireEmailVerification:St(F(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:kc(F(e,"plugins"))&&Rc(F(e,"database")),secureCookiesDisabled:Tc(F(t,"useSecureCookies")),sessionFreshAgeZero:Cc(F(n,"freshAge")),trustedOriginsWildcard:Fc(F(e,"trustedOrigins"))}},Dc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Mc=(e,t)=>{if(w(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?Lc(s):Dc();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},_c=(e,t)=>yr(e,t,Mc),zc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return zn(e.getExpression(),t.matchReceiver)?s:void 0},Kc=(e,t,s)=>{const n=zc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!j(i)||de(i))&&!(s.requireUnmodifiedReach===!0&&!qa(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},it=(e,t,s)=>C(e,t,(n,i)=>Kc(n,i,s)),$c=new Set(["content","pdf","scrape","screenshot"]),Bc=(e,t)=>it(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:$c}),Vc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Uc=new Set(["RateLimiter"]),Wc=new Set(["extend"]),Bs="lunora",qc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ni=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Dt=e=>e&&r.isObjectLiteralExpression(e)?ni(e):{analyzable:!1,presentKeys:[],trueKeys:[]},jc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Fn(t.getBody());return s?ni(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Hc=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=w(n.getExpression());i!==void 0&&(Vc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Dt(n.getArguments()[0])}):Wc.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...jc(n.getArguments()[0])}))}for(const n of x(e,d.NewExpression)){const i=w(n.getExpression());i===void 0||!Uc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Dt(n.getArguments()[0])})}return s},Gc=e=>{for(const t of qc){const s=E(e,t);if(!_(s))continue;const n=new jt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Xe(s,"utf8")),i=[];for(const o of x(n,d.CallExpression))w(o.getExpression())===Bs&&i.push({callee:Bs,file:t,line:o.getStartLineNumber(),...Dt(o.getArguments()[0])});return i}return[]},Yc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Je(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Hc(o,n))}return s.push(...Gc(qt(t))),s},Vs="ctx.containers.",Qc=e=>{if(!e.startsWith(Vs))return!1;const t=e.slice(Vs.length);return t.length>0&&!t.includes(".")},Xc=(e,t)=>it(e,t,{argIndex:0,matchReceiver:Qc,methods:new Set(["get"])}),Jc=new Set(["allow","deny","setAllowed"]),Zc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=U(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},el=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Zc(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},tl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Jc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},sl=(e,t)=>el(e,t)??tl(e,t),nl=(e,t)=>C(e,t,sl),il=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&K(s.getExpression())?s.getName():void 0},rl=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&K(s)?1:0]},ol=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),al=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>ol.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},cl=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return C(e,t,(i,o)=>{const a=il(i);if(a===void 0)return;const c=al(rl(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},ll=new Set(["defineExportSink","r2Sink","webhookExportSink"]),dl=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return ll.has(s)?s:void 0},ul=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},fl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Je(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of x(o,d.CallExpression)){const c=dl(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?ul(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},gl=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),pl=new Set(["dbRateLimit","rateLimit"]),ml=e=>{const t=Dn(e);if(!t)return!1;const s=U(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},hl=(e,t)=>{const s=w(e.getExpression());if(s===void 0)return;const n=gl.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:ml(e.getArguments()[n]),file:t,limitName:pl.has(s)?Ln(e):"",line:e.getStartLineNumber()}},vl=(e,t)=>C(e,t,hl),El=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=te(t);if(s?.kind!=="query")return;const n=br(t,s.receiver);return n?{exportName:H(e)??e.getName(),handler:n}:void 0},Us=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},xl=e=>{const t=Us(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Us(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Sl=(e,t)=>{const s=[];for(const n of tt(e.handler,"flags"))s.push({callee:xl(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Al=(e,t)=>{const s=[];for(const n of X(e)){const i=El(n);i&&s.push(...Sl(i,t))}return s},yl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Al(i,I(t,n)))}return s},bl=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Y(e.getExpression(),["flags"]),Nl=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Pl=(e,t)=>{if(!bl(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Nl(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},wl=(e,t)=>C(e,t,Pl),Il=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Tl=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Cl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of x(i,d.CallExpression))Il(a)&&s.push({file:o,indexName:Tl(a),line:a.getStartLineNumber()})}return s},Pe=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,ii=e=>{const t=e.getArguments()[0],s=Pe(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=U(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?Pe(n.getInitializer()):void 0},Ol=new Set(["delete","get","head","options","patch","post","put"]),kl=new Set(["handler","stream"]),Rl=new Set(["runAction","runMutation"]),Fl=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),we=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,ri=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(le(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Ws=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:ri(s,"ctx")},qs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:ri(s,"request")},js=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Rl.has(a)&&we(c,t))return a;if(Fl.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&we(c.getExpression(),t))return`db.${a}`}},Hs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&we(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!we(n.getInitializer(),t))){for(const o of i.getElements())if(le(o)==="auth")return!0}}return!1},Ll=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Dl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&we(n.getExpression(),t)},Ml=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],oi=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Ml(s)},_l=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?oi(t,a.getText()):[]}return[]},zl=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=oi(s,t.getText());return n.length>0?n:_l(t,s)},Gs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>Dl(i,t)&&zl(i).some(o=>Ll.test(o)))},Kl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!kl.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Ol.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},$l=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Pe(e.getArguments()[0]),l=c&&Ws(c,!0);if(!c||l===void 0||Gs(c,qs(c,!0)))return;const u=js(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Hs(c,l),sideEffect:u}}const n=Kl(e);if(n===void 0)return;const i=Pe(e.getArguments()[0]),o=i&&Ws(i,!1);if(!i||o===void 0||Gs(i,qs(i,!1)))return;const a=js(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Hs(i,o),sideEffect:a}},Bl=(e,t)=>C(e,t,$l),Vl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Ul=new Set(["append","set"]),ai=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Ys=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Vl.has(w(n.getExpression())??"")&&_e(n,t)),Wl=(e,t)=>{if(Ys(e,t))return!0;const s=Q(e);return s!==void 0&&Ys(s,t)},Mt=(e,t)=>ja(e,t)&&!Wl(e,t),ql=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&r.isNewExpression(t)&&w(t.getExpression())==="Headers"},qe=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},is=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Mt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:ai(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Mt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=qe(n.getExpression());i!==void 0&&is(i,t,s)}},ci=(e,t)=>{const s=qe(e);if(s===void 0)return;const n=U(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=qe(n.getInitializer());i!==void 0&&is(i,"response-init",t)},jl=(e,t)=>{const s=w(e.getExpression());if(s==="Response")ci(e.getArguments()[1],t);else if(s==="Headers"){const n=qe(e.getArguments()[0]);n!==void 0&&is(n,"headers-ctor",t)}},Hl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){ci(e.getArguments()[1],t);return}if(Ul.has(n)&&ql(i)){const o=e.getArguments()[1];o!==void 0&&Mt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:ai(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Gl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))jl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Hl(s,t)},Yl=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Pe(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return Gl(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},Ql=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression))s.push(...Yl(n,t));return s},Xl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ql(i,I(t,n)))}return s},li="identity.ts",Jl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return st(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Zl=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&&st(n.getModuleSpecifierValue())}return!1},ed=e=>{if(r.isIdentifier(e))return Jl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Zl(t)}return!1},td=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!ed(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ue(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Qt(s,"member");a!==void 0&&t.push({exportName:a})}return t},sd=(e,t)=>{const s=E(t,li);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=td(n);if(i.length!==0){if(i.length>1)throw ue(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},nd=new Set(["auth","context.auth"]),id="userId",rd=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},od=(e,t)=>{const s=E(t,li);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(w(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?rd(o):void 0}},Qs=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return nd.has(t.getText())||Y(t,["auth"])?e:void 0},ad=e=>{if(r.isPropertyAccessExpression(e)&&Qs(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Qs(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},Xs=(e,t,s)=>{const n=ad(e);return n===void 0?void 0:{declared:n===id||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},cd=(e,t)=>{const s=od(e,t);return s===void 0?[]:[...ie(e,t,d.PropertyAccessExpression,(n,i)=>Xs(n,i,s)),...ie(e,t,d.ElementAccessExpression,(n,i)=>Xs(n,i,s))]},ld=(e,t)=>{if(w(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=F(s,"key");if(!(!n||!j(n)||de(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},dd=(e,t)=>C(e,t,ld),ud=new Set(["delete","get","getRaw","getWithMetadata","put"]),fd=(e,t,s=[])=>{const n=it(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ud});return Xt(n,s)},gd=new Set(["queue","send"]),Js=new Set(["bcc","cc","to"]),pd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!gd.has(t))return;const s=e.getExpression();return Y(s,["mail"])||Y(s,["email"])?t:void 0},md=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Js.has(A(t))&&j(n)&&!de(n)}if(!r.isPropertyAssignment(t)||!Js.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&j(s)&&!de(s)}):!1,hd=(e,t)=>{const s=pd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!md(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},vd=(e,t)=>C(e,t,hd),Ed=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=We(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=We(l);if(u===void 0)continue;const f=Wn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},xd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;return n?.receiver?Zt(n.receiver).flatMap(i=>Ed(i,H(e)??e.getName(),t)):[]},Sd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...xd(a,o))}return s},Ad=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return K(s)},yd=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=U(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},bd=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Hr(s.getExpression())?s:void 0},Nd=e=>{const t=bd(e),s=t===void 0?void 0:yd(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?H(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Ad(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Pd=e=>e.getVariableDeclarations().flatMap(t=>Nd(t)),wd=(e,t)=>{const s=E(t,jr);if(!_(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Pd(n)},Id=new Set(["delete","get","patch"]),Td=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Cd=new Set(["auth","identity","session","user"]),Od=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),kd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!K(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Rd=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},Fd=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Ld=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Dd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Fd(s.getExpression(),t)&&Ld(s.getThenStatement())),Md=(e,t)=>{for(const s of x(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Id.has(i))continue;const o=n.getExpression(),a=K(o);if(!(a||r.isPropertyAccessExpression(o)&&K(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},_d=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Jt(Ze(s))!==void 0)),zd=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Od.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Kd=e=>{for(const t of x(e,d.Identifier))if(Td.has(t.getText()))return!0;return[...Cd].some(t=>tt(e,t).length>0)?!0:_d(e)||zd(e)},$d=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=ii(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Bn(n.receiver,"use","rls"),a=Kd(i),c=new Set,l=[];for(const u of x(i,d.CallExpression)){const f=kd(u);if(f===void 0)continue;const g=Rd(u);if(g===void 0||c.has(g)||!Dd(i,g))continue;const m=Md(i,g);m!==void 0&&(c.add(g),l.push({exportName:H(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},Bd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...$d(a,o))}return s},di=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?D(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Vd=e=>{const t=T(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!et(s)},Ud=e=>{const t=T(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Wd=e=>{const s=T(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!et(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},je=e=>{const t=D(e);return t===void 0||Cr(t.getSourceFile())},_t=(e,t)=>{const s=T(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&je(o);if(di(Ze(o),t))return!(r.isPropertyAccessExpression(o)&&Kn.has(o.getName()))||r.isExpressionStatement(T(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!je(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},ze={kind:"opaque"},qd={kind:"unreached"},jd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},zt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?D(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=jd(s);return i===void 0||Yt(i)?void 0:i}const n=re(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},ui=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?ze:c===void 0?a.some(l=>l.isRestParameter())?ze:qd:c.isRestParameter()?ze:{kind:"parameter",parameter:c}},Hd=e=>{const t=T(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=zt(s.getExpression());return n===void 0?ze:ui(n,s,t)},Gd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Yd=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,fi=e=>{const t=T(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=Yd(s);if(n!==void 0)return b(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},Qd=4,gi=(e,t,s=0)=>{if(Tr(e))return!0;if(Vd(e)){const i=T(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!Gd.has(c)}if(Ud(e)||Wd(e)||fi(e)||_t(e,t))return!0;const n=Hd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Xd(n.parameter,s+1)},Zs=new WeakMap,Xd=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Zs.get(e.compilerNode);if(n!==void 0)return n;if(t>Qd)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||D(a)?.compilerNode!==e.compilerNode||gi(a,void 0,t));return(o||t===0)&&Zs.set(e.compilerNode,o),o},en=new WeakMap,Jd=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=D(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Zd=(e,t,s)=>{const{context:n,impl:i}=e,o=en.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const m=g.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?gi(g,n):!et(g),f=!Jd(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const m=g.getText();if(m==="arguments")return!1;const v=l.get(m);return v===void 0||c.includes(g)||D(g)?.compilerNode!==v?!0:u(g)});return en.set(i.compilerNode,f),f},tn=new WeakMap,eu=e=>{let t=tn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Gr(s);return n===void 0?[]:[[n.compilerNode,s]]})),tn.set(e.compilerNode,t)),t},tu=e=>{const t=eu(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:H(n)??n.getName()};return a!==void 0&&Zd(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},At="args",Se=e=>{const t=Gt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===At?t.member:void 0}if(!r.isIdentifier(e))return;const s=D(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=re(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&le(i)===At||r.isIdentifier(o)&&o.getText()===At?le(s):void 0},su=new Set(["auth","identity","user"]),Kt=e=>{const t=i=>{const o=Jt(i);return o!==void 0&&o.length>0&&su.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=Q(s);return n!==void 0&&t(n)},pi=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Se(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?Q(n):void 0;if(o!==void 0)for(const a of pi(o,t-1))s.add(a)}return s},Ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Ke(n),...Ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=Se(h(u)??u);return g===void 0?[]:Ke(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Se(h(n)??n),c=Se(h(i)??i);return a!==void 0&&Kt(i)&&o.push(a),c!==void 0&&Kt(n)&&o.push(c),o},nu=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&zr(i.getExpression(),"defineIdentityGuard")},iu=e=>{if(!nu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Se(h(s)??s),o=t.some((a,c)=>c!==n&&Kt(a));return i!==void 0&&o?[i]:[]})},ru=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},ou=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),sn=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},au=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),cu=(e,t)=>{const s=new Set;for(const n of x(e,d.IfStatement))if(n.getEnd()<=t&&sn(n,e)&&ru(n.getThenStatement()))for(const i of Ke(n.getExpression()))s.add(i);for(const n of x(e,d.CallExpression))if(n.getEnd()<=t&&au(n)&&sn(n,e))for(const i of iu(n))s.add(i);return s},lu=(e,t)=>{const s=pi(t);if(s.size===0)return!1;const n=e.getFirstAncestor(ou);if(n===void 0)return!1;const i=cu(n,e.getStart());return[...s].every(o=>i.has(o))},du=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),uu=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),$t=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),mi=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),fu=e=>{const t=T(e),s=t.getParent();if(r.isVariableDeclaration(s))return b(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},gu=e=>{const t=fu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||re(t)?[t]:void 0:mi(t)},Ae=e=>e.isUnion()?e.getUnionTypes().every(t=>Ae(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Ae(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),He=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},$e=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},pu=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&uu.get(s.getText())?.has(t.getName())===!0&&je(s)},mu=e=>{const t=Ct(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=T(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&He(n,$n)?n:void 0},hu=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=T(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:He(n,du,t)?n:void 0},vu=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Eu=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&b(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},nn=e=>{const t=T(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&pu(s);return hu(s,t)??vu(s,t)??Eu(s,t)??(n?s:mu(t))},xu=5e4,hi=()=>({inProgress:new Set,verdicts:new Map});class Su{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>xu&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Au=8,yu=8;class bu{budget;scope;taint;verdicts=hi();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Ae(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?mi(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Au?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(T(l),!0,a,0))&&(t===n||!Ae(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=nn(o);m!==void 0;m=nn(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=T(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Ae(o.getType());if(et(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=gu(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=T(t).getParent();if(n>=yu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===T(t)?this.valueCompromises(i,!1,s,n+1):!He(i,$t);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||re(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=T(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>$e(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=He(t,$t)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=zt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!_t(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(_t(s,this.scope.context))return!1;const i=zt(t.getExpression()),o=i===void 0?void 0:ui(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||fi(t)||b(Ct(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Ct(t);return b(s,this.scope.impl)?void 0:s}}const Nu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Pu=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=D(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},wu=new Set(["all","allSettled","any","race"]),rn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,yt=8;class Iu{budget=new Su;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=hi();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new bu(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,yt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>Or(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=D(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=T(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!$t.has(g.getName()))return!0;const m=a.getArguments().filter(v=>v!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(v=>this.isTaintedValue(v,!1))}const c=r.isVariableDeclaration(a)&&re(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const m=T(g),v=m.getParent();return!r.isCallExpression(v)||v.getExpression()!==m||this.isCallSiteTainted(v,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&je(i)&&wu.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:$e(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=D(t),i=rn(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&Kn.has(i)?!1:i!==void 0&&$n.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>$e(a)!==void 0)&&(i===void 0||!Nu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Ze(i),c=r.isIdentifier(a)?rn(D(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=$e(i);if(o===void 0)return!Pu(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Nr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(di(i,this.scope.context))return!0;const o=r.isIdentifier(i)?D(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=re(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=Yt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,yt))return!1;if(this.variableDepth>=yt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const on=new WeakMap,Tu=e=>{const t=on.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Iu(e);return on.set(e.impl.compilerNode,s),s},Cu=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Ou=new Set(["insert","insertManyUnsafe","patch","replace"]),ku=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Ou.has(t)&&Lr(e.getExpression())?t:void 0},Ru=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},Fu=(e,t)=>{const s=Gt(e);return s?.member===t?h(s.object):void 0},an=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,vi=(e,t,s,n=1)=>{const i=Fu(e,s);if(i!==void 0)return an(i,t);const o=r.isIdentifier(e)?D(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&le(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||re(l)&&an(h(l.getInitializer()),t))}const a=re(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&vi(a,t,s,n-1)},Bt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Bt(t.getWhenTrue()),...Bt(t.getWhenFalse())]:[t]},Lu=(e,t,s)=>{const n=[],i=s===void 0?void 0:Tu(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!Cu.has(a))continue;const l=Bt(c).filter(f=>i===void 0?j(f)&&!Dr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&vi(c,s.parameter,a),g=l.every(m=>lu(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Du=(e,t,s)=>{const n=ku(e.getExpression()),i=n==="patch"||n==="replace"?2:1,o=n===void 0?void 0:e.getArguments()[i];if(n===void 0||o===void 0)return[];const a=Ru(o,n);if(a.length===0)return[];const c=S(e),l=tu(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>Lu(f,u,l))},Mu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=C(e,t,(c,l)=>Du(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Xt(o,s).map(c=>kr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},_u=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),zu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Ku=e=>{const t=U(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?zu(t.getInitializer()):void 0},$u=(e,t)=>{const s=w(e.getExpression());if(s===void 0||!_u.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Ku(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Bu=(e,t)=>C(e,t,$u),Vu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Uu=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Wu=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=U(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Ei=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},xi=(e,t)=>e===t||e.startsWith(`${t}.`),Si=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},cn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},Ai=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>cn(s));return r.isIdentifier(e)&&cn(e)&&t.push(e),t},qu=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},ju=e=>{const t=Ei(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Hu=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:ju(e),i=new Set,o=a=>Si(a).some(c=>n.some(l=>xi(c.getText(),l)))?!0:Ai(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of qu(a))i.add(l)}return{names:i,prefixes:n}},Gu=(e,t)=>Si(e).some(s=>t.prefixes.some(n=>xi(s.getText(),n)))?!0:Ai(e).some(s=>t.names.has(s.getText())),Yu=e=>{const t=Pr(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Qu=(e,t,s)=>{const n=Ei(e,0);if(n===void 0)return[];const i=Hu(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!Mn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Gu(u,i))continue;const f=Yu(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:S(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Xu=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=Uu(n),o=i===void 0?void 0:Vu.get(i);if(o===void 0)continue;const a=Wu(n,o);a!==void 0&&s.push(...Qu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Ju=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xu(i,I(t,n)))}return s},ln={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},dn=new Set(["account","credential","member","passkey","session","user"]),Zu=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ef=e=>{const s=Zu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return dn.has(s)||dn.has(n)},tf=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},sf=(e,t)=>{const{objects:s,opaque:n}=ss(e,t);return fc(s).some(i=>tf(i))?!0:n?void 0:!1},nf=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!U(t,"captcha"),usesRateLimit:!!U(t,"rateLimit")}},rf=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Be={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},of=e=>{const t=rf(e),s=t?w(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=nf(t);return{...Be,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in ln?{...Be,[ln[s]]:!0}:Be},af=e=>{const t={...Be};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=of(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},cf=new Set(["insert","insertMany","insertManyUnsafe","replace"]),lf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!cf.has(t.getName()))return!1;const s=t.getExpression();if(!K(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:ef(i.getLiteralText())},df=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),un=new Set(["queues","scheduler","topics","workflows"]),uf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!df.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&un.has(s.getName())&&Mr(s.getExpression()))return!0;s=s.getExpression()}const n=Jt(s);return n?.length===1&&un.has(n[0]??"")},ff=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return K(s)},yi=new Set(["generateObject","generateText","streamObject","streamText"]),gf=e=>{const t=w(e.getExpression());return t!==void 0&&yi.has(t)},pf=e=>{const t=w(e.getExpression());if(t===void 0||!yi.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!U(s,"maxOutputTokens")},mf=new Set(["log","span","trace"]),hf=new Set(["ai"]),vf=new Set(["email","mail"]),Ef=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),bt=(e,t)=>[...t].some(s=>tt(e,s).length>0),bi=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),xf=new Set(["every","filter","flatMap","forEach","map","some"]),Sf=new Set(["all","allSettled","race"]),Ni=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(xf.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Sf.has(n))return t},Af=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(bi.has(t.getKind())){const s=Ni(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},yf=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(bi.has(t.getKind())){if(t=Ni(t),t===void 0)return!1;continue}t=t.getParent()}return!1},bf=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const v=m.getExpression();return r.isIdentifier(v)&&v.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Nf=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Pf=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},wf=e=>{let t=!1,s=!0;for(const n of[...Ef].flatMap(i=>tt(e,i))){const i=Pf(n);i&&(t=!0,!Af(i)&&!Nf(i)&&!bf(i)&&!yf(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},If=e=>x(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),fn="lunora-advisor-exempt",Tf=/^[\s*/]+/u,Cf=/[\w-]/u,Of=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
22
22
  `);for(const n of s.split(`
23
- `)){const i=n.replace(Tf,"");if(!i.startsWith(ln))continue;const o=i.slice(ln.length);if(Cf.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},kf=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=U(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Rf=(e,t)=>{const s=kf(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},Ff=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of x(e,d.CallExpression))if(lf(l)&&(o=!0),uf(l)&&(t=!0),ff(l)&&(i=!0),gf(l)&&(s=!0),pf(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=wf(e);return{callsMail:yt(e,vf),emitsEvent:yt(e,mf),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||yt(e,hf),throwsBareError:If(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},Lf=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=te(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?af(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Rf(e,s);return{...o?Ff(o):{},...Of(e),...i,analyzableBody:o!==void 0,exportName:H(e)??e.getName(),file:t,hasEmailArg:sf(s,n.receiver),kind:n.kind,visibility:n.visibility}},Df=(e,t)=>{const s=[];for(const n of X(e)){const i=Lf(n,t);i&&s.push(i)}return s},Mf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Df(i,I(t,n)))}return s},_f=new Set(["dbRateLimit","rateLimit"]),zf=e=>r.isArrowFunction(e)?e.getBody():e,Kf=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Ni=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Pi=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},$f=(e,t)=>j(e)||t!==void 0&&Pi(e,t).some(s=>Ni(s)),Bf=(e,t)=>t===void 0?de(e):Pi(e,t).some(s=>!Ni(s)),Vf=(e,t)=>{const s=w(e.getExpression());if(s===void 0||!_f.has(s))return;const n=F(Ln(e.getArguments()[2]),"key");if(!n)return;const i=zf(n),o=Kf(n);if(!(!$f(i,o)||Bf(i,o)))return{callee:s,scope:S(e),file:t,limitName:Fn(e),line:e.getStartLineNumber()}},Uf=(e,t)=>C(e,t,Vf),Wf=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),qf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Wf.has(t.getName()))return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&$(s.getExpression()))return s.getName()},jf=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&$(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Hf=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},wi=(e,t=!1)=>{const s=Hf(e);if(r.isIdentifier(s)){if(t)return;const n=Q(s);return n===void 0?void 0:wi(n,!0)}if(r.isCallExpression(s))return qf(s)??jf(s)},Gf=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of x(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},Yf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query")return[];const i=ni(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Kr(n.receiver,"output"),a=n.receiver!==void 0&&$n(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Gf(i)){const f=wi(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:H(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Qf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...Yf(a,o))}return s},Xf=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},Jf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=Vn(o);if(a===void 0)continue;const c=Xf(F(a.options,"with"));c.length!==0&&i.push({exportName:H(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Zf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...Jf(a,o))}return s},q=(e,t)=>`${e}:${t}`,dn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},eg=(e,t)=>[...ie(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?dn(s,n,s.getName(),s.isExported()):void 0),...ie(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?dn(i,n,s.getName(),i.isExported()):void 0})],tg=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(q(c,a))},sg=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,ng=(e,t)=>{const s=new Map(e.map(n=>[q(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(q(i.file,i.name))?.set(sg(n),{fields:n.fields,method:n.method,table:n.table})}return s},ig=(e,t,s)=>x(e.node,d.CallExpression).map(n=>tg(n,t,s)).filter(n=>n!==void 0),rg=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(q(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(q(o.file,o.name))?.push(a)}},og=(e,t,s)=>{const n=new Map(e.map(a=>[q(a.file,a.name),a])),i=new Map(e.map(a=>[`${Xt(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[q(a.file,a.name),ig(a,n,t)]));return rg(s,n,i,o),o},ag=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},cg=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(q(i.file,i.name))??[])ag(t.get(q(i.file,i.name)),t.get(q(o.file,o.name)))&&(n=!0)}},lg=(e,t,s,n)=>{const i=eg(e,t),o=ng(i,s);return cg(i,o,og(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(q(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},He=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=He(e.getLeft()),s=He(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},dg=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&He(t)!==void 0},ug=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},fg=(e,t,s)=>io(e)?!wr(s)&&ro(ug(t)):!0,gg=(e,t)=>{const s=[],n=[...x(e,d.BinaryExpression),...x(e,d.StringLiteral),...x(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(dg(o))continue;const a=He(o);if(a===void 0)continue;const c=so(a);if(c===void 0||!fg(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:no(a)}))}return s},pg=(e,t)=>{const s=[],n=new Wt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Qe(i,"utf8"),{overwrite:!0});s.push(...gg(o,I(t,i)))}return s},mg=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=Vn(o);if(a===void 0)continue;const c=F(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&j(c);!l&&!u||i.push({exportName:H(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},hg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...mg(a,o))}return s},vg=new Set(["query","unsafe"]),Eg=e=>!r.isPropertyAccessExpression(e)||!vg.has(e.getName())?!1:Y(e.getExpression(),["sql"]),xg=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Sg=(e,t)=>{if(!Eg(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!xg(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},Ag=(e,t)=>C(e,t,Sg),yg=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],bg=e=>{for(const[t,s]of yg)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Ng=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=bg(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Pg=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),wg=(e,t,s=[])=>{const n=nt(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Pg,requireUnmodifiedReach:!0});return Gt(n,s)},Ig=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Tg=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Cg=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=Tg(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Og=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ig.get(t);return s===void 0?void 0:_n(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},kg=(e,t)=>{const s=Og(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...Cg(e.getArguments()[s.optionsIndex])}},Rg=(e,t)=>C(e,t,kg),Fg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Ii=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Fg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>oe(i)||s(i));if(!(n===void 0||oe(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},ss=(e,t)=>b(e.getFirstAncestor(s=>b(s,t)||oe(s)),t),Lg=(e,t)=>b(e,t)||e.getFirstAncestor(s=>b(s,t))!==void 0,Ti=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return b(e,t)||ss(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Ii(e);return s!==void 0&&!Lg(s,t)}return!1},Ci=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],Dg=e=>Ci(e).some(t=>Ti(t,e)),Mg=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},_g=e=>Ci(e).some(t=>Ti(t,e)||r.isBreakStatement(t)&&b(Ii(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Mg(t)&&ss(t,e)),zg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>ss(t,e)),Kg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),$g=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",bt=(e,t)=>{const s=Kg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||_g(e)||zg(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(oe)!==void 0))return{file:t,kind:$g(e),line:e.getStartLineNumber(),scope:i}},Bg=(e,t)=>[...ie(e,t,d.WhileStatement,bt),...ie(e,t,d.ForStatement,bt),...ie(e,t,d.DoStatement,bt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),Vg=new Set(["when","where"]),Nt=new Set(["definePolicy","defineShape"]),Ug=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Nt.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return Nt.has(i)?i:void 0}const s=t.getText();return Nt.has(s)?s:void 0},Wg=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,Oi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Wg(e))return"empty-object";if(r.isParenthesizedExpression(e))return Oi(e.getExpression())}},ns=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),qg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ns(t)===e),ki=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>ns(t)===e),jg=e=>{const t=qg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||ki(e).length>0},Hg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>ns(t)===e),$t=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",Gg=(e,t)=>$t(e)||$t(t),Yg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),un=e=>!$t(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Qg=(e,t,s)=>{const n=Yg.get(e);if(n!==void 0)return Gg(t,s)?n==="positive"?"negative":"positive":un(t)||un(s)?void 0:n},ye=e=>{if(r.isParenthesizedExpression(e))return ye(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Qg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=ye(e.getLeft()),i=ye(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},fn=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},Xg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Jg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Zg=e=>{const t=[];for(const s of ki(e)){const n=ye(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Hg(e)){const n=ye(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?fn(s.getThenStatement()):fn(s.getElseStatement())??Xg(s);i!==void 0&&t.push(Jg(i))}return t},ep=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},tp=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!Vg.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&jg(a))for(const c of Zg(a)){const l=Oi(c);l!==void 0&&i.push({exportName:ep(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},sp=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=Ug(n);i!==void 0&&s.push(...tp(n,i,t))}return s},np=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sp(i,I(t,n)))}return s},ip=new Set(["query","upsert","upsertMany","upsertNow"]),me=new Set,rp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(ip.has(t))return Y(e.getExpression(),["vectors"])?t:void 0},is=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},Ri=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Fi=e=>Ri(e)?.getDeclarations()[0],op=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Li=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},gn=(e,t,s)=>{const n=Ri(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Li(Fi(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return rs(o,t,s-1)}return j(e)},rs=(e,t,s)=>{const n=is(e);return de(n)?!1:r.isIdentifier(n)?gn(n,t,s):j(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>op(i)&&gn(i,t,s))},Di=e=>{const t=Li(Fi(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ee=(e,t)=>{const s=is(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ee(s.getWhenTrue(),t),...ee(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ee(s.getLeft(),t),...ee(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Di(s);return n===void 0?[]:ee(n,!1)}return[]},ap=(e,t)=>{const s=ee(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>Ge(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},cp=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",lp=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),Ge=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=ap(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else cp(n)&&(s=[lp(n)]);return s},dp=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},up=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return me;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return me;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Bt=(e,t=!0,s=me)=>{const n=is(e);if(r.isIdentifier(n)){const o=t?Di(n):void 0;return o===void 0?[{node:n,parameters:s}]:Bt(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Bt(o.getExpression(),t,s):ee(o,!0).flatMap(a=>Ge(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=rs(i.getExpression(),me,1)?up(o):me;return dp(o).flatMap(c=>ee(c,!0).flatMap(l=>Ge(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},fp=(e,t)=>{const s=rp(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Bt(n):ee(n,!0).flatMap(o=>Ge(o,!0).map(a=>({node:a,parameters:me})))).some(({node:o,parameters:a})=>rs(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},gp=(e,t)=>C(e,t,fp),pp=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:m,workflows:v}=s;return xr({adminRoutes:$a(e,t),aiRawRuns:Ya(e,t),aiToolSideEffects:oc(e,t),argumentDerivedFetches:lc(e,t),argumentValidators:Ic(e,t),authApiCalls:Ur(e,t),authConfigs:_c(e,t),browserUrlAccesses:Bc(e,t),callEdges:n.callEdges,configCalls:Yc(e,t),containerKeyAccesses:Xc(e,t),containerOverrides:nl(e,t),containers:i,countReads:cl(e,t,f.tables),crons:o,cronTargets:o.flatMap(B=>B.functionPath===void 0?[]:[B.functionPath]),exportSinks:fl(e,t),staleMigrationImports:Ng(e,t),failOpenGuards:vl(e,t),flagReads:yl(e,t),flagSecurityDefaults:wl(e,t),geoIndexUsages:Cl(e,t),httpActionGuards:Bl(e,t),httpHeaderWrites:Xl(e,t),hyperdriveCalls:Wr(e,t),identityClaimReads:cd(e,t),imageDeliveryUrlAccesses:dd(e,t),inserts:n.inserts,kvKeyAccesses:fd(e,t,a),mailRecipientAccesses:vd(e,t),maskProcedures:qr(e,t),maskStrategies:Sd(e,t),mutatorWrites:wd(e,t),nondeterministicCalls:Qr(e,t),normalizeIdAuthorizations:Bd(e,t),notifyCalls:Jr(e,t),notifyConfig:Xr(e,t),mutators:l,ownerFieldWrites:Mu(e,t,a,l),unrestrictedWhereBranches:np(e,t),paymentWebhooks:Bu(e,t),privilegedDispatches:Ju(e,t),procedureProtections:Mf(e,t),queries:n.queries,queues:u,r2sqlCalls:Zr(e,t),ratelimitKeySelectors:Uf(e,t),rawRowReturns:Qf(e,t),relationLoads:Zf(e,t),rlsProcedures:eo(e,t),schema:f,secretLiterals:pg(e,t),modules:c,shapes:g,softDeleteReads:hg(e,t),sqlInterpolations:Ag(e,t),storageKeyAccesses:wg(e,t,a),storageUploads:Rg(e,t),tableWrites:n.tableWrites,rowEffects:lg(e,t,n.tableWrites,n.callEdges),unboundedLoops:Bg(e,t),vectorNamespaceAccesses:gp(e,t),workflowCalls:n.workflowCalls,workflows:v,wranglerVariables:m})},mp=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),hp=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>mp(i))]},vp=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Ep=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",pn={error:"ERROR",info:"INFO",warn:"WARN"},mn={ERROR:2,INFO:0,WARN:1},xp=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),Sp=(e,t)=>{const{advisor:s}=Wn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(pn,n)?pn[n]:void 0;return i===void 0?[...t,xp(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>Ep(o)||mn[o.level]>=mn[i])},Ap=(e,t)=>{const{advisor:s}=Wn(e),n=hp(t,s?.accept??[]);return Sp(e,s?.acceptUnreadable===!0?[...n,vp()]:n)},yp={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},bp="crons",Np=lo.replace(/\.ts$/u,""),pe=(e,t)=>`${Xt(e)}:${t}`,Pt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Pp=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${yp[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...Pt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Pt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Pt("workflow",t.workflow,"workflow name")}))],wp=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Ip=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:wp(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Tp=e=>Pp(e).flatMap(t=>Ip(t)),Cp=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:bp,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Op=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),xe=(e,t)=>t===void 0?e:{...e,module:t},kp=e=>{const t=new Map,s=new Map,n=Op(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(pe(c.file,c.exportName),l)};for(const c of e.functions){const l=pe(c.filePath,c.exportName),u=[...to(c.filePath),c.exportName].join(".");o(xe({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Me(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=pe(c.filePath,c.exportName);o(xe({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Me(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(xe({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(xe({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Me(e.modules,c.filePath)),pe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(xe({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Me(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},pe(Np,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},Rp=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Fp=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(pe(e.file,e.exportName))??{reason:Rp(e.exportName)},Lp=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Fp(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},wt=e=>`${e.from}|${e.kind}|${e.to}`,Dp=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Mp=e=>{const{nodes:t,sites:s}=kp(e),n=new Map,i=new Map;for(const o of[...Cp(e),...Tp(e)]){const a=Lp(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(wt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Dp(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>wt(o).localeCompare(wt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},_p=e=>`${qn}export const architecture = ${fo(e,"Record<string, unknown>")};
24
- `,hn=(e,t="api")=>{const s=new Map;for(const n of e){const i=Xt(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new z("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},zp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>jn(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>Hn(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:xo)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},Kp=(e,t,s={})=>{if(t===void 0)return;const n=zp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
23
+ `)){const i=n.replace(Tf,"");if(!i.startsWith(fn))continue;const o=i.slice(fn.length);if(Cf.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},kf=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=U(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Rf=(e,t)=>{const s=kf(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},Ff=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of x(e,d.CallExpression))if(lf(l)&&(o=!0),uf(l)&&(t=!0),ff(l)&&(i=!0),gf(l)&&(s=!0),pf(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=wf(e);return{callsMail:bt(e,vf),emitsEvent:bt(e,mf),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||bt(e,hf),throwsBareError:If(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},Lf=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=te(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?af(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Rf(e,s);return{...o?Ff(o):{},...Of(e),...i,analyzableBody:o!==void 0,exportName:H(e)??e.getName(),file:t,hasEmailArg:sf(s,n.receiver),kind:n.kind,visibility:n.visibility}},Df=(e,t)=>{const s=[];for(const n of X(e)){const i=Lf(n,t);i&&s.push(i)}return s},Mf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Df(i,I(t,n)))}return s},_f=new Set(["dbRateLimit","rateLimit"]),zf=e=>r.isArrowFunction(e)?e.getBody():e,Kf=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Pi=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},wi=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},$f=(e,t)=>j(e)||t!==void 0&&wi(e,t).some(s=>Pi(s)),Bf=(e,t)=>t===void 0?de(e):wi(e,t).some(s=>!Pi(s)),Vf=(e,t)=>{const s=w(e.getExpression());if(s===void 0||!_f.has(s))return;const n=F(Dn(e.getArguments()[2]),"key");if(!n)return;const i=zf(n),o=Kf(n);if(!(!$f(i,o)||Bf(i,o)))return{callee:s,scope:S(e),file:t,limitName:Ln(e),line:e.getStartLineNumber()}},Uf=(e,t)=>C(e,t,Vf),Wf=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),qf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Wf.has(t.getName()))return;const s=t.getExpression();if(K(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&K(s.getExpression()))return s.getName()},jf=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&K(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Hf=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},Ii=(e,t=!1)=>{const s=Hf(e);if(r.isIdentifier(s)){if(t)return;const n=Q(s);return n===void 0?void 0:Ii(n,!0)}if(r.isCallExpression(s))return qf(s)??jf(s)},Gf=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of x(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},Yf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query")return[];const i=ii(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Kr(n.receiver,"output"),a=n.receiver!==void 0&&Bn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Gf(i)){const f=Ii(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:H(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Qf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...Yf(a,o))}return s},Xf=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},Jf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=Un(o);if(a===void 0)continue;const c=Xf(F(a.options,"with"));c.length!==0&&i.push({exportName:H(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Zf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...Jf(a,o))}return s},q=(e,t)=>`${e}:${t}`,gn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},eg=(e,t)=>[...ie(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?gn(s,n,s.getName(),s.isExported()):void 0),...ie(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?gn(i,n,s.getName(),i.isExported()):void 0})],tg=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(q(c,a))},sg=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,ng=(e,t)=>{const s=new Map(e.map(n=>[q(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(q(i.file,i.name))?.set(sg(n),{fields:n.fields,method:n.method,table:n.table})}return s},ig=(e,t,s)=>x(e.node,d.CallExpression).map(n=>tg(n,t,s)).filter(n=>n!==void 0),rg=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(q(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(q(o.file,o.name))?.push(a)}},og=(e,t,s)=>{const n=new Map(e.map(a=>[q(a.file,a.name),a])),i=new Map(e.map(a=>[`${es(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[q(a.file,a.name),ig(a,n,t)]));return rg(s,n,i,o),o},ag=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},cg=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(q(i.file,i.name))??[])ag(t.get(q(i.file,i.name)),t.get(q(o.file,o.name)))&&(n=!0)}},lg=(e,t,s,n)=>{const i=eg(e,t),o=ng(i,s);return cg(i,o,og(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(q(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ge=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ge(e.getLeft()),s=Ge(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},dg=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Ge(t)!==void 0},ug=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},fg=(e,t,s)=>io(e)?!wr(s)&&ro(ug(t)):!0,gg=(e,t)=>{const s=[],n=[...x(e,d.BinaryExpression),...x(e,d.StringLiteral),...x(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(dg(o))continue;const a=Ge(o);if(a===void 0)continue;const c=so(a);if(c===void 0||!fg(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:no(a)}))}return s},pg=(e,t)=>{const s=[],n=new jt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Xe(i,"utf8"),{overwrite:!0});s.push(...gg(o,I(t,i)))}return s},mg=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=Un(o);if(a===void 0)continue;const c=F(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&j(c);!l&&!u||i.push({exportName:H(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},hg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of X(i))s.push(...mg(a,o))}return s},vg=new Set(["query","unsafe"]),Eg=e=>!r.isPropertyAccessExpression(e)||!vg.has(e.getName())?!1:Y(e.getExpression(),["sql"]),xg=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Sg=(e,t)=>{if(!Eg(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!xg(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},Ag=(e,t)=>C(e,t,Sg),yg=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],bg=e=>{for(const[t,s]of yg)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Ng=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=bg(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Pg=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),wg=(e,t,s=[])=>{const n=it(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Pg,requireUnmodifiedReach:!0});return Xt(n,s)},Ig=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Tg=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Cg=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=Tg(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Og=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ig.get(t);return s===void 0?void 0:zn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},kg=(e,t)=>{const s=Og(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...Cg(e.getArguments()[s.optionsIndex])}},Rg=(e,t)=>C(e,t,kg),Fg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Ti=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Fg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>oe(i)||s(i));if(!(n===void 0||oe(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},rs=(e,t)=>b(e.getFirstAncestor(s=>b(s,t)||oe(s)),t),Lg=(e,t)=>b(e,t)||e.getFirstAncestor(s=>b(s,t))!==void 0,Ci=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return b(e,t)||rs(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Ti(e);return s!==void 0&&!Lg(s,t)}return!1},Oi=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],Dg=e=>Oi(e).some(t=>Ci(t,e)),Mg=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},_g=e=>Oi(e).some(t=>Ci(t,e)||r.isBreakStatement(t)&&b(Ti(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Mg(t)&&rs(t,e)),zg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>rs(t,e)),Kg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),$g=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Nt=(e,t)=>{const s=Kg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||_g(e)||zg(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(oe)!==void 0))return{file:t,kind:$g(e),line:e.getStartLineNumber(),scope:i}},Bg=(e,t)=>[...ie(e,t,d.WhileStatement,Nt),...ie(e,t,d.ForStatement,Nt),...ie(e,t,d.DoStatement,Nt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),Vg=new Set(["when","where"]),Pt=new Set(["definePolicy","defineShape"]),Ug=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Pt.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return Pt.has(i)?i:void 0}const s=t.getText();return Pt.has(s)?s:void 0},Wg=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,ki=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Wg(e))return"empty-object";if(r.isParenthesizedExpression(e))return ki(e.getExpression())}},os=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),qg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>os(t)===e),Ri=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>os(t)===e),jg=e=>{const t=qg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Ri(e).length>0},Hg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>os(t)===e),Vt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",Gg=(e,t)=>Vt(e)||Vt(t),Yg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),pn=e=>!Vt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Qg=(e,t,s)=>{const n=Yg.get(e);if(n!==void 0)return Gg(t,s)?n==="positive"?"negative":"positive":pn(t)||pn(s)?void 0:n},ye=e=>{if(r.isParenthesizedExpression(e))return ye(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Qg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=ye(e.getLeft()),i=ye(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},mn=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},Xg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Jg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Zg=e=>{const t=[];for(const s of Ri(e)){const n=ye(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Hg(e)){const n=ye(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?mn(s.getThenStatement()):mn(s.getElseStatement())??Xg(s);i!==void 0&&t.push(Jg(i))}return t},ep=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},tp=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!Vg.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&jg(a))for(const c of Zg(a)){const l=ki(c);l!==void 0&&i.push({exportName:ep(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},sp=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=Ug(n);i!==void 0&&s.push(...tp(n,i,t))}return s},np=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sp(i,I(t,n)))}return s},ip=new Set(["query","upsert","upsertMany","upsertNow"]),me=new Set,rp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(ip.has(t))return Y(e.getExpression(),["vectors"])?t:void 0},as=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},Fi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Li=e=>Fi(e)?.getDeclarations()[0],op=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Di=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},hn=(e,t,s)=>{const n=Fi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Di(Li(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return cs(o,t,s-1)}return j(e)},cs=(e,t,s)=>{const n=as(e);return de(n)?!1:r.isIdentifier(n)?hn(n,t,s):j(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>op(i)&&hn(i,t,s))},Mi=e=>{const t=Di(Li(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ee=(e,t)=>{const s=as(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ee(s.getWhenTrue(),t),...ee(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ee(s.getLeft(),t),...ee(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Mi(s);return n===void 0?[]:ee(n,!1)}return[]},ap=(e,t)=>{const s=ee(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>Ye(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},cp=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",lp=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),Ye=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=ap(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else cp(n)&&(s=[lp(n)]);return s},dp=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},up=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return me;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return me;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Ut=(e,t=!0,s=me)=>{const n=as(e);if(r.isIdentifier(n)){const o=t?Mi(n):void 0;return o===void 0?[{node:n,parameters:s}]:Ut(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Ut(o.getExpression(),t,s):ee(o,!0).flatMap(a=>Ye(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=cs(i.getExpression(),me,1)?up(o):me;return dp(o).flatMap(c=>ee(c,!0).flatMap(l=>Ye(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},fp=(e,t)=>{const s=rp(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Ut(n):ee(n,!0).flatMap(o=>Ye(o,!0).map(a=>({node:a,parameters:me})))).some(({node:o,parameters:a})=>cs(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},gp=(e,t)=>C(e,t,fp),pp=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:m,workflows:v}=s;return Sr({adminRoutes:$a(e,t),aiRawRuns:Ya(e,t),aiToolSideEffects:oc(e,t),argumentDerivedFetches:lc(e,t),argumentValidators:Ic(e,t),authApiCalls:Ur(e,t),authConfigs:_c(e,t),browserUrlAccesses:Bc(e,t),callEdges:n.callEdges,configCalls:Yc(e,t),containerKeyAccesses:Xc(e,t),containerOverrides:nl(e,t),containers:i,countReads:cl(e,t,f.tables),crons:o,cronTargets:o.flatMap(B=>B.functionPath===void 0?[]:[B.functionPath]),exportSinks:fl(e,t),staleMigrationImports:Ng(e,t),failOpenGuards:vl(e,t),flagReads:yl(e,t),flagSecurityDefaults:wl(e,t),geoIndexUsages:Cl(e,t),httpActionGuards:Bl(e,t),httpHeaderWrites:Xl(e,t),hyperdriveCalls:Wr(e,t),identityClaimReads:cd(e,t),imageDeliveryUrlAccesses:dd(e,t),inserts:n.inserts,kvKeyAccesses:fd(e,t,a),mailRecipientAccesses:vd(e,t),maskProcedures:qr(e,t),maskStrategies:Sd(e,t),mutatorWrites:wd(e,t),nondeterministicCalls:Qr(e,t),normalizeIdAuthorizations:Bd(e,t),notifyCalls:Jr(e,t),notifyConfig:Xr(e,t),mutators:l,ownerFieldWrites:Mu(e,t,a,l),unrestrictedWhereBranches:np(e,t),paymentWebhooks:Bu(e,t),privilegedDispatches:Ju(e,t),procedureProtections:Mf(e,t),queries:n.queries,queues:u,r2sqlCalls:Zr(e,t),ratelimitKeySelectors:Uf(e,t),rawRowReturns:Qf(e,t),relationLoads:Zf(e,t),rlsProcedures:eo(e,t),schema:f,secretLiterals:pg(e,t),modules:c,shapes:g,softDeleteReads:hg(e,t),sqlInterpolations:Ag(e,t),storageKeyAccesses:wg(e,t,a),storageUploads:Rg(e,t),tableWrites:n.tableWrites,rowEffects:lg(e,t,n.tableWrites,n.callEdges),unboundedLoops:Bg(e,t),vectorNamespaceAccesses:gp(e,t),workflowCalls:n.workflowCalls,workflows:v,wranglerVariables:m})},mp=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),hp=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>mp(i))]},vp=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Ep=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",vn={error:"ERROR",info:"INFO",warn:"WARN"},En={ERROR:2,INFO:0,WARN:1},xp=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),Sp=(e,t)=>{const{advisor:s}=qn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(vn,n)?vn[n]:void 0;return i===void 0?[...t,xp(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>Ep(o)||En[o.level]>=En[i])},Ap=(e,t)=>{const{advisor:s}=qn(e),n=hp(t,s?.accept??[]);return Sp(e,s?.acceptUnreadable===!0?[...n,vp()]:n)},yp={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},bp="crons",Np=lo.replace(/\.ts$/u,""),pe=(e,t)=>`${es(e)}:${t}`,wt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Pp=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${yp[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...wt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...wt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...wt("workflow",t.workflow,"workflow name")}))],wp=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Ip=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:wp(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Tp=e=>Pp(e).flatMap(t=>Ip(t)),Cp=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:bp,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Op=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),xe=(e,t)=>t===void 0?e:{...e,module:t},kp=e=>{const t=new Map,s=new Map,n=Op(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(pe(c.file,c.exportName),l)};for(const c of e.functions){const l=pe(c.filePath,c.exportName),u=[...to(c.filePath),c.exportName].join(".");o(xe({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Me(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=pe(c.filePath,c.exportName);o(xe({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Me(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(xe({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(xe({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Me(e.modules,c.filePath)),pe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(xe({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Me(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},pe(Np,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},Rp=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Fp=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(pe(e.file,e.exportName))??{reason:Rp(e.exportName)},Lp=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Fp(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},It=e=>`${e.from}|${e.kind}|${e.to}`,Dp=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Mp=e=>{const{nodes:t,sites:s}=kp(e),n=new Map,i=new Map;for(const o of[...Cp(e),...Tp(e)]){const a=Lp(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(It(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Dp(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>It(o).localeCompare(It(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},_p=e=>`${jn}export const architecture = ${fo(e,"Record<string, unknown>")};
24
+ `,xn=(e,t="api")=>{const s=new Map;for(const n of e){const i=es(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new z("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},zp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Hn(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>Gn(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:xo)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},Kp=(e,t,s={})=>{if(t===void 0)return;const n=zp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
25
25
  `);throw new z("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.`)},$p="env.ts",Bp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return tt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Vp=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&&tt(n.getModuleSpecifierValue())}return!1},Up=e=>{if(r.isIdentifier(e))return Bp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&Vp(t)}return!1},Wp=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Up(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ue(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=Ht(s,"member");a!==void 0&&t.push({exportName:a})}return t},qp=(e,t)=>{const s=E(t,$p);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Wp(n);if(i.length!==0){if(i.length>1)throw ue(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},jp={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},Hp=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Gp=(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())},Yp=(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"}),Qp=new Set(["durable"]),Xp=new Set(["rollback"]),Mi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Jp="defineApp",be="app",vn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===be&&s.getInitializer()?.getText()===t)||t===be&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===be),Zp=e=>{if(e===void 0||!To.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===be;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===be;if(r.isVariableDeclaration(t))return vn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&vn(e.getSourceFile(),s)},em="AppBuilder",_i=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},tm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===em&&s.getDeclarations().some(n=>_i(n))},sm=e=>e.getText()===Jp&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||_i(t)),zi=(e,t,s=new Set)=>{const n=Je(t);if(n===void 0||!r.isIdentifier(n))return!1;if(sm(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 Zp(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 zi(e,a.getInitializer(),s)}}return!1},Ki=(e,t)=>{const s=qt(t.getExpression());return s?.member==="deliveryAuthorization"&&(zi(e,s.object)||tm(s.object))},nm=new Map([["defineContainer",{keys:Hp,signal:"containerEgressPolicy"}],["defineStep",{keys:Xp,signal:"workflowRollback"}],["stream",{keys:Qp,signal:"durableStreams"}]]),im=(e,t)=>{const s=nm.get(Mi(t));if(s!==void 0)return t.getArguments().some(n=>Yp(Gp(e,n),s.keys))?s.signal:void 0},rm=(e,t)=>jp[Mi(t)]??(Ki(e,t)?"deliveryAuthorization":void 0),om=(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=No(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=x(o,d.CallExpression);for(const c of a){const l=im(o,c)??rm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>Bn(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 Wt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Qe(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Ki(i,o))}return n},am=(e,t)=>{const s=wo();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Po(i,s))return!0}return!1},cm="createWorker",lm="extend",En=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,xn=e=>{const t=[],s=En(F(e,"backupCron"));s!==void 0&&t.push(s);const n=F(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=En(i.getNameNode());o!==void 0&&t.push(o)}return t},dm=e=>{const t=w(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===cm)return r.isObjectLiteralExpression(s)?xn(s):[];if(t!==lm||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Rn(s.getBody());return n===void 0?[]:xn(n)},um=(e,t)=>{const s=[];for(const{filePath:n}of Xe(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression))s.push(...dm(o))}return[...new Set(s)]},$i=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:$i(e.inner)},fm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=$i(n);return i!==void 0&&t.has(i)}))},gm=(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 z("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 z("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})}},pm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=sd(s,t),a=qp(s,t),c=uo(s,t),{queues:l,topics:u}=Oo(s,t),f=Ro(n),g=Ao(s,t);gm(c,g);const m=yo(s,t),v=Fo(s,t),B=bo(s,t,c,g),fe=um(s,t),N=om(s,t,Co(n)),V=ko(s,t),G=am(s,t),L=Io(s,t);L.browser=L.browser||V.usesSandboxBrowser;const R=Ct(n,e.target),O=Lo(L,R,{agents:g.length>0,commitOrderedTables:i.tables.some(M=>M.commitOrdered===!0),cronTriggers:B.length>0,crossShardFanout:i.tables.some(M=>Bo(M)),containerEgressPolicy:N.containerEgressPolicy,containerRuntimeScheduling:m.some(M=>M.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(M=>M.sandbox===!0),deliveryAuthorization:N.deliveryAuthorization,durableStreams:N.durableStreams,globalTables:i.tables.some(M=>M.shardMode==="global"),liveContext:N.liveContext,liveStreams:N.liveStreams,typedWebSockets:N.typedWebSockets,queues:l.length>0,relationGraph:fm(i),secretValues:G,secrets:N.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:N.workflowRollback,workflowSchedules:c.some(M=>M.schedules!==void 0)}),W=O.usage,J=So(W),se=O.signals.vectorStore!==!1,ne=O.signals.services===!1?[]:f,ae=Gn(n),K=ae??new Set,P=K.has("lunorash");Kp(i,ae,{hasVectors:se,scheduler:W.scheduler||B.length>0,storage:W.storage||v.rules.length>0||Object.keys(Yn(i)).length>0,usage:W});const k=_(E(t,"flags.ts")),Ce=_(E(t,"notify.ts"));return{agents:g,capabilities:J,containers:m,crons:B,dataModelContent:qo(i),declaredDependencies:ae,dependencies:K,entryCronTriggers:fe,env:a,featureUsage:W,hasFlags:k,hasNotify:Ce,identity:o,platformGate:{...O,diagnostics:[...Do(n,e.target),...O.diagnostics,...Mo(R,i.vectorIndexes),...N.liveStreams&&N.deliveryAuthorization?[_o(R)]:[],...N.socketRoutes&&N.deliveryAuthorization?[zo(R)]:[]]},queues:l,serverContent:Uo({agents:g,capabilities:J,containers:m,env:a,hasVectors:se,hasFlags:k,hasNotify:Ce,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:v.rules.map(M=>M.bucket),topics:u,useUmbrella:P,workflows:c}),services:ne,storageRulesMetadata:v,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:P,workflows:c}},Bi=(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},mm=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},hm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),vm=/^[\w$]+:[\w$]+$/u,Em=(e,t)=>{const s=Mn(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},Sn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},xm=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Sn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Ar.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Sn(s):void 0}}},Sm=(e,t,s)=>({schedule:{argKeys:xm(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Am=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Dn.has(s))return Em(s,n);if((s==="runAfter"||s==="runAt")&&mm(t)){const l=Mn(i)??(r.isStringLiteral(i)&&vm.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,...Sm(s,n,o)}}const a=hm.get(s),c=a===void 0?void 0:Bi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},ym=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Vi=e=>Sr.isOptionalChain(e.compilerNode),bm=(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:oe(t)?t.getFirstAncestor(oe)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&ym.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Vi(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Dg(s)),Nm=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(oe);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(oe),i))===!0},Pm=(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)),wm=(e,t)=>{if(Vi(e)||t==="schedule"&&Nm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(bm(s,i)){if(!Pm(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},An=(e,t,s)=>{if(s===void 0)return;const n=wm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Im=(e,t)=>[...C(e,t,(s,n)=>An(s,n,Am(s))),...ie(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Bi(s,"services");return An(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Tm=new Set(["boolean","number","object","string"]),Cm=e=>{const t=e.getName();if(!Tm.has(t))return;const s=e.getExpression();return Y(s,["flags"])||Y(s,["flags","details"])?t:void 0},Om=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Cm(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},km=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression)){const a=Om(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))},Rm=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"||jo(o))return;const a=e.getSourceFile().getFilePath();if(Ho(i,e,a)){const c=Go(i,e,a,0,new Set);return c===void 0&&Yo(o),c}return o},Fm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=$r(t.getNameNode());return s===void 0||s==="namespace"}),Lm=(e,t)=>{for(const{filePath:s}of Xe(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of x(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Fm(a)))return i}}},Dm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Mm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ue(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 (${Dm}). 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})},_m="room:",zm="__lunora_socket__:",Km=/^[A-Za-z]\w*$/u,yn=e=>Km.test(e),$m=e=>`${e}:`.startsWith(_m)||`${e}:`.startsWith(zm),Ui=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Wi=e=>Ui(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),bn=e=>A(e),os=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),ce=(e,t)=>{const s=ue(e,`defineLiveStream ${t}`);return new z("LIVE_STREAM_NOT_LITERAL",s.message)},qi=(e,t,s)=>{const n=os(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ce(n??e,`needs ${s} so codegen can read its topics`);if(Wi(i))throw ce(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Bm=(e,t)=>{const s=bn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ce(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Wi(n))throw ce(n,`cannot spread into or compute the keys of topic "${s}"`);if(!yn(s)||$m(s))throw new z("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(os(n,"key")===void 0)return{fields:[],name:s};const a=qi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>bn(l)),c=a.find(l=>!yn(l));if(c!==void 0)throw new z("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}},Vm=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ce(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Ui(n))throw ce(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=os(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ce(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:I(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Bm(a,l))}},Um=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 z("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)}},Wm=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},qm=(e,t)=>x(e,d.CallExpression).filter(s=>Bn(s,"defineLiveStream")).map(s=>{const n=Wm(s),i=r.isVariableDeclaration(n)?Ht(n,"binding"):void 0;if(i===void 0)throw new z("LIVE_STREAM_NOT_EXPORTED",ue(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 Vm(s,i,t)}),jm=(e,t)=>{const s=y(t).flatMap(n=>qm(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return Um(s),s},Hm=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Gm=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Hm(e):!0,ji=(e,t=!1)=>{for(const s of e.getProperties()){if(Gm(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||ji(n,!0))return!0}return!1},Ym=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Qn(n))for(const o of Qt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||ji(a)))return!0}}return!1},Qm=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Ue(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=Ue(a);c!==void 0&&s.push({column:c,strategy:Un(a),table:i})}}return s},Xm=(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 Qn(i))for(const a of Qt(o))for(const c of Qm(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Jm=["providerSubscriptionId","state"],Zm=["providerEventId","processedAt"],Nn=(e,t)=>t.every(s=>s in e.shape),eh=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&&Nn(t,Jm)&&Nn(s,Zm)},th=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],sh=(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},nh=(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},ih="@lunora/privacy",Hi="userId",Pn=new Set(["user","users"]),rh=e=>e.replaceAll("\\","/"),oh="privacy",ah=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),it=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ie=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",as=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),ch=(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},rt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},lh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=ch(s,"tables"),i=it(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:as(n).map(a=>Ie(a)))t.datasets.set(o,i)},cs=8,he=(e,t=0)=>{if(t>cs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return he(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:he(i,t+1)},dh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:he(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?as(n):[],o=new Set(i.map(a=>Ie(a)));for(const a of th)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?it(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ie(a)==="user"&&t.userTables.add(c))}},wn=(e,t,s)=>{t.datasets.set(it(e.getArguments()[0])??s,s)},uh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ie(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()]}},Gi=(e,t=0)=>{const s=he(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>cs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Gi(i.getExpression(),t+1):[uh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},fh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Gi(t)},gh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:he(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?as(n):[])t.excluded.set(Ie(i),r.isPropertyAssignment(i)?it(i.getInitializer())??"":"")},ph=(e,t)=>{switch(rt(e)){case"actionCacheDataset":{wn(e,t,"actionCache");break}case"authDataset":{dh(e,t);break}case"defineDataset":{lh(e,t);break}case"documentHistoryDataset":{wn(e,t,"documentHistory");break}}},ls=e=>e!==void 0&&r.isCallExpression(e)&&rt(e)==="defineDataset",Yi=e=>e!==void 0&&r.isCallExpression(e)&&ah.has(rt(e)??""),mh=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)&&(ls(i)||Yi(i))?n:void 0},Qi=(e,t,s=0)=>{const n=he(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>cs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Qi(i.getExpression(),t,s+1))return!1}else if(!ls(i)&&!Yi(i)){const o=r.isIdentifier(i)?mh(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},hh=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Qi(t,s)?s:void 0},vh=(e,t)=>{const s=[];for(const i of x(e,d.CallExpression))if(ph(i,t),rt(i)==="definePrivacy"){const o=fh(i);gh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:hh(o)})}return{declared:x(e,d.VariableDeclaration).filter(i=>ls(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Eh=(e,t)=>{const s=E(t,"schema.ts"),n=[...y(t),..._(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>rh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},xh=(e,t,s)=>{if(s?.has(ih)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Pn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Pn)},i=[],o=[];for(const f of Eh(e,t)){const g=vh(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:sh(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},Xi=(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&&Xi(n,t)),Sh=(e,t)=>e.extensionKey!==oh&&(Hi in e.shape||Object.values(e.shape).some(s=>Xi(s,t))),Ah=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 "${Hi}" 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.`,yh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Sh(o,t.userTables)).map(o=>o.name),[n]=nh(s,t.classifications);if(n!==void 0)throw new z("PRIVACY_COVERAGE",Ah(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new z("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},bh=(e,t)=>{const s=Ko(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")}},Nh=new Set(["delete","hardDelete","patch","replace","restore"]),Ph=new Set(["insertMany","insertManyUnsafe","patchIf","patchWhere"]),wh=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),In=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],i=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return i.length===n.length?i:[]},Ih=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const i=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return i===void 0?[]:In(i,e)}return In(s,e)},Tn="",Th=(e,t)=>{if(t!=="patch"&&t!=="patchMany")return;const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=[];for(const i of s.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isShorthandPropertyAssignment(i))return;n.push(i.getName())}return n},Ch=(e,t)=>{if(Ph.has(e))return{method:e,tables:[t!==void 0&&r.isStringLiteral(t)?t.getLiteralText():Tn]};if(Nh.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:Ih(t,e);return{method:e,tables:s.length===0?[Tn]:s}}},Cn=(e,t)=>e===void 0?void 0:{...e,fields:Th(t,e.method)},Oh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if($(n))return Cn(Ch(s,e.getArguments()[0]),e);if(wh.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Cn({method:s,tables:[n.getName()]},e)},kh=(e,t)=>C(e,t,(s,n)=>{const i=Oh(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}))}),Rh=(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"}),Fh=(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 Zt(e,t).opaque},Lh=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=te(a);c!==void 0&&Fh(a,c.receiver)&&s.push(Rh(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},Dh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...Lh(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Mh=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)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. 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"}]]),Ye=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Ji=e=>!e.isAny(),Zi=e=>{const t=e.getType();if(!Ji(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Mh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},_h=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},er={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."},zh=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.`}),Kh={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)."},$h=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Bh={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)."},Vh=(e,t,s)=>{if(!t.some(i=>Rr(i)))return Kh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return $h.has(s.typeName)&&!n&&!t.some(i=>oa(i))?Bh:er},tr=(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:zh(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"}},Uh=(e,t,s)=>{const n=[];for(const i of X(e)){const o=r.isIdentifier(i.getNameNode())?Tt(i):[i.getName()],c=o.some(u=>Ye(s,t,u))||!_h(i)?void 0:Zi(i),[l=i.getName()]=o;c!==void 0&&n.push(tr(t,l,c,i.getStartLineNumber(),Vh(i,o,c)))}return n},Wh=(e,t,s)=>{if(Ye(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=Zi(i.getExpression());o!==void 0&&n.push(tr(t,"default",o,i.getStartLineNumber(),er))}return n},qh=(e,t,s)=>[...Uh(e,t,s),...Wh(e,t,s)],jh=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Tt(n).some(i=>Ye(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Tt(n).find(o=>Ye(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Hh=({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"}),Gh=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...qh(c,l,s)),i.push(...jh(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Ji(a.getType()))&&n.push(Hh(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Yh=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"},Qh=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Xh=(e,t)=>C(e,t,(s,n)=>Yh(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:Qh(s)}:void 0),Te=(e,t)=>{_(e)&&Qe(e,"utf8")===t||hr(e,t,"utf8")},Jh=(e,t)=>{if(t===""){Ne(e,{force:!0});return}Te(e,t)},Zh=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){Ne(s,{force:!0,recursive:!0});return}if(_(s))for(const n of On(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[kn(e,i)]===void 0&&Ne(i)}for(const[n,i]of Object.entries(t))Vt(Ut(E(e,n)),{recursive:!0}),Te(E(e,n),i)},ev=(e,t,s)=>{const n=E(e,t);if(Object.keys(s).length===0){Ne(n,{force:!0,recursive:!0});return}if(_(n))for(const i of On(n,{recursive:!0,withFileTypes:!0})){const o=E(i.parentPath,i.name);i.isFile()&&s[kn(n,o)]===void 0&&Ne(o)}for(const[i,o]of Object.entries(s)){const a=E(n,i);Vt(Ut(a),{recursive:!0}),Te(a,o)}},tv=e=>{try{const t=ca(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Ve=(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)},sv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,nv=(e,t)=>{_(e)||Vt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Te(E(e,n.name),n.content),s.push(n.name);break}case"directory":{ev(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{Zh(e,n.files),s.push(...Object.keys(n.files));break}default:Jh(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},iv=e=>{const t=tv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=da({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=fa({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.`)},$p="env.ts",Bp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return st(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Vp=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&&st(n.getModuleSpecifierValue())}return!1},Up=e=>{if(r.isIdentifier(e))return Bp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&Vp(t)}return!1},Wp=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Up(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ue(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=Qt(s,"member");a!==void 0&&t.push({exportName:a})}return t},qp=(e,t)=>{const s=E(t,$p);if(!_(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Wp(n);if(i.length!==0){if(i.length>1)throw ue(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},jp={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},Hp=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Gp=(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())},Yp=(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"}),Qp=new Set(["durable"]),Xp=new Set(["rollback"]),_i=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Jp="defineApp",be="app",Sn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===be&&s.getInitializer()?.getText()===t)||t===be&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===be),Zp=e=>{if(e===void 0||!To.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===be;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===be;if(r.isVariableDeclaration(t))return Sn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&Sn(e.getSourceFile(),s)},em="AppBuilder",zi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},tm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===em&&s.getDeclarations().some(n=>zi(n))},sm=e=>e.getText()===Jp&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||zi(t)),Ki=(e,t,s=new Set)=>{const n=Ze(t);if(n===void 0||!r.isIdentifier(n))return!1;if(sm(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 Zp(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 Ki(e,a.getInitializer(),s)}}return!1},$i=(e,t)=>{const s=Gt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Ki(e,s.object)||tm(s.object))},nm=new Map([["defineContainer",{keys:Hp,signal:"containerEgressPolicy"}],["defineStep",{keys:Xp,signal:"workflowRollback"}],["stream",{keys:Qp,signal:"durableStreams"}]]),im=(e,t)=>{const s=nm.get(_i(t));if(s!==void 0)return t.getArguments().some(n=>Yp(Gp(e,n),s.keys))?s.signal:void 0},rm=(e,t)=>jp[_i(t)]??($i(e,t)?"deliveryAuthorization":void 0),om=(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=No(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=x(o,d.CallExpression);for(const c of a){const l=im(o,c)??rm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>Vn(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 jt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Xe(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>$i(i,o))}return n},am=(e,t)=>{const s=wo();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Po(i,s))return!0}return!1},cm="createWorker",lm="extend",An=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,yn=e=>{const t=[],s=An(F(e,"backupCron"));s!==void 0&&t.push(s);const n=F(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=An(i.getNameNode());o!==void 0&&t.push(o)}return t},dm=e=>{const t=w(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===cm)return r.isObjectLiteralExpression(s)?yn(s):[];if(t!==lm||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Fn(s.getBody());return n===void 0?[]:yn(n)},um=(e,t)=>{const s=[];for(const{filePath:n}of Je(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression))s.push(...dm(o))}return[...new Set(s)]},Bi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Bi(e.inner)},fm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Bi(n);return i!==void 0&&t.has(i)}))},gm=(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 z("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 z("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})}},pm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=sd(s,t),a=qp(s,t),c=uo(s,t),{queues:l,topics:u}=Oo(s,t),f=Ro(n),g=Ao(s,t);gm(c,g);const m=yo(s,t),v=Fo(s,t),B=bo(s,t,c,g),fe=um(s,t),N=om(s,t,Co(n)),V=ko(s,t),G=am(s,t),L=Io(s,t);L.browser=L.browser||V.usesSandboxBrowser;const R=kt(n,e.target),O=Lo(L,R,{agents:g.length>0,commitOrderedTables:i.tables.some(M=>M.commitOrdered===!0),cronTriggers:B.length>0,crossShardFanout:i.tables.some(M=>Bo(M)),containerEgressPolicy:N.containerEgressPolicy,containerRuntimeScheduling:m.some(M=>M.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(M=>M.sandbox===!0),deliveryAuthorization:N.deliveryAuthorization,durableStreams:N.durableStreams,globalTables:i.tables.some(M=>M.shardMode==="global"),liveContext:N.liveContext,liveStreams:N.liveStreams,typedWebSockets:N.typedWebSockets,queues:l.length>0,relationGraph:fm(i),secretValues:G,secrets:N.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:N.workflowRollback,workflowSchedules:c.some(M=>M.schedules!==void 0)}),W=O.usage,J=So(W),se=O.signals.vectorStore!==!1,ne=O.signals.services===!1?[]:f,ae=Yn(n),$=ae??new Set,P=$.has("lunorash");Kp(i,ae,{hasVectors:se,scheduler:W.scheduler||B.length>0,storage:W.storage||v.rules.length>0||Object.keys(Qn(i)).length>0,usage:W});const k=_(E(t,"flags.ts")),Ce=_(E(t,"notify.ts"));return{agents:g,capabilities:J,containers:m,crons:B,dataModelContent:qo(i),declaredDependencies:ae,dependencies:$,entryCronTriggers:fe,env:a,featureUsage:W,hasFlags:k,hasNotify:Ce,identity:o,platformGate:{...O,diagnostics:[...Do(n,e.target),...O.diagnostics,...Mo(R,i.vectorIndexes),...N.liveStreams&&N.deliveryAuthorization?[_o(R)]:[],...N.socketRoutes&&N.deliveryAuthorization?[zo(R)]:[]]},queues:l,serverContent:Uo({agents:g,capabilities:J,containers:m,env:a,hasVectors:se,hasFlags:k,hasNotify:Ce,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:v.rules.map(M=>M.bucket),topics:u,useUmbrella:P,workflows:c}),services:ne,storageRulesMetadata:v,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:P,workflows:c}},Vi=(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},mm=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},hm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),vm=/^[\w$]+:[\w$]+$/u,Em=(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},bn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},xm=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return bn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Ht.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?bn(s):void 0}}},Sm=(e,t,s)=>({schedule:{argKeys:xm(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Am=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Mn.has(s))return Em(s,n);if((s==="runAfter"||s==="runAt")&&mm(t)){const l=_n(i)??(r.isStringLiteral(i)&&vm.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,...Sm(s,n,o)}}const a=hm.get(s),c=a===void 0?void 0:Vi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},ym=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Ui=e=>Ar.isOptionalChain(e.compilerNode),bm=(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:oe(t)?t.getFirstAncestor(oe)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&ym.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Ui(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Dg(s)),Nm=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(oe);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(oe),i))===!0},Pm=(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)),wm=(e,t)=>{if(Ui(e)||t==="schedule"&&Nm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(bm(s,i)){if(!Pm(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Nn=(e,t,s)=>{if(s===void 0)return;const n=wm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Im=(e,t)=>[...C(e,t,(s,n)=>Nn(s,n,Am(s))),...ie(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Vi(s,"services");return Nn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Tm=new Set(["boolean","number","object","string"]),Cm=e=>{const t=e.getName();if(!Tm.has(t))return;const s=e.getExpression();return Y(s,["flags"])||Y(s,["flags","details"])?t:void 0},Om=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Cm(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},km=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression)){const a=Om(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))},Rm=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"||jo(o))return;const a=e.getSourceFile().getFilePath();if(Ho(i,e,a)){const c=Go(i,e,a,0,new Set);return c===void 0&&Yo(o),c}return o},Fm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=$r(t.getNameNode());return s===void 0||s==="namespace"}),Lm=(e,t)=>{for(const{filePath:s}of Je(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of x(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Fm(a)))return i}}},Dm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Mm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ue(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 (${Dm}). 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})},_m="room:",zm="__lunora_socket__:",Km=/^[A-Za-z]\w*$/u,Pn=e=>Km.test(e),$m=e=>`${e}:`.startsWith(_m)||`${e}:`.startsWith(zm),Wi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),qi=e=>Wi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),wn=e=>A(e),ls=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),ce=(e,t)=>{const s=ue(e,`defineLiveStream ${t}`);return new z("LIVE_STREAM_NOT_LITERAL",s.message)},ji=(e,t,s)=>{const n=ls(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ce(n??e,`needs ${s} so codegen can read its topics`);if(qi(i))throw ce(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Bm=(e,t)=>{const s=wn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ce(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(qi(n))throw ce(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Pn(s)||$m(s))throw new z("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(ls(n,"key")===void 0)return{fields:[],name:s};const a=ji(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>wn(l)),c=a.find(l=>!Pn(l));if(c!==void 0)throw new z("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}},Vm=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ce(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Wi(n))throw ce(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=ls(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ce(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=ji(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:I(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Bm(a,l))}},Um=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 z("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)}},Wm=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},qm=(e,t)=>x(e,d.CallExpression).filter(s=>Vn(s,"defineLiveStream")).map(s=>{const n=Wm(s),i=r.isVariableDeclaration(n)?Qt(n,"binding"):void 0;if(i===void 0)throw new z("LIVE_STREAM_NOT_EXPORTED",ue(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 Vm(s,i,t)}),jm=(e,t)=>{const s=y(t).flatMap(n=>qm(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return Um(s),s},Hm=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,Gm=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Hm(e):!0,Hi=(e,t=!1)=>{for(const s of e.getProperties()){if(Gm(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Hi(n,!0))return!0}return!1},Ym=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Xn(n))for(const o of Zt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Hi(a)))return!0}}return!1},Qm=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=We(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=We(a);c!==void 0&&s.push({column:c,strategy:Wn(a),table:i})}}return s},Xm=(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 Xn(i))for(const a of Zt(o))for(const c of Qm(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Jm=["providerSubscriptionId","state"],Zm=["providerEventId","processedAt"],In=(e,t)=>t.every(s=>s in e.shape),eh=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&&In(t,Jm)&&In(s,Zm)},th=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],sh=(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},nh=(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},ih="@lunora/privacy",Gi="userId",Tn=new Set(["user","users"]),rh=e=>e.replaceAll("\\","/"),oh="privacy",ah=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),rt=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ie=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",ds=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),ch=(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},ot=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},lh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=ch(s,"tables"),i=rt(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:ds(n).map(a=>Ie(a)))t.datasets.set(o,i)},us=8,he=(e,t=0)=>{if(t>us)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return he(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:he(i,t+1)},dh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:he(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?ds(n):[],o=new Set(i.map(a=>Ie(a)));for(const a of th)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?rt(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ie(a)==="user"&&t.userTables.add(c))}},Cn=(e,t,s)=>{t.datasets.set(rt(e.getArguments()[0])??s,s)},uh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ie(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()]}},Yi=(e,t=0)=>{const s=he(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>us)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Yi(i.getExpression(),t+1):[uh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},fh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Yi(t)},gh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:he(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?ds(n):[])t.excluded.set(Ie(i),r.isPropertyAssignment(i)?rt(i.getInitializer())??"":"")},ph=(e,t)=>{switch(ot(e)){case"actionCacheDataset":{Cn(e,t,"actionCache");break}case"authDataset":{dh(e,t);break}case"defineDataset":{lh(e,t);break}case"documentHistoryDataset":{Cn(e,t,"documentHistory");break}}},fs=e=>e!==void 0&&r.isCallExpression(e)&&ot(e)==="defineDataset",Qi=e=>e!==void 0&&r.isCallExpression(e)&&ah.has(ot(e)??""),mh=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)&&(fs(i)||Qi(i))?n:void 0},Xi=(e,t,s=0)=>{const n=he(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>us)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Xi(i.getExpression(),t,s+1))return!1}else if(!fs(i)&&!Qi(i)){const o=r.isIdentifier(i)?mh(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},hh=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Xi(t,s)?s:void 0},vh=(e,t)=>{const s=[];for(const i of x(e,d.CallExpression))if(ph(i,t),ot(i)==="definePrivacy"){const o=fh(i);gh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:hh(o)})}return{declared:x(e,d.VariableDeclaration).filter(i=>fs(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Eh=(e,t)=>{const s=E(t,"schema.ts"),n=[...y(t),..._(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>rh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},xh=(e,t,s)=>{if(s?.has(ih)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Tn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Tn)},i=[],o=[];for(const f of Eh(e,t)){const g=vh(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:sh(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},Ji=(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&&Ji(n,t)),Sh=(e,t)=>e.extensionKey!==oh&&(Gi in e.shape||Object.values(e.shape).some(s=>Ji(s,t))),Ah=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 "${Gi}" 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.`,yh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Sh(o,t.userTables)).map(o=>o.name),[n]=nh(s,t.classifications);if(n!==void 0)throw new z("PRIVACY_COVERAGE",Ah(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new z("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},bh=(e,t)=>{const s=Ko(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")}},Nh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),On=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Ph="",wh=(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},Ih=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Ht.Const?t.getInitializer():void 0},Ve=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ve(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Ih(e);if(n!==void 0)return Ve(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},Th=(e,t)=>{if(Nh.has(e))return{method:e,tables:Ve(t)??[Ph]}},Tt=(e,t,s)=>e===void 0?void 0:{...e,fields:wh(t,e.method,s)},Ch=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()===Ht.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!K(s.getExpression())))return s.getName()},Oh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Ch(n);if(i!==void 0)return On.has(s)?Tt({method:s,tables:[i]},e,1):void 0;if(K(n))return Tt(Th(s,e.getArguments()[0]),e,2);if(On.has(s)&&r.isPropertyAccessExpression(n)&&K(n.getExpression()))return Tt({method:s,tables:[n.getName()]},e,1)},kh=(e,t)=>C(e,t,(s,n)=>{const i=Oh(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}))}),Rh=(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"}),Fh=(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 ss(e,t).opaque},Lh=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=te(a);c!==void 0&&Fh(a,c.receiver)&&s.push(Rh(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},Dh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...Lh(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Mh=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)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. 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"}]]),Qe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Zi=e=>!e.isAny(),er=e=>{const t=e.getType();if(!Zi(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Mh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},_h=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},tr={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."},zh=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.`}),Kh={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)."},$h=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Bh={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)."},Vh=(e,t,s)=>{if(!t.some(i=>Rr(i)))return Kh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return $h.has(s.typeName)&&!n&&!t.some(i=>oa(i))?Bh:tr},sr=(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:zh(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"}},Uh=(e,t,s)=>{const n=[];for(const i of X(e)){const o=r.isIdentifier(i.getNameNode())?Ot(i):[i.getName()],c=o.some(u=>Qe(s,t,u))||!_h(i)?void 0:er(i),[l=i.getName()]=o;c!==void 0&&n.push(sr(t,l,c,i.getStartLineNumber(),Vh(i,o,c)))}return n},Wh=(e,t,s)=>{if(Qe(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=er(i.getExpression());o!==void 0&&n.push(sr(t,"default",o,i.getStartLineNumber(),tr))}return n},qh=(e,t,s)=>[...Uh(e,t,s),...Wh(e,t,s)],jh=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Ot(n).some(i=>Qe(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Ot(n).find(o=>Qe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Hh=({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"}),Gh=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...qh(c,l,s)),i.push(...jh(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!Zi(a.getType()))&&n.push(Hh(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Yh=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"},Qh=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Xh=(e,t)=>C(e,t,(s,n)=>Yh(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:Qh(s)}:void 0),Te=(e,t)=>{_(e)&&Xe(e,"utf8")===t||vr(e,t,"utf8")},Jh=(e,t)=>{if(t===""){Ne(e,{force:!0});return}Te(e,t)},Zh=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){Ne(s,{force:!0,recursive:!0});return}if(_(s))for(const n of kn(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[Rn(e,i)]===void 0&&Ne(i)}for(const[n,i]of Object.entries(t))Wt(qt(E(e,n)),{recursive:!0}),Te(E(e,n),i)},ev=(e,t,s)=>{const n=E(e,t);if(Object.keys(s).length===0){Ne(n,{force:!0,recursive:!0});return}if(_(n))for(const i of kn(n,{recursive:!0,withFileTypes:!0})){const o=E(i.parentPath,i.name);i.isFile()&&s[Rn(n,o)]===void 0&&Ne(o)}for(const[i,o]of Object.entries(s)){const a=E(n,i);Wt(qt(a),{recursive:!0}),Te(a,o)}},tv=e=>{try{const t=ca(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Ue=(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)},sv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,nv=(e,t)=>{_(e)||Wt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Te(E(e,n.name),n.content),s.push(n.name);break}case"directory":{ev(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{Zh(e,n.files),s.push(...Object.keys(n.files));break}default:Jh(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},iv=e=>{const t=tv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=da({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=fa({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
29
29
  `,openApiModuleContent:ua(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
30
- `,openRpcModuleContent:ga(i)}},rv=".lunora-schema.json",ov=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},av=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new z("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 z("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 z("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})}},cv=8,lv=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:v}=e,B=()=>Xo(()=>{const L=Jo(l,a,{lazyFunctions:o}),R=Yr(l,a);return{functions:L,httpRoutes:Zo(l,a),mutators:R}});let{erased:fe,value:{functions:N,httpRoutes:V,mutators:G}}=B();hn([...N,...G].map(L=>L.filePath)),hn(V.filter(L=>L.stream).map(L=>L.filePath),"http-stream");for(let L=1;;L+=1){const R=u?N:N.filter(P=>P.channel?.kind!=="room"&&P.lifecycle!=="socket"),O=Aa({agents:t,functions:R,httpRoutes:V,mutators:G,useUmbrella:m,workflows:v}),W={agents:t,functions:R,lazyFunctions:o,migrations:c,mutators:G,shapes:f,useUmbrella:m,usesSandbox:g},J=Oa(W),se=ka(W),ne=ya({functions:N,useUmbrella:m}),ae=E(a,"_generated",Xn),K=[[s,O],[i,ne],[n,J],...Object.entries(se).map(([P,k])=>[E(ae,P),k])];if(L>=cv||K.every(([P,k])=>sv(l,P,k)))return{apiContent:O,erased:fe,functions:N,functionModulesContent:se,functionsContent:J,httpRoutes:V,internalContent:ne,mutators:G};for(const[P,k]of K)Ve(l,P,k);({erased:fe,value:{functions:N,httpRoutes:V,mutators:G}}=B())}},dv=e=>{const t=ov(),s=t?vt.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=E(n,"schema.ts");if(!_(o))throw new z("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??Eo(n);Vr(Rm);const c=ia(a,o,e.projectRoot);yh(c.tables,xh(a,n,Gn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:v,entryCronTriggers:B,env:fe,featureUsage:N,hasFlags:V,hasNotify:G,identity:L,platformGate:R,queues:O,serverContent:W,services:J,storageRulesMetadata:se,topics:ne,usesSandbox:ae,useUmbrella:K,workflows:P}=pm({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Mm(c,c.jurisdiction===void 0?void 0:Lm(a,n));const k=E(n,"_generated"),Ce=E(k,"dataModel.ts"),M=E(k,"server.ts"),sr=E(k,"api.ts"),nr=E(k,"internal.ts"),ir=E(k,"functions.ts");Ve(a,Ce,m),Ve(a,M,W);const ds=Object.fromEntries(J.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(Wo(p,k))));for(const[p,ht]of Object.entries(ds))Ve(a,E(k,p),ht);const Oe=ta(a,n),ge=ra(a,n),ot=R.signals.typedWebSockets!==!1,{apiContent:us,erased:rr,functions:Z,functionModulesContent:fs,functionsContent:gs,httpRoutes:at,internalContent:ps,mutators:ct}=lv({agents:l,apiPath:sr,generatedFunctionsPath:ir,internalPath:nr,lazyFunctions:i,roomsSupported:ot,lunoraDirectory:n,migrations:Oe,project:a,shapes:ge,useUmbrella:K,usesSandbox:ae,workflows:P}),ms=ao(a,n),lt=co(ms,c,[...Z,...at].map(p=>p.filePath)),ke=ms.length>0,Re=e.lint===!1&&!ke?void 0:{callEdges:Im(a,n),inserts:ea(a,n),queries:sa(a,n,Z),tableWrites:kh(a,n),workflowCalls:Xh(a,n)},Fe=e.lint===!1||Re===void 0?void 0:pp(a,n,{callSites:Re,containers:f,crons:g,functions:Z,modules:lt,mutators:ct,queues:O,schema:c,shapes:ge,workflows:P,wranglerVariables:e.wranglerVariables}),hs=Fe===void 0?[]:Ap(e.projectRoot,[...vr(Fe,{source:"static"}),...Gh(a,n,{byName:new Set([...P,...O,...l,...f].map(p=>p.exportName)),byPath:new Set([...Z,...ct,...ge,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...Dh(a,n),...Qo(rr,n),...pa(O,e.wranglerQueueProducers)]),or=na(a,n),vs=Xm(a,n);av(ge,vs,Ym(a,n));const ar=V?km(a,n):[],dt=R.signals.vectorStore!==!1,cr=$o(Ct(e.projectRoot,e.target),"deliveryAuthorization"),ve=bh(N,{containerCount:f.length,cronCount:g.length,dependencies:v,hasPaymentTables:eh(c.tables),queueCount:O.length,storageColumnCount:Object.keys(Yn(c)).length,storageRuleCount:se.rules.length,vectorIndexCount:c.vectorIndexes.length,target:Ct(e.projectRoot,e.target),vectorStoreSupported:dt,workflowCount:P.length}),Es=t?vt.now():0,ut=la(c,Oe.map(p=>p.id)),ft=jm(a,n),xs=Vo({advisories:hs.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Fe?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:fe,flagKeys:ar,hasFlags:V,hasNotify:G,hasRooms:ot&&Z.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:l.length>0||Z.some(p=>vo(p)),hasSecretValues:R.signals.secretValues===!0,hasSockets:ot&&Z.some(p=>p.lifecycle==="socket"),lazyFunctions:i,hasVectors:dt,liveStreamDeclarations:ft,liveStreams:R.signals.liveStreams===!0,maskMetadata:vs,mutators:ct,queues:O,rlsMetadata:or,schema:c,schemaSnapshot:ut,shapes:ge,services:J,storageRules:se,studioFeatures:ve,topics:ne,useUmbrella:K,workflows:P}),Ss=xa(ge,v.has("@lunora/db"),K),As=ma(f,c.jurisdiction),ys=ha(P),bs=va(l),Ns=Ea(O,e.wranglerQueueProducers),Ps=Ra(ft,K),ws=ba(g),lr=Na(ve.scheduler),dr=Pa(c.tables,K,c.jurisdiction),ur=oo(e.projectRoot)?wa(K):"",Is=Ia(c.vectorIndexes),Le=Ca(c,K),Ts=Sa(v.has("@lunora/seed")),De=e.apiSpec??"openapi",gt=De==="openapi"||De==="both",pt=De==="openrpc"||De==="both",Cs=aa({capabilities:u,emailAgents:l.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:v.has("@lunora/cloudflare-access"),hasAuth:v.has("@lunora/auth"),hasFramework:v.has("@lunora/astro")||v.has("@lunora/svelte")||v.has("@lunora/vue")||_(E(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>jn(p)),hasHyperdriveGlobal:c.tables.some(p=>Hn(p)),hasKvIntrospector:ve.kv,hasNotify:G,hasQueue:O.some(p=>p.mode==="push"),liveStreams:R.signals.liveStreams===!0,liveStreamsWithheld:R.liveStreamsWithheld,liveStreamDeclarations:ft,hasScheduler:ve.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:ve.storage,hasDeliveryAuthorization:cr,hasVectors:dt,hasWorkflow:P.length>0,identity:L,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:K,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:gt,wantsOpenRpc:pt}),{openApiContent:Os,openApiModuleContent:ks,openRpcContent:Rs,openRpcModuleContent:Fs}=iv({functions:Z,httpRoutes:at,modules:lt,projectRoot:e.projectRoot,wantsArchitecture:ke}),Ee=ke&&Re!==void 0?Mp({...Re,crons:g,functions:Z,httpRoutes:at,modules:lt,queues:O,schema:c,services:J,topics:ne,workflows:P}):void 0,mt=E(n,rv),fr=_(mt),gr=e.dryRun?[]:nv(k,[{content:Cs,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:us,kind:"always",name:"api.ts"},{content:ps,kind:"always",name:"internal.ts"},{content:W,kind:"always",name:"server.ts"},{content:gs,kind:"always",name:"functions.ts"},{files:fs,kind:"directory",name:Xn},{content:xs,kind:"always",name:"shard.ts"},{content:ws,kind:"always",name:"crons.ts"},{content:Is,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:As,kind:"optional",name:"containers.ts"},{content:ys,kind:"optional",name:"workflows.ts"},{content:bs,kind:"optional",name:"agents.ts"},{content:Ns,kind:"optional",name:"queues.ts"},{content:Ps,kind:"optional",name:"live.ts"},{content:lr,kind:"optional",name:"scheduler.ts"},{content:dr,kind:"optional",name:"shardRegistry.ts"},{content:ur,kind:"optional",name:"durableObjects.ts"},{content:Ts,kind:"optional",name:"seed.ts"},{content:Ss,kind:"optional",name:"collections.ts"},{files:ds,kind:"services"},{content:gt?Os:"",kind:"optional",name:"openapi.json"},{content:gt?ks:"",kind:"optional",name:"openapi.ts"},{content:pt?Rs:"",kind:"optional",name:"openrpc.json"},{content:pt?Fs:"",kind:"optional",name:"openrpc.ts"},{content:Ee===void 0?"":`${JSON.stringify(Ee,void 0,2)}
31
- `,kind:"optional",name:"architecture.json"},{content:Ee===void 0?"":_p(Ee),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!fr||e.updateSchemaBaseline===!0)&&Te(mt,Er(ut)),t){const p=vt.now(),ht=Math.round(p-s),pr=Math.round(Es-s),mr=Math.round(p-Es);console.error(`@lunora/codegen: codegen took ${ht.toString()}ms (discovery ${pr.toString()}ms, emit ${mr.toString()}ms)`)}return{advisories:hs,advisorContext:Fe,agents:l,architecture:Ee,containers:f,cronTriggers:[...new Set([...Ta(g),...B])],generated:{agents:bs,api:us,app:Cs,collections:Ss,containers:As,crons:ws,dataModel:m,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:fs,functions:gs,internal:ps,live:Ps,openApi:Os,openApiModule:ks,openRpc:Rs,openRpcModule:Fs,queues:Ns,seed:Ts,server:W,shard:xs,vectors:Is,workflows:ys},migrations:Oe,outputDirectory:k,platformDiagnostics:R.diagnostics,queues:O,schemaSnapshot:ut,schemaSnapshotPath:mt,workflows:P,writtenFiles:gr}},TE=e=>Ir(()=>dv(e));export{rv as SCHEMA_SNAPSHOT_FILENAME,Eo as createCodegenProject,kE as findTsconfig,RE as refreshCodegenProject,TE as runCodegen,FE as tsconfigFingerprint};
30
+ `,openRpcModuleContent:ga(i)}},rv=".lunora-schema.json",ov=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},av=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new z("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 z("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 z("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})}},cv=8,lv=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:v}=e,B=()=>Xo(()=>{const L=Jo(l,a,{lazyFunctions:o}),R=Yr(l,a);return{functions:L,httpRoutes:Zo(l,a),mutators:R}});let{erased:fe,value:{functions:N,httpRoutes:V,mutators:G}}=B();xn([...N,...G].map(L=>L.filePath)),xn(V.filter(L=>L.stream).map(L=>L.filePath),"http-stream");for(let L=1;;L+=1){const R=u?N:N.filter(P=>P.channel?.kind!=="room"&&P.lifecycle!=="socket"),O=Aa({agents:t,functions:R,httpRoutes:V,mutators:G,useUmbrella:m,workflows:v}),W={agents:t,functions:R,lazyFunctions:o,migrations:c,mutators:G,shapes:f,useUmbrella:m,usesSandbox:g},J=Oa(W),se=ka(W),ne=ya({functions:N,useUmbrella:m}),ae=E(a,"_generated",Jn),$=[[s,O],[i,ne],[n,J],...Object.entries(se).map(([P,k])=>[E(ae,P),k])];if(L>=cv||$.every(([P,k])=>sv(l,P,k)))return{apiContent:O,erased:fe,functions:N,functionModulesContent:se,functionsContent:J,httpRoutes:V,internalContent:ne,mutators:G};for(const[P,k]of $)Ue(l,P,k);({erased:fe,value:{functions:N,httpRoutes:V,mutators:G}}=B())}},dv=e=>{const t=ov(),s=t?Et.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0,o=E(n,"schema.ts");if(!_(o))throw new z("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??Eo(n);Vr(Rm);const c=ia(a,o,e.projectRoot);yh(c.tables,xh(a,n,Yn(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:v,entryCronTriggers:B,env:fe,featureUsage:N,hasFlags:V,hasNotify:G,identity:L,platformGate:R,queues:O,serverContent:W,services:J,storageRulesMetadata:se,topics:ne,usesSandbox:ae,useUmbrella:$,workflows:P}=pm({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Mm(c,c.jurisdiction===void 0?void 0:Lm(a,n));const k=E(n,"_generated"),Ce=E(k,"dataModel.ts"),M=E(k,"server.ts"),nr=E(k,"api.ts"),ir=E(k,"internal.ts"),rr=E(k,"functions.ts");Ue(a,Ce,m),Ue(a,M,W);const gs=Object.fromEntries(J.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(Wo(p,k))));for(const[p,vt]of Object.entries(gs))Ue(a,E(k,p),vt);const Oe=ta(a,n),ge=ra(a,n),at=R.signals.typedWebSockets!==!1,{apiContent:ps,erased:or,functions:Z,functionModulesContent:ms,functionsContent:hs,httpRoutes:ct,internalContent:vs,mutators:lt}=lv({agents:l,apiPath:nr,generatedFunctionsPath:rr,internalPath:ir,lazyFunctions:i,roomsSupported:at,lunoraDirectory:n,migrations:Oe,project:a,shapes:ge,useUmbrella:$,usesSandbox:ae,workflows:P}),Es=ao(a,n),dt=co(Es,c,[...Z,...ct].map(p=>p.filePath)),ke=Es.length>0,Re=e.lint===!1&&!ke?void 0:{callEdges:Im(a,n),inserts:ea(a,n),queries:sa(a,n,Z),tableWrites:kh(a,n),workflowCalls:Xh(a,n)},Fe=e.lint===!1||Re===void 0?void 0:pp(a,n,{callSites:Re,containers:f,crons:g,functions:Z,modules:dt,mutators:lt,queues:O,schema:c,shapes:ge,workflows:P,wranglerVariables:e.wranglerVariables}),xs=Fe===void 0?[]:Ap(e.projectRoot,[...Er(Fe,{source:"static"}),...Gh(a,n,{byName:new Set([...P,...O,...l,...f].map(p=>p.exportName)),byPath:new Set([...Z,...lt,...ge,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...Dh(a,n),...Qo(or,n),...pa(O,e.wranglerQueueProducers)]),ar=na(a,n),Ss=Xm(a,n);av(ge,Ss,Ym(a,n));const cr=V?km(a,n):[],ut=R.signals.vectorStore!==!1,lr=$o(kt(e.projectRoot,e.target),"deliveryAuthorization"),ve=bh(N,{containerCount:f.length,cronCount:g.length,dependencies:v,hasPaymentTables:eh(c.tables),queueCount:O.length,storageColumnCount:Object.keys(Qn(c)).length,storageRuleCount:se.rules.length,vectorIndexCount:c.vectorIndexes.length,target:kt(e.projectRoot,e.target),vectorStoreSupported:ut,workflowCount:P.length}),As=t?Et.now():0,ft=la(c,Oe.map(p=>p.id)),gt=jm(a,n),ys=Vo({advisories:xs.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Fe?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:fe,flagKeys:cr,hasFlags:V,hasNotify:G,hasRooms:at&&Z.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:l.length>0||Z.some(p=>vo(p)),hasSecretValues:R.signals.secretValues===!0,hasSockets:at&&Z.some(p=>p.lifecycle==="socket"),lazyFunctions:i,hasVectors:ut,liveStreamDeclarations:gt,liveStreams:R.signals.liveStreams===!0,maskMetadata:Ss,mutators:lt,queues:O,rlsMetadata:ar,schema:c,schemaSnapshot:ft,shapes:ge,services:J,storageRules:se,studioFeatures:ve,topics:ne,useUmbrella:$,workflows:P}),bs=xa(ge,v.has("@lunora/db"),$),Ns=ma(f,c.jurisdiction),Ps=ha(P),ws=va(l),Is=Ea(O,e.wranglerQueueProducers),Ts=Ra(gt,$),Cs=ba(g),dr=Na(ve.scheduler),ur=Pa(c.tables,$,c.jurisdiction),fr=oo(e.projectRoot)?wa($):"",Os=Ia(c.vectorIndexes),Le=Ca(c,$),ks=Sa(v.has("@lunora/seed")),De=e.apiSpec??"openapi",pt=De==="openapi"||De==="both",mt=De==="openrpc"||De==="both",Rs=aa({capabilities:u,emailAgents:l.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:v.has("@lunora/cloudflare-access"),hasAuth:v.has("@lunora/auth"),hasFramework:v.has("@lunora/astro")||v.has("@lunora/svelte")||v.has("@lunora/vue")||_(E(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>Hn(p)),hasHyperdriveGlobal:c.tables.some(p=>Gn(p)),hasKvIntrospector:ve.kv,hasNotify:G,hasQueue:O.some(p=>p.mode==="push"),liveStreams:R.signals.liveStreams===!0,liveStreamsWithheld:R.liveStreamsWithheld,liveStreamDeclarations:gt,hasScheduler:ve.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:ve.storage,hasDeliveryAuthorization:lr,hasVectors:ut,hasWorkflow:P.length>0,identity:L,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:$,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:pt,wantsOpenRpc:mt}),{openApiContent:Fs,openApiModuleContent:Ls,openRpcContent:Ds,openRpcModuleContent:Ms}=iv({functions:Z,httpRoutes:ct,modules:dt,projectRoot:e.projectRoot,wantsArchitecture:ke}),Ee=ke&&Re!==void 0?Mp({...Re,crons:g,functions:Z,httpRoutes:ct,modules:dt,queues:O,schema:c,services:J,topics:ne,workflows:P}):void 0,ht=E(n,rv),gr=_(ht),pr=e.dryRun?[]:nv(k,[{content:Rs,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:ps,kind:"always",name:"api.ts"},{content:vs,kind:"always",name:"internal.ts"},{content:W,kind:"always",name:"server.ts"},{content:hs,kind:"always",name:"functions.ts"},{files:ms,kind:"directory",name:Jn},{content:ys,kind:"always",name:"shard.ts"},{content:Cs,kind:"always",name:"crons.ts"},{content:Os,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:Ns,kind:"optional",name:"containers.ts"},{content:Ps,kind:"optional",name:"workflows.ts"},{content:ws,kind:"optional",name:"agents.ts"},{content:Is,kind:"optional",name:"queues.ts"},{content:Ts,kind:"optional",name:"live.ts"},{content:dr,kind:"optional",name:"scheduler.ts"},{content:ur,kind:"optional",name:"shardRegistry.ts"},{content:fr,kind:"optional",name:"durableObjects.ts"},{content:ks,kind:"optional",name:"seed.ts"},{content:bs,kind:"optional",name:"collections.ts"},{files:gs,kind:"services"},{content:pt?Fs:"",kind:"optional",name:"openapi.json"},{content:pt?Ls:"",kind:"optional",name:"openapi.ts"},{content:mt?Ds:"",kind:"optional",name:"openrpc.json"},{content:mt?Ms:"",kind:"optional",name:"openrpc.ts"},{content:Ee===void 0?"":`${JSON.stringify(Ee,void 0,2)}
31
+ `,kind:"optional",name:"architecture.json"},{content:Ee===void 0?"":_p(Ee),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!gr||e.updateSchemaBaseline===!0)&&Te(ht,xr(ft)),t){const p=Et.now(),vt=Math.round(p-s),mr=Math.round(As-s),hr=Math.round(p-As);console.error(`@lunora/codegen: codegen took ${vt.toString()}ms (discovery ${mr.toString()}ms, emit ${hr.toString()}ms)`)}return{advisories:xs,advisorContext:Fe,agents:l,architecture:Ee,containers:f,cronTriggers:[...new Set([...Ta(g),...B])],generated:{agents:ws,api:ps,app:Rs,collections:bs,containers:Ns,crons:Cs,dataModel:m,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:ms,functions:hs,internal:vs,live:Ts,openApi:Fs,openApiModule:Ls,openRpc:Ds,openRpcModule:Ms,queues:Is,seed:ks,server:W,shard:ys,vectors:Os,workflows:Ps},migrations:Oe,outputDirectory:k,platformDiagnostics:R.diagnostics,queues:O,schemaSnapshot:ft,schemaSnapshotPath:ht,workflows:P,writtenFiles:pr}},TE=e=>Ir(()=>dv(e));export{rv as SCHEMA_SNAPSHOT_FILENAME,Eo as createCodegenProject,kE as findTsconfig,RE as refreshCodegenProject,TE as runCodegen,FE as tsconfigFingerprint};
@@ -0,0 +1 @@
1
+ import{LunoraError as C}from"@lunora/errors";import{Node as i,SyntaxKind as B}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as u,descendantsOfKind as V}from"./isTestPath-JdN4KXhV.mjs";import{createRequire as q}from"node:module";import{join as O}from"node:path";import{fileURLToPath as J}from"node:url";import{createJiti as U}from"jiti";import{r as K,p as W}from"./parse-validator-CP5CL6Q7.mjs";import{R as X}from"./reserved-words-CW1QFbTd.mjs";import{a as w}from"./property-name-7cBlgK_O.mjs";const Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,G=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},H=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:H(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=G(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},Q=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Y=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},ee=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Y(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:Q(e.shardMode),vectorIndexes:[]}},te=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>ee(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},ne=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},re=e=>{const t=ne(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},se=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ie=(e,t)=>{const n=re(e);if(n)try{const s=U(O(t,"noop.js")).esmResolve(n.moduleSpecifier),r=q(O(t,"noop.cjs"))(s.startsWith("file:")?J(s):s),o=se(r,n);return typeof o!="object"||o===null?void 0:te(o)}catch{return}},oe=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},y=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},N=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},v=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},P=e=>e&&oe.has(e)?e:void 0,E=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ae=(e,t)=>{const n=v(e,t);return n!==void 0&&n.length>0?n:void 0},j=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const d=l.getArguments()[0];if(!d||!i.isStringLiteral(d))throw c(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=d.getLiteralText();if(!s.has(m))throw c(d,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},le=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ce=/^(?:sqlite_|_cf_|__)/u,de=/__(?:agg|rank|geo|fts)_/u,fe=e=>ce.test(e)||de.test(e),ue=new Set(["cascade","restrict","set null"]),pe=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,k=(e,t)=>{if(pe.has(e))throw c(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(X.has(e))throw c(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw c(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(fe(e))throw c(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ge=e=>e&&ue.has(e)?e:void 0,me=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},he=(e,t,n)=>{const s=i.isPropertyAssignment(e)?e.getInitializer():void 0;if(!s||!i.isObjectLiteralExpression(s))throw c(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[r,o,a]=["table","from","to"].map(l=>f(s,l));if(r===void 0||o===void 0||a===void 0)throw c(s,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(o===a)throw c(s,`relation \`through\` has \`from\` and \`to\` both set to "${o}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:o,table:r,to:a}}},be=(e,t,n,s)=>{const r=s&&i.isObjectLiteralExpression(s)?s:void 0,o=e==="many"?r?.getProperty("through"):void 0;return o?he(o,t,n):{field:(r&&f(r,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&r?ge(f(r,"onDelete")):void 0,references:(r&&f(r,"references"))??"_id",table:n}},xe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw c(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();return be(s,w(e),a,o)},ye=e=>{const t=me(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=xe(s);r&&n.push(r)}return n},ve=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw c(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`,{code:"INDEX_FIELD_NESTED_PATH",name:"LunoraError",status:500})},Ee=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw c(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},Ie=e=>{const[t,n,s]=e,r=Ee(s),o=E(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const d of a)if(!i.isStringLiteral(d))throw c(d,`index "${o}" lists a non-literal field (${JSON.stringify(d.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(d=>i.isStringLiteral(d));for(const d of l)ve(d,d.getLiteralText(),o);return{fields:l.map(d=>d.getLiteralText()),name:o,unique:r}},we=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=v(n,"filterFields"),o=f(n,"language"),a=N(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:E(t),staged:a,strategy:l}},ke=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=y(n,"precision")),{field:s,name:E(t),precision:r}},Se=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=y(n,"after")),{after:r,field:s}},Te=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},_e=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Te(l)).filter(l=>l!==void 0))}r=v(n,"partitionBy")}return{name:E(t),partitionBy:r,sortBy:s}},Oe=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:y(s,"dimensions"),field:r,metadata:v(s,"metadata"),metric:P(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Le=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},L=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw c(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw c(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Ae=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:ae(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Ne=(e,t,n,s)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ke(n));break}case"global":{e.shardMode="global",e.globalBackend=Le(n);break}case"index":{e.indexes.unshift(Ie(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(_e(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ye(r));break}case"searchIndex":{e.searchIndexes.push(we(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:L(n[0],"deletedAt")};break}case"source":{e.externalSource=Ae(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(L(n[0],"updatedAt"));break}case"ttl":{e.ttl=Se(n);break}case"vectorize":{const r=Oe(n,s);r&&e.vectorIndexes.push(r);break}}},A=["__vocab","_config","_content","_data","_docsize","_idx"],Pe=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of A){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw c(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${A.join(", ")}.`)}},je=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw c(e,le(t))},$e=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw c(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw c(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw c(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},D=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))Ne(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=W(l);else if(l)throw c(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=$e(e,s,n),Pe(e,t,n.searchIndexes),je(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},z=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=K(r.getExpression());a!==void 0&&!s.has(a)&&z(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=w(r);if(k(a,r.getNameNode()),n.has(a))throw c(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(D(o,a))}}return t},De=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},ze=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:y(s,"dimensions"),metric:P(f(s,"metric")),name:o,table:De(s)}},F=e=>{const t=[];for(const n of e.getProperties()){const s=ze(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Fe=(e,t)=>{if(!$.test(e))throw c(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},h=(e,t,n)=>n.has(e)?S(t,e):e,x=(e,t)=>{const n=s=>s===void 0?void 0:x(s,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(s=>x(s,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([s,r])=>[s,x(r,t)]))}}},Me=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,shape:Object.fromEntries(Object.entries(e.shape).map(([o,a])=>[o,x(a,l=>h(l,t,n))])),relations:e.relations.map(o=>{const a=h(o.table,t,n);return o.through===void 0?{...o,table:a}:{...o,table:a,through:{...o.through,table:h(o.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:h(o.table,t,n)}))}},Re=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ce=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Be=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Ve=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},qe=(e,t)=>{const n=Re(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Ve(n);return s?b(s,t.getName()):void 0}return n}},Je=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,Ce(t))return t;const s=Be(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=qe(a,t)}},Ue=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ke=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=w(r);k(a,r.getNameNode()),s.push(D(o,a))}return s},We=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:F(n)},M=(e,t,n,s,r)=>{Fe(e,s);const o=new Set(t.map(d=>d.name)),a=t.map(d=>Me(d,e,o,r)),l=n.map(d=>({...d,name:S(e,d.name),table:h(d.table,e,o)}));return{tables:a,vectorIndexes:l}},Xe=(e,t,n)=>M(e,Ke(n),We(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ze=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Je(n);if(!s){if(t!==void 0){const o=ie(n,t);if(o){for(const a of o.bareTables)k(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Ue(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Xe(r.key,r.keyNode,r.options)},Ge=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},He=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ge(e)){const a=Ze(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw c(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Qe=new Set(["eu","fedramp","us"]),Ye=e=>j(e,"jurisdiction","jurisdiction",Qe,'"eu", "us", or "fedramp"'),et=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&N(r,"pinAuth")===!0}t=s}},tt=new Set(["required"]),nt=e=>j(e,"rls","rls mode",tt,'"required"'),rt=e=>{if(!i.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(!s||!i.isCallExpression(s))return;const r=s.getExpression(),o=s.getArguments()[1],a=o&&i.isObjectLiteralExpression(o)?f(o,"on"):void 0;if(!i.isIdentifier(r)||r.getText()!=="defineAggregateIndex"||a===void 0)return;t.add(a)}return t},st=(e,t)=>{if(t===void 0)return;const n=rt(t);for(const s of e)(n===void 0||n.has(s.name))&&(s.aggregateIndexed=!0)},ht=(e,t,n)=>{const s=e.addSourceFileAtPath(t),r=V(s,B.CallExpression).find(p=>{const _=p.getExpression();return i.isIdentifier(_)&&_.getText()==="defineSchema"});if(!r)throw new C("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw c(r,"defineSchema() expects an object literal");const a=z(o),l=r.getArguments()[1],d=l&&i.isObjectLiteralExpression(l)?F(l):[],m=He(r,a,n);st(a,r.getArguments()[2]);const T=[...a.flatMap(p=>p.vectorIndexes),...d,...m],R=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),I=T.find(p=>R.has(p.table));if(I)throw c(r,Z(I.table,I.name));return{jurisdiction:Ye(r),...et(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:nt(r),tables:a,vectorIndexes:T}};export{ht as default};
@@ -1 +1 @@
1
- import"./CAPABILITY_PROBES-brcmKenl.mjs";import{e}from"./server-DCjunXFf.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
1
+ import"./CAPABILITY_PROBES-brcmKenl.mjs";import{e}from"./server-8wMiVU6J.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-gWobaDx2.mjs";import"./shard-runtime-DXlpfT3P.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-wyX4XRYk.mjs";import"./shard-runtime-DXlpfT3P.mjs";import"./shared-Br_OnErI.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -326,13 +326,13 @@ export const internalAction = lunoraBuilders.internalAction as unknown as Intern
326
326
  * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
327
327
  * \`${u.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
328
328
  * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
329
- * \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
329
+ * \`ctx.db.patch("nodes", id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
330
330
  * no \`as unknown as\` cast. Runtime-identical to the package export; only the
331
331
  * context type narrows, so discovery finds a mutator authored either way.
332
332
  * @example
333
333
  * export const setText = defineMutator({
334
334
  * args: { id: v.id("nodes"), text: v.string() },
335
- * server: async (ctx, args) => { await ctx.db.patch(args.id, { text: args.text }); },
335
+ * server: async (ctx, args) => { await ctx.db.patch("nodes", args.id, { text: args.text }); },
336
336
  * });
337
337
  */
338
338
  export const defineMutator = defineMutatorBase as unknown as <Args extends Record<string, Validator> = Record<string, Validator>, ClientTx = unknown, R = unknown>(
@@ -106,18 +106,18 @@ ${y("headroom ?? this.transactionHeadroom()")}
106
106
  // A single-row \`writeRow\` delete never carries it, so it keeps the
107
107
  // table's declared \`.softDelete()\` behaviour.
108
108
  if (args.op === "delete") {
109
- await writer.delete(args.id ?? "", args.table, { hard: args.hard === true });
109
+ await writer.delete(args.table, args.id ?? "", { hard: args.hard === true });
110
110
 
111
111
  return { id: args.id ?? null, op: "delete" };
112
112
  }
113
113
 
114
114
  if (args.op === "replace") {
115
- await writer.replace(args.id ?? "", args.doc ?? {}, args.table);
115
+ await writer.replace(args.table, args.id ?? "", args.doc ?? {});
116
116
 
117
117
  return { id: args.id ?? null, op: "replace" };
118
118
  }
119
119
 
120
- await writer.patch(args.id ?? "", args.doc ?? {}, args.table);
120
+ await writer.patch(args.table, args.id ?? "", args.doc ?? {});
121
121
 
122
122
  return { id: args.id ?? null, op: "patch" };
123
123
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.361",
3
+ "version": "1.0.0-alpha.363",
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.260",
54
- "@lunora/agent": "1.0.0-alpha.251",
55
- "@lunora/container": "1.0.0-alpha.93",
53
+ "@lunora/advisor": "1.0.0-alpha.262",
54
+ "@lunora/agent": "1.0.0-alpha.253",
55
+ "@lunora/container": "1.0.0-alpha.94",
56
56
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
57
57
  "@lunora/platform": "1.0.0-alpha.75",
58
- "@lunora/queue": "1.0.0-alpha.129",
59
- "@lunora/scheduler": "1.0.0-alpha.152",
60
- "@lunora/values": "1.0.0-alpha.82",
61
- "@lunora/workflow": "1.0.0-alpha.96",
58
+ "@lunora/queue": "1.0.0-alpha.130",
59
+ "@lunora/scheduler": "1.0.0-alpha.153",
60
+ "@lunora/values": "1.0.0-alpha.83",
61
+ "@lunora/workflow": "1.0.0-alpha.97",
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{LunoraError as C}from"@lunora/errors";import{Node as i,SyntaxKind as B}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as u,descendantsOfKind as V}from"./isTestPath-JdN4KXhV.mjs";import{createRequire as q}from"node:module";import{join as _}from"node:path";import{fileURLToPath as J}from"node:url";import{createJiti as U}from"jiti";import{r as K,p as W}from"./parse-validator-CP5CL6Q7.mjs";import{R as Z}from"./reserved-words-CW1QFbTd.mjs";import{a as w}from"./property-name-7cBlgK_O.mjs";const G=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,X=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},H=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:H(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=X(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},Q=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Y=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},ee=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Y(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:Q(e.shardMode),vectorIndexes:[]}},te=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>ee(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},ne=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},re=e=>{const t=ne(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},se=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ie=(e,t)=>{const n=re(e);if(n)try{const s=U(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=q(_(t,"noop.cjs"))(s.startsWith("file:")?J(s):s),o=se(r,n);return typeof o!="object"||o===null?void 0:te(o)}catch{return}},oe=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},y=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},N=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},v=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},P=e=>e&&oe.has(e)?e:void 0,E=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ae=(e,t)=>{const n=v(e,t);return n!==void 0&&n.length>0?n:void 0},j=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const d=l.getArguments()[0];if(!d||!i.isStringLiteral(d))throw c(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=d.getLiteralText();if(!s.has(m))throw c(d,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},le=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ce=/^(?:sqlite_|_cf_|__)/u,de=/__(?:agg|rank|geo|fts)_/u,fe=e=>ce.test(e)||de.test(e),ue=new Set(["cascade","restrict","set null"]),pe=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,k=(e,t)=>{if(pe.has(e))throw c(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(Z.has(e))throw c(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw c(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(fe(e))throw c(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ge=e=>e&&ue.has(e)?e:void 0,me=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},he=(e,t,n)=>{const s=i.isPropertyAssignment(e)?e.getInitializer():void 0;if(!s||!i.isObjectLiteralExpression(s))throw c(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[r,o,a]=["table","from","to"].map(l=>f(s,l));if(r===void 0||o===void 0||a===void 0)throw c(s,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(o===a)throw c(s,`relation \`through\` has \`from\` and \`to\` both set to "${o}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:o,table:r,to:a}}},be=(e,t,n,s)=>{const r=s&&i.isObjectLiteralExpression(s)?s:void 0,o=e==="many"?r?.getProperty("through"):void 0;return o?he(o,t,n):{field:(r&&f(r,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&r?ge(f(r,"onDelete")):void 0,references:(r&&f(r,"references"))??"_id",table:n}},xe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw c(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();return be(s,w(e),a,o)},ye=e=>{const t=me(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=xe(s);r&&n.push(r)}return n},ve=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw c(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},Ee=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw c(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},Ie=e=>{const[t,n,s]=e,r=Ee(s),o=E(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const d of a)if(!i.isStringLiteral(d))throw c(d,`index "${o}" lists a non-literal field (${JSON.stringify(d.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(d=>i.isStringLiteral(d));for(const d of l)ve(d,d.getLiteralText(),o);return{fields:l.map(d=>d.getLiteralText()),name:o,unique:r}},we=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=v(n,"filterFields"),o=f(n,"language"),a=N(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:E(t),staged:a,strategy:l}},ke=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=y(n,"precision")),{field:s,name:E(t),precision:r}},Se=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=y(n,"after")),{after:r,field:s}},Te=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Oe=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Te(l)).filter(l=>l!==void 0))}r=v(n,"partitionBy")}return{name:E(t),partitionBy:r,sortBy:s}},_e=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:y(s,"dimensions"),field:r,metadata:v(s,"metadata"),metric:P(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Ae=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},A=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw c(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw c(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Le=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:ae(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Ne=(e,t,n,s)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ke(n));break}case"global":{e.shardMode="global",e.globalBackend=Ae(n);break}case"index":{e.indexes.unshift(Ie(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Oe(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ye(r));break}case"searchIndex":{e.searchIndexes.push(we(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:A(n[0],"deletedAt")};break}case"source":{e.externalSource=Le(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(A(n[0],"updatedAt"));break}case"ttl":{e.ttl=Se(n);break}case"vectorize":{const r=_e(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Pe=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw c(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},je=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw c(e,le(t))},$e=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw c(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw c(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw c(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},D=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))Ne(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=W(l);else if(l)throw c(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=$e(e,s,n),Pe(e,t,n.searchIndexes),je(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},z=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=K(r.getExpression());a!==void 0&&!s.has(a)&&z(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=w(r);if(k(a,r.getNameNode()),n.has(a))throw c(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(D(o,a))}}return t},De=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},ze=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:y(s,"dimensions"),metric:P(f(s,"metric")),name:o,table:De(s)}},F=e=>{const t=[];for(const n of e.getProperties()){const s=ze(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Fe=(e,t)=>{if(!$.test(e))throw c(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},h=(e,t,n)=>n.has(e)?S(t,e):e,x=(e,t)=>{const n=s=>s===void 0?void 0:x(s,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(s=>x(s,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([s,r])=>[s,x(r,t)]))}}},Me=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,shape:Object.fromEntries(Object.entries(e.shape).map(([o,a])=>[o,x(a,l=>h(l,t,n))])),relations:e.relations.map(o=>{const a=h(o.table,t,n);return o.through===void 0?{...o,table:a}:{...o,table:a,through:{...o.through,table:h(o.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:h(o.table,t,n)}))}},Re=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ce=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Be=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Ve=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},qe=(e,t)=>{const n=Re(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Ve(n);return s?b(s,t.getName()):void 0}return n}},Je=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,Ce(t))return t;const s=Be(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=qe(a,t)}},Ue=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ke=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=w(r);k(a,r.getNameNode()),s.push(D(o,a))}return s},We=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:F(n)},M=(e,t,n,s,r)=>{Fe(e,s);const o=new Set(t.map(d=>d.name)),a=t.map(d=>Me(d,e,o,r)),l=n.map(d=>({...d,name:S(e,d.name),table:h(d.table,e,o)}));return{tables:a,vectorIndexes:l}},Ze=(e,t,n)=>M(e,Ke(n),We(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ge=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Je(n);if(!s){if(t!==void 0){const o=ie(n,t);if(o){for(const a of o.bareTables)k(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Ue(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Ze(r.key,r.keyNode,r.options)},Xe=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},He=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Xe(e)){const a=Ge(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw c(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Qe=new Set(["eu","fedramp","us"]),Ye=e=>j(e,"jurisdiction","jurisdiction",Qe,'"eu", "us", or "fedramp"'),et=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&N(r,"pinAuth")===!0}t=s}},tt=new Set(["required"]),nt=e=>j(e,"rls","rls mode",tt,'"required"'),rt=e=>{if(!i.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(!s||!i.isCallExpression(s))return;const r=s.getExpression(),o=s.getArguments()[1],a=o&&i.isObjectLiteralExpression(o)?f(o,"on"):void 0;if(!i.isIdentifier(r)||r.getText()!=="defineAggregateIndex"||a===void 0)return;t.add(a)}return t},st=(e,t)=>{if(t===void 0)return;const n=rt(t);for(const s of e)(n===void 0||n.has(s.name))&&(s.aggregateIndexed=!0)},ht=(e,t,n)=>{const s=e.addSourceFileAtPath(t),r=V(s,B.CallExpression).find(p=>{const O=p.getExpression();return i.isIdentifier(O)&&O.getText()==="defineSchema"});if(!r)throw new C("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw c(r,"defineSchema() expects an object literal");const a=z(o),l=r.getArguments()[1],d=l&&i.isObjectLiteralExpression(l)?F(l):[],m=He(r,a,n);st(a,r.getArguments()[2]);const T=[...a.flatMap(p=>p.vectorIndexes),...d,...m],R=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),I=T.find(p=>R.has(p.table));if(I)throw c(r,G(I.table,I.name));return{jurisdiction:Ye(r),...et(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:nt(r),tables:a,vectorIndexes:T}};export{ht as default};