@lunora/codegen 1.0.0-alpha.327 → 1.0.0-alpha.328

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.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as p}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as l,errorPlatformDiagnosticNames as c,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 v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as N,discoverAgents as g}from"./packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-B81lOULB.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs";import{default as P}from"./packem_shared/discoverCrons-DBnCama4.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as y,mayReadCapabilityContext as U,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-CF7sUwa8.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs";import{default as W}from"./packem_shared/discoverFunctions-CIJja4zp.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-WBAqBcfK.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-DVIQ0i_e.mjs";import{default as w}from"./packem_shared/discoverInserts-CednbRCq.mjs";import{d as Y}from"./packem_shared/index-iWQbulvu.mjs";import{default as Z}from"./packem_shared/discoverMigrations-C9mLIhGZ.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-Jkk8Zgkb.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-B6FUSWes.mjs";import{NOTIFY_FILENAME as ae,discoverNotifyCalls as ie,discoverNotifyChannels as me,discoverNotifyConfig as fe}from"./packem_shared/NOTIFY_FILENAME-DiYZjYts.mjs";import{default as de}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-BezURxvr.mjs";import{QUEUES_FILENAME as xe,discoverQueues as Se}from"./packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs";import{default as ue}from"./packem_shared/discoverR2sqlCalls-B9Q6xfi6.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-Os1lrVX_.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-DCgP2H39.mjs";import{discoverSandboxUsage as Oe}from"./packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs";import{default as Te}from"./packem_shared/discoverSchema-BtsX-CN9.mjs";import{readServiceBindings as Ie,resolveServiceBindings as _e}from"./packem_shared/readServiceBindings-DvqIThzd.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Fe}from"./packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs";import{default as De}from"./packem_shared/discoverStorageRulesMetadata-BTD9Vs5X.mjs";import{WORKFLOWS_FILENAME as ye,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs";import{emitApp as He}from"./packem_shared/emitApp-DuJW6LKD.mjs";import{isD1GlobalTable as Be,isHyperdriveGlobalTable as ke}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-DFv-RYZU.mjs";import{OPENRPC_VERSION as qe,buildOpenRpcDocument as we,emitOpenRpc as Je,emitOpenRpcModule as Ye}from"./packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs";import{DEFAULT_TARGET as Ze,platformMatrixIds as $e,readProjectTarget as er,resolveCodegenTarget as rr}from"./packem_shared/DEFAULT_TARGET-BbWiB-rs.mjs";import{l as tr,r as sr}from"./packem_shared/project-config-file-BV7RR-l6.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ir,runCodegen as mr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-WbrlAts0.mjs";import{SchemaSnapshotParseError as pr,buildSchemaSnapshot as dr,evaluateSchemaDrift as nr,parseSchemaSnapshot as lr}from"./packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs";import{default as xr}from"./packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs";import{schemaFromIr as Er}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Ar,validatorIrToJsonSchema as vr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Nr,SDK_TARGETS as gr,generateSdk as Or}from"./sdk/index.mjs";import{redact as Tr,secretKindOf as hr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as _r}from"./packem_shared/emitDrizzleSchema-DitcRZ1a.mjs";import{e as Mr}from"./packem_shared/server-DAvi_bv_.mjs";import{e as Pr}from"./packem_shared/shard-BtImwCVL.mjs";import{G as br}from"./packem_shared/shared-DnCokNcE.mjs";import{MESSAGE_SOLUTIONS as Ur,findSolutionByMessage as Gr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as jr,findProjectConfigFile as Br}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{createCodegenProject as Wr,findTsconfig as Kr,refreshCodegenProject as Vr}from"./packem_shared/createCodegenProject-V51_yBw3.mjs";import{s as Qr,t as qr,u as wr}from"./packem_shared/shard-runtime-BpoCV-aM.mjs";import{emitApi as Yr,emitCollections as Xr,emitInternalApi as Zr}from"./packem_shared/emitApi-CDgIPAG2.mjs";import{emitCrons as eo,emitScheduler as ro,emitVectors as oo,emitWranglerCronTriggers as to}from"./packem_shared/emitCrons-BQW2lviZ.mjs";import{emitDataModel as ao}from"./packem_shared/emitDataModel-BskFt9Wv.mjs";import{emitFunctions as mo}from"./packem_shared/emitFunctions-Cg0JxGpk.mjs";import{isTypedSchema as po}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{N as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Ze as DEFAULT_TARGET,j as FLAGS_FILENAME,br as GENERATED_HEADER,Ar as LUNORA_ERROR_CODES,Ur as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,ae as NOTIFY_FILENAME,qe as OPENRPC_VERSION,jr as PROJECT_CONFIG_FILENAMES,xe as QUEUES_FILENAME,ir as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Nr as SDK_LANGUAGES,gr as SDK_TARGETS,Me as SHAPES_FILENAME,pr as SchemaSnapshotParseError,e as VERSION,ye as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,we as buildOpenRpcDocument,dr as buildSchemaSnapshot,b as capabilitiesUsedBy,Wr as createCodegenProject,n as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,g as discoverAgents,I as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyChannels,fe as discoverNotifyConfig,le as discoverQueries,Se as discoverQueues,ue as discoverR2sqlCalls,Ne as discoverRlsMetadata,ve as discoverRlsProcedures,Oe as discoverSandboxUsage,Te as discoverSchema,Fe as discoverShapes,De as discoverStorageRulesMetadata,Ue as discoverWorkflows,Qr as emitAgents,Yr as emitApi,He as emitApp,Xr as emitCollections,qr as emitContainers,eo as emitCrons,ao as emitDataModel,_r as emitDrizzleSchema,mo as emitFunctions,Zr as emitInternalApi,Ve as emitOpenApi,ze as emitOpenApiModule,Je as emitOpenRpc,Ye as emitOpenRpcModule,ro as emitScheduler,Mr as emitServer,Pr as emitShard,oo as emitVectors,wr as emitWorkflows,to as emitWranglerCronTriggers,l as errorAdvisoryNames,c as errorPlatformDiagnosticNames,nr as evaluateSchemaDrift,Gr as findLunoraSolution,Br as findProjectConfigFile,Kr as findTsconfig,xr as fingerprintSchemaSources,y as foldCapabilitySignals,m as formatAdvisories,Or as generateSdk,Be as isD1GlobalTable,ke as isHyperdriveGlobalTable,R as isTestPath,po as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,tr as loadProjectConfig,U as mayReadCapabilityContext,lr as parseSchemaSnapshot,$e as platformMatrixIds,de as readPackageDependencies,sr as readProjectConfigLiterals,er as readProjectTarget,Ie as readServiceBindings,Tr as redact,Vr as refreshCodegenProject,rr as resolveCodegenTarget,_e as resolveServiceBindings,mr as runCodegen,Er as schemaFromIr,hr as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,p as toAdvisorContext,vr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as p}from"./packem_shared/formatAdvisories-BCVASH7N.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as l,errorPlatformDiagnosticNames as c,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 v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as N,discoverAgents as g}from"./packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-B81lOULB.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-dFRtAyIe.mjs";import{default as P}from"./packem_shared/discoverCrons-DBnCama4.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as y,mayReadCapabilityContext as U,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-CF7sUwa8.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs";import{default as W}from"./packem_shared/discoverFunctions-CIJja4zp.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-WBAqBcfK.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-DVIQ0i_e.mjs";import{default as w}from"./packem_shared/discoverInserts-CednbRCq.mjs";import{d as Y}from"./packem_shared/index-iWQbulvu.mjs";import{default as Z}from"./packem_shared/discoverMigrations-C9mLIhGZ.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-Jkk8Zgkb.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-B6FUSWes.mjs";import{NOTIFY_FILENAME as ae,discoverNotifyCalls as ie,discoverNotifyChannels as me,discoverNotifyConfig as fe}from"./packem_shared/NOTIFY_FILENAME-DiYZjYts.mjs";import{default as de}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-BezURxvr.mjs";import{QUEUES_FILENAME as xe,discoverQueues as Se}from"./packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs";import{default as ue}from"./packem_shared/discoverR2sqlCalls-B9Q6xfi6.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-Os1lrVX_.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-DCgP2H39.mjs";import{discoverSandboxUsage as Oe}from"./packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs";import{default as Te}from"./packem_shared/discoverSchema-BtsX-CN9.mjs";import{readServiceBindings as Ie,resolveServiceBindings as _e}from"./packem_shared/readServiceBindings-DvqIThzd.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Fe}from"./packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs";import{default as De}from"./packem_shared/discoverStorageRulesMetadata-BTD9Vs5X.mjs";import{WORKFLOWS_FILENAME as ye,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-CdeS224T.mjs";import{emitApp as He}from"./packem_shared/emitApp-DuJW6LKD.mjs";import{isD1GlobalTable as Be,isHyperdriveGlobalTable as ke}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-DFv-RYZU.mjs";import{OPENRPC_VERSION as qe,buildOpenRpcDocument as we,emitOpenRpc as Je,emitOpenRpcModule as Ye}from"./packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs";import{DEFAULT_TARGET as Ze,platformMatrixIds as $e,readProjectTarget as er,resolveCodegenTarget as rr}from"./packem_shared/DEFAULT_TARGET-BbWiB-rs.mjs";import{l as tr,r as sr}from"./packem_shared/project-config-file-BV7RR-l6.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ir,runCodegen as mr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bc6q0Wob.mjs";import{SchemaSnapshotParseError as pr,buildSchemaSnapshot as dr,evaluateSchemaDrift as nr,parseSchemaSnapshot as lr}from"./packem_shared/SchemaSnapshotParseError-BRJT7c2k.mjs";import{default as xr}from"./packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs";import{schemaFromIr as Er}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Ar,validatorIrToJsonSchema as vr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Nr,SDK_TARGETS as gr,generateSdk as Or}from"./sdk/index.mjs";import{redact as Tr,secretKindOf as hr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as _r}from"./packem_shared/emitDrizzleSchema-DitcRZ1a.mjs";import{e as Mr}from"./packem_shared/server-DAvi_bv_.mjs";import{e as Pr}from"./packem_shared/shard-BtImwCVL.mjs";import{G as br}from"./packem_shared/shared-DnCokNcE.mjs";import{MESSAGE_SOLUTIONS as Ur,findSolutionByMessage as Gr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as jr,findProjectConfigFile as Br}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{createCodegenProject as Wr,findTsconfig as Kr,refreshCodegenProject as Vr}from"./packem_shared/createCodegenProject-V51_yBw3.mjs";import{s as Qr,t as qr,u as wr}from"./packem_shared/shard-runtime-BpoCV-aM.mjs";import{emitApi as Yr,emitCollections as Xr,emitInternalApi as Zr}from"./packem_shared/emitApi-CDgIPAG2.mjs";import{emitCrons as eo,emitScheduler as ro,emitVectors as oo,emitWranglerCronTriggers as to}from"./packem_shared/emitCrons-BQW2lviZ.mjs";import{emitDataModel as ao}from"./packem_shared/emitDataModel-BskFt9Wv.mjs";import{emitFunctions as mo}from"./packem_shared/emitFunctions-Cd0Tuw73.mjs";import{isTypedSchema as po}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{N as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Ze as DEFAULT_TARGET,j as FLAGS_FILENAME,br as GENERATED_HEADER,Ar as LUNORA_ERROR_CODES,Ur as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,ae as NOTIFY_FILENAME,qe as OPENRPC_VERSION,jr as PROJECT_CONFIG_FILENAMES,xe as QUEUES_FILENAME,ir as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Nr as SDK_LANGUAGES,gr as SDK_TARGETS,Me as SHAPES_FILENAME,pr as SchemaSnapshotParseError,e as VERSION,ye as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,we as buildOpenRpcDocument,dr as buildSchemaSnapshot,b as capabilitiesUsedBy,Wr as createCodegenProject,n as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,g as discoverAgents,I as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyChannels,fe as discoverNotifyConfig,le as discoverQueries,Se as discoverQueues,ue as discoverR2sqlCalls,Ne as discoverRlsMetadata,ve as discoverRlsProcedures,Oe as discoverSandboxUsage,Te as discoverSchema,Fe as discoverShapes,De as discoverStorageRulesMetadata,Ue as discoverWorkflows,Qr as emitAgents,Yr as emitApi,He as emitApp,Xr as emitCollections,qr as emitContainers,eo as emitCrons,ao as emitDataModel,_r as emitDrizzleSchema,mo as emitFunctions,Zr as emitInternalApi,Ve as emitOpenApi,ze as emitOpenApiModule,Je as emitOpenRpc,Ye as emitOpenRpcModule,ro as emitScheduler,Mr as emitServer,Pr as emitShard,oo as emitVectors,wr as emitWorkflows,to as emitWranglerCronTriggers,l as errorAdvisoryNames,c as errorPlatformDiagnosticNames,nr as evaluateSchemaDrift,Gr as findLunoraSolution,Br as findProjectConfigFile,Kr as findTsconfig,xr as fingerprintSchemaSources,y as foldCapabilitySignals,m as formatAdvisories,Or as generateSdk,Be as isD1GlobalTable,ke as isHyperdriveGlobalTable,R as isTestPath,po as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,tr as loadProjectConfig,U as mayReadCapabilityContext,lr as parseSchemaSnapshot,$e as platformMatrixIds,de as readPackageDependencies,sr as readProjectConfigLiterals,er as readProjectTarget,Ie as readServiceBindings,Tr as redact,Vr as refreshCodegenProject,rr as resolveCodegenTarget,_e as resolveServiceBindings,mr as runCodegen,Er as schemaFromIr,hr as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,p as toAdvisorContext,vr as validatorIrToJsonSchema};
@@ -1,4 +1,4 @@
1
- import{existsSync as M,mkdirSync as _t,readFileSync as er,writeFileSync as tr,rmSync as Se,readdirSync as En}from"node:fs";import{dirname as Kt,join as v,relative as xn}from"node:path";import{performance as ft}from"node:perf_hooks";import{runAdvisor as sr}from"@lunora/advisor";import{LunoraError as j}from"@lunora/errors";import{serializeSchemaSnapshot as nr}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as ir}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,ts as rr,VariableDeclarationKind as or}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as I,bindingKeyName as oe,collectCallRows as C,findObjectProperty as B,collectSecurityCallRows as ar,propertyInitializer as F,listSecurityScanFiles as je,objectLiteralFromCallbackBody as Sn,limitNameOf as An,optionsObjectLiteral as yn,handlerOf as cr,collectNodeRows as ne,chainRootOf as He,outermostValueWrapper as w,isWriteTarget as Ge,isSameNode as A,unwrapExpression as h,isConstDeclaration as ie,memberAccessOf as zt,returningFunctionOf as yt,walkChain as lr,RUN_METHODS as bn,functionReferenceSegments as dr,isTestPath as ur,isFunctionLike as re,functionKeyOf as Nn}from"./isTestPath-B81lOULB.mjs";import{b as Y,d as q,f as D,g as Bt,c as x,a as Pn,w as $t,k as fr,l as gr,h as pr,m as mr,j as bt,i as hr}from"./attribution-hVBriwzy.mjs";import{a as Ps,r as gt,i as H,b as vr,m as wn,c as Ye,e as Vt,E as In,C as Cn,d as Er,f as xr,g as Sr}from"./context-root-D-pTjHtx.mjs";import{a as P,i as Ar,c as ee,d as Tn,e as yr,f as br}from"./classify-procedure-call-DUBO9bqm.mjs";import{a as S,r as On,s as Nr,b as Pr}from"./project-config-file-BV7RR-l6.mjs";import{a as wr,b as Qe}from"./module-specifiers-WF8iAydP.mjs";import{r as Xe,s as Ir}from"./parse-validator-IDBKIT7M.mjs";import Cr from"./discoverAuthApiCalls-xs0ONfI-.mjs";import{i as _,r as kn}from"./database-calls-DJgmh0Kv.mjs";import Tr from"./discoverHyperdriveCalls-DVIQ0i_e.mjs";import{diagnosticAt as Ne}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Ut,a as ze,s as Rn,d as Or}from"./index-iWQbulvu.mjs";import{MUTATORS_FILENAME as kr,isDefineMutatorCallee as Rr,mutatorServerImplOf as Fr,discoverMutators as Dr}from"./MUTATORS_FILENAME-Jkk8Zgkb.mjs";import Lr from"./discoverNondeterministicCalls-B6FUSWes.mjs";import{discoverNotifyConfig as Mr,discoverNotifyCalls as _r}from"./NOTIFY_FILENAME-DiYZjYts.mjs";import Kr from"./discoverR2sqlCalls-B9Q6xfi6.mjs";import zr from"./discoverRlsProcedures-Os1lrVX_.mjs";import{s as Wt,n as Br}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as $r,redact as Vr,isHeuristicSecretKind as Ur,isSecretishName as Wr}from"./redact-Cy14LEnc.mjs";import{a as Re,d as qr,r as jr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as Hr,discoverWorkflows as Gr}from"./WORKFLOWS_FILENAME-CdeS224T.mjs";import{r as Yr}from"./json-data-Chfs2Cz5.mjs";import{G as Qr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Xr}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as Yv,refreshCodegenProject as Qv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as Jr,usedCapabilities as Zr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Fn,isHyperdriveGlobalTable as Dn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as eo}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as to}from"./CONTAINERS_FILENAME-dFRtAyIe.mjs";import so from"./discoverCrons-DBnCama4.mjs";import{contextPropertiesRead as no,discoverFeatureUsage as io}from"./capabilitiesUsedBy-CF7sUwa8.mjs";import Ln from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as ro,findProjectConfigFile as oo}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{discoverQueueDeclarations as ao}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as co}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as lo}from"./readServiceBindings-DvqIThzd.mjs";import uo from"./discoverStorageRulesMetadata-BTD9Vs5X.mjs";import{resolveCodegenTarget as Nt,gatePlatformFeatures as fo,readTargetDiagnostics as go,vectorizeDimensionDiagnostics as po,liveStreamsDeliveryAuthorizationDiagnostic as mo,socketRoutesDeliveryAuthorizationDiagnostic as ho,studioPlatformFor as vo,platformFeatureAvailable as Eo}from"./DEFAULT_TARGET-BbWiB-rs.mjs";import{i as xo}from"./schema-BgM8A3XV.mjs";import{b as Mn,e as So}from"./shard-BtImwCVL.mjs";import{e as Ao,a as yo}from"./server-DAvi_bv_.mjs";import{emitDataModel as bo}from"./emitDataModel-BskFt9Wv.mjs";import{i as No,a as Po,e as wo,b as Io,d as Co,c as To}from"./unwrap-handler-return-CeaOifqX.mjs";import Oo from"./discoverFunctions-CIJja4zp.mjs";import ko from"./discoverHttpRoutes-WBAqBcfK.mjs";import Ro from"./discoverInserts-CednbRCq.mjs";import{e as _n}from"./exported-procedure-chains-DOFtzPZn.mjs";import Fo from"./discoverMigrations-C9mLIhGZ.mjs";import Do from"./discoverQueries-BezURxvr.mjs";import Lo from"./discoverRlsMetadata-DCgP2H39.mjs";import Mo from"./discoverSchema-BtsX-CN9.mjs";import{discoverShapes as _o}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as Ko}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as zo}from"./emitApp-DuJW6LKD.mjs";import{readJsonSync as Bo}from"@visulima/fs";import{buildSchemaSnapshot as $o}from"./SchemaSnapshotParseError-BRJT7c2k.mjs";import{buildOpenApiDocument as Vo,emitOpenApiModule as Uo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as Wo,emitOpenRpcModule as qo}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as jo,t as Ho,u as Go,s as Yo,w as Qo}from"./shard-runtime-BpoCV-aM.mjs";import{emitCollections as Xo,emitSeed as Jo,emitApi as Zo,emitInternalApi as ea}from"./emitApi-CDgIPAG2.mjs";import{emitCrons as ta,emitScheduler as sa,emitShardRegistry as na,emitDurableObjects as ia,emitVectors as ra,emitWranglerCronTriggers as oa}from"./emitCrons-BQW2lviZ.mjs";import aa from"./emitDrizzleSchema-DitcRZ1a.mjs";import{LAZY_FUNCTION_DIRECTORY as Kn,emitFunctions as ca,emitLazyFunctionModules as la}from"./emitFunctions-Cg0JxGpk.mjs";const zn=new Set(["delete","get","head","options","patch","post","put"]),da=new Set(["handler","stream"]),ua=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ws=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),fa=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()}},ga=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 fa(s)},pa=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(ws.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&ws.has(s.getText()))return!0}return!1},ma=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!da.has(n.getName()))return;const i=ga(s);if(!i||!ua.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&pa(o);return{exportName:q(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},ha=(e,t)=>{const s=[];for(const n of Y(e)){const i=ma(n,t);i&&s.push(i)}return s},va=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ha(i,I(t,n)))}return s},Ea=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}},xa=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)?oe(t):void 0}},Sa=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))&&Ps(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))&&Ps(i)},Is=(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=Ea(e);return n!==void 0&&xa(n)===t?!0:t==="args"&&Sa(e)},Bn=(e,t)=>r.isIdentifier(e)?Is(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Is(s,t)),Aa=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},Cs=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Bt(t)?t.getInitializer():void 0},Pt=e=>Bn(e,"args"),G=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 s.getDescendantsOfKind(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},W=e=>{if(Pt(e))return!0;const t=G(e);return t!==void 0&&Pt(t)},ya=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=G(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},ae=e=>{if(gt(e))return!0;const t=Cs(e);if(t!==void 0&&gt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=Cs(i);return o!==void 0&&gt(o)})},Fe=(e,t)=>Bn(e,t),ba=(e,t)=>{if(Fe(e,t))return!0;const s=G(e);if(s!==void 0&&Fe(s,t))return!0;const n=Aa(e);if(n!==void 0){const i=G(n);return i!==void 0&&Fe(i,t)}return!1},Na=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:H(e.getExpression(),["ai"]),Pa=(e,t)=>{if(!Na(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)||ae(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},wa=(e,t)=>C(e,t,Pa),Ia=new Set(["generateText","streamText"]),Ca=new Set(["messages","prompt","system"]),Ta=[{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"]}],Oa=(e,t)=>Ta.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ka=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[vr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Oa(i,s));return n===void 0?void 0:`${n}.${s}`},Ra=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ka(t);if(s!==void 0)return s}},Fa=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=oe(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Da=e=>{if(Pt(e))return!0;const t=Fa(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},La=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!Ca.has(S(t)))continue;const s=t.getInitializer();if(s!==void 0&&Da(s))return!0}return!1},Ma=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=P(n.getExpression());if(i===void 0||!Ia.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(P(c.getExpression())==="tool"&&(a=Ra(c),a!==void 0))break;a!==void 0&&s.push({scope:x(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:La(o)})}return s},_a=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ma(i,I(t,n)))}return s},Ka=e=>H(e,["fetch"]),za=(e,t)=>{if(!Ka(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},Ba=(e,t)=>C(e,t,za),qt=(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=Xe(s.getExpression());return n===void 0||qt(n,t)})}finally{t.delete(e)}},$a=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=B(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:Xe(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:qt(i)}},Va=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)?Xe(o):void 0;a===void 0?s=!0:(t.push(a),s||=qt(a))}n=i.getExpression()}return{objects:t,opaque:s}},jt=(e,t)=>t?Va(t):$a(e),$n=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=Xe(s.getExpression());return n===void 0?[]:$n(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[S(s)]:[]})}finally{t.delete(e)}},Ua=e=>e.flatMap(t=>$n(t,new Set)),Wa=new Set(["check","length","max"]),wt=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(Wa.has(s.getName()))return!0;t=n}},It=e=>wr(e)||e==="@lunora/values",qa=e=>{const t=new Set(["v"]);for(const s of Ar(e,"v",It))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&It(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},ja=(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},Ha=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Ga=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&It(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Ht=(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 Ha(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Ga(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Ya=(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)},Qa=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Xa=e=>r.isReturnStatement(e)?e.getExpression():void 0,Ja=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Qa(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Xa(t);return s?[s]:[]}),Vn=(e,t)=>{if(Ht(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Vn(e.getExpression(),t)},Za=(e,t)=>{const s=Ya(e.getExpression(),e.getSourceFile());if(!s)return[];const n=wt(e),i=new Set(Ja(s).map(o=>Vn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Ht(o,t);return a===void 0?[]:[{bounded:wt(o)||n&&i.has(o),factory:a}]})},ec=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Ht(s,t),i=n===void 0?[]:[{bounded:wt(s),factory:n}];return r.isCallExpression(s)?[...i,...Za(s,t)]:i}),tc=(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=ec(a,t),l=S(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}},sc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ee(n);if(i?.visibility!=="public")return;const{objects:o}=jt(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=tc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:q(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},nc=(e,t)=>{const s=[],n=qa(e),i={destructured:ja(e,n),namespaces:n};for(const o of Y(e)){const a=sc(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(...nc(i,I(t,n)))}return s},pt=e=>e?.getKind()===d.TrueKeyword,rc=e=>e?.getKind()===d.FalseKeyword,oc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,ac=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),cc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&P(t.getExpression())==="scim"),lc=e=>e!==void 0&&r.isCallExpression(e)&&ac.has(P(e.getExpression())??""),dc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),uc=e=>{const t=F(e,"advanced"),s=F(e,"emailAndPassword"),n=F(e,"session");return{analyzable:!0,disableCsrfCheck:pt(F(t,"disableCSRFCheck")),emailPasswordEnabled:pt(F(s,"enabled")),requireEmailVerification:pt(F(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:cc(F(e,"plugins"))&&lc(F(e,"database")),secureCookiesDisabled:rc(F(t,"useSecureCookies")),sessionFreshAgeZero:oc(F(n,"freshAge")),trustedOriginsWildcard:dc(F(e,"trustedOrigins"))}},fc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),gc=(e,t)=>{if(P(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?uc(s):fc();return{scope:x(e),file:t,line:e.getStartLineNumber(),...i}},pc=(e,t)=>ar(e,t,gc),mc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return wn(e.getExpression(),t.matchReceiver)?s:void 0},hc=(e,t,s)=>{const n=mc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!W(i)||ae(i))&&!(s.requireUnmodifiedReach===!0&&!ya(i)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:n}},Je=(e,t,s)=>C(e,t,(n,i)=>hc(n,i,s)),vc=new Set(["content","pdf","scrape","screenshot"]),Ec=(e,t)=>Je(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:vc}),xc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Sc=new Set(["RateLimiter"]),Ac=new Set(["extend"]),Ts="lunora",yc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Un=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=S(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Ct=e=>e&&r.isObjectLiteralExpression(e)?Un(e):{analyzable:!1,presentKeys:[],trueKeys:[]},bc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Sn(t.getBody());return s?Un(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Nc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=P(n.getExpression());i!==void 0&&(xc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Ct(n.getArguments()[0])}):Ac.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...bc(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=P(n.getExpression());i===void 0||!Sc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Ct(n.getArguments()[0])})}return s},Pc=(e,t)=>{for(const s of yc){const n=v(t,s);if(!M(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))P(a.getExpression())===Ts&&o.push({callee:Ts,file:s,line:a.getStartLineNumber(),...Ct(a.getArguments()[0])});return o}return[]},wc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of je(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Nc(o,n))}return s.push(...Pc(e,Kt(t))),s},Os="ctx.containers.",Ic=e=>{if(!e.startsWith(Os))return!1;const t=e.slice(Os.length);return t.length>0&&!t.includes(".")},Cc=(e,t)=>Je(e,t,{argIndex:0,matchReceiver:Ic,methods:new Set(["get"])}),Tc=new Set(["allow","deny","setAllowed"]),Oc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=B(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},kc=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Oc(e)))return{detail:"enableInternet: true",scope:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Rc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Tc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Fc=(e,t)=>kc(e,t)??Rc(e,t),Dc=(e,t)=>C(e,t,Fc),Lc=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},Mc=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&_(s)?1:0]},_c=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Kc=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=>_c.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},zc=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return C(e,t,(i,o)=>{const a=Lc(i);if(a===void 0)return;const c=Kc(Mc(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:x(i),table:a}})},Bc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),$c=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Bc.has(s)?s:void 0},Vc=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=S(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(S(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Uc=(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 o.getDescendantsOfKind(d.CallExpression)){const c=$c(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Vc(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},Wc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),qc=new Set(["dbRateLimit","rateLimit"]),jc=e=>{const t=yn(e);if(!t)return!1;const s=B(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Hc=(e,t)=>{const s=P(e.getExpression());if(s===void 0)return;const n=Wc.get(s);if(n!==void 0)return{callee:s,scope:x(e),failOpen:jc(e.getArguments()[n]),file:t,limitName:qc.has(s)?An(e):"",line:e.getStartLineNumber()}},Gc=(e,t)=>C(e,t,Hc),Yc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ee(t);if(s?.kind!=="query")return;const n=cr(t,s.receiver);return n?{exportName:q(e)??e.getName(),handler:n}:void 0},ks=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Qc=e=>{const t=ks(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=ks(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Xc=(e,t)=>{const s=[];for(const n of Ye(e.handler,"flags"))s.push({callee:Qc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Jc=(e,t)=>{const s=[];for(const n of Y(e)){const i=Yc(n);i&&s.push(...Xc(i,t))}return s},Zc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Jc(i,I(t,n)))}return s},el=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:H(e.getExpression(),["flags"]),tl=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},sl=(e,t)=>{if(!el(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=tl(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:x(e),file:t,key:i,line:e.getStartLineNumber()}},nl=(e,t)=>C(e,t,sl),il=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},rl=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},ol=(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 i.getDescendantsOfKind(d.CallExpression))il(a)&&s.push({file:o,indexName:rl(a),line:a.getStartLineNumber()})}return s},Ae=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,Wn=e=>{const t=e.getArguments()[0],s=Ae(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=B(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?Ae(n.getInitializer()):void 0},al=new Set(["delete","get","head","options","patch","post","put"]),cl=new Set(["handler","stream"]),ll=new Set(["runAction","runMutation"]),dl=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),ye=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,qn=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(oe(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Rs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:qn(s,"ctx")},Fs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:qn(s,"request")},Ds=(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(ll.has(a)&&ye(c,t))return a;if(dl.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&ye(c.getExpression(),t))return`db.${a}`}},Ls=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&ye(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!ye(n.getInitializer(),t))){for(const o of i.getElements())if(oe(o)==="auth")return!0}}return!1},ul=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,fl=(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"&&ye(n.getExpression(),t)},gl=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],jn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:gl(s)},pl=(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)?jn(t,a.getText()):[]}return[]},ml=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=jn(s,t.getText());return n.length>0?n:pl(t,s)},Ms=(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=>fl(i,t)&&ml(i).some(o=>ul.test(o)))},hl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!cl.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(al.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},vl=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ae(e.getArguments()[0]),l=c&&Rs(c,!0);if(!c||l===void 0||Ms(c,Fs(c,!0)))return;const u=Ds(c,l);return u===void 0?void 0:{scope:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Ls(c,l),sideEffect:u}}const n=hl(e);if(n===void 0)return;const i=Ae(e.getArguments()[0]),o=i&&Rs(i,!1);if(!i||o===void 0||Ms(i,Fs(i,!1)))return;const a=Ds(i,o);return a===void 0?void 0:{scope:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Ls(i,o),sideEffect:a}},El=(e,t)=>C(e,t,vl),xl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Sl=new Set(["append","set"]),Hn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",_s=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>xl.has(P(n.getExpression())??"")&&Fe(n,t)),Al=(e,t)=>{if(_s(e,t))return!0;const s=G(e);return s!==void 0&&_s(s,t)},Tt=(e,t)=>ba(e,t)&&!Al(e,t),yl=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=G(e);return t!==void 0&&r.isNewExpression(t)&&P(t.getExpression())==="Headers"},Be=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=G(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Gt=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Tt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Hn(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Tt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:S(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=Be(n.getExpression());i!==void 0&&Gt(i,t,s)}},Gn=(e,t)=>{const s=Be(e);if(s===void 0)return;const n=B(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=Be(n.getInitializer());i!==void 0&&Gt(i,"response-init",t)},bl=(e,t)=>{const s=P(e.getExpression());if(s==="Response")Gn(e.getArguments()[1],t);else if(s==="Headers"){const n=Be(e.getArguments()[0]);n!==void 0&&Gt(n,"headers-ctor",t)}},Nl=(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"){Gn(e.getArguments()[1],t);return}if(Sl.has(n)&&yl(i)){const o=e.getArguments()[1];o!==void 0&&Tt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Hn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Pl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))bl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Nl(s,t)},wl=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Ae(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 Pl(n,{scope:x(e),relativePath:t,requestName:o.getText(),rows:a}),a},Il=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...wl(n,t));return s},Cl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Il(i,I(t,n)))}return s},Yn="identity.ts",Tl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Qe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Ol=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&&Qe(n.getModuleSpecifierValue())}return!1},kl=e=>{if(r.isIdentifier(e))return Tl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Ol(t)}return!1},Rl=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!kl(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Ne(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Pn(s,"member");a!==void 0&&t.push({exportName:a})}return t},Fl=(e,t)=>{const s=v(t,Yn);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Rl(n);if(i.length!==0){if(i.length>1)throw Ne(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Dl=new Set(["auth","context.auth"]),Ll="userId",Ml=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(S(s))}return t},_l=(e,t)=>{const s=v(t,Yn);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(P(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Ml(o):void 0}},Ks=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Dl.has(t.getText())||H(t,["auth"])?e:void 0},Kl=e=>{if(r.isPropertyAccessExpression(e)&&Ks(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Ks(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},zs=(e,t,s)=>{const n=Kl(e);return n===void 0?void 0:{declared:n===Ll||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:x(e)}},zl=(e,t)=>{const s=_l(e,t);return s===void 0?[]:[...ne(e,t,d.PropertyAccessExpression,(n,i)=>zs(n,i,s)),...ne(e,t,d.ElementAccessExpression,(n,i)=>zs(n,i,s))]},Bl=(e,t)=>{if(P(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=F(s,"key");if(!(!n||!W(n)||ae(n)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},$l=(e,t)=>C(e,t,Bl),Vl=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ul=(e,t,s=[])=>{const n=Je(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Vl});return $t(n,s)},Wl=new Set(["queue","send"]),Bs=new Set(["bcc","cc","to"]),ql=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Wl.has(t))return;const s=e.getExpression();return H(s,["mail"])||H(s,["email"])?t:void 0},jl=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Bs.has(S(t))&&W(n)&&!ae(n)}if(!r.isPropertyAssignment(t)||!Bs.has(S(t)))return!1;const s=t.getInitializer();return s!==void 0&&W(s)&&!ae(s)}):!1,Hl=(e,t)=>{const s=ql(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!jl(n)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},Gl=(e,t)=>C(e,t,Hl),Yl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=ze(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=ze(l);if(u===void 0)continue;const f=Rn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Ql=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;return n?.receiver?Ut(n.receiver).flatMap(i=>Yl(i,q(e)??e.getName(),t)):[]},Xl=(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 Y(i))s.push(...Ql(a,o))}return s},Jl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Zl=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=B(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},ed=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Rr(s.getExpression())?s:void 0},td=e=>{const t=ed(e),s=t===void 0?void 0:Zl(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?q(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Jl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},sd=e=>e.getVariableDeclarations().flatMap(t=>td(t)),nd=(e,t)=>{const s=v(t,kr);if(!M(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return sd(n)},id=new Set(["delete","get","patch"]),rd=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),od=new Set(["auth","identity","session","user"]),ad=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),cd=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():""},ld=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},dd=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),ud=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,fd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>dd(s.getExpression(),t)&&ud(s.getThenStatement())),gd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!id.has(i))continue;const o=n.getExpression();if(!(_(o)||r.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},pd=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Vt(He(s))!==void 0)),md=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>ad.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),hd=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(rd.has(t.getText()))return!0;return[...od].some(t=>Ye(e,t).length>0)?!0:pd(e)||md(e)},vd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ee(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Wn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Tn(n.receiver,"use","rls"),a=hd(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=cd(u);if(f===void 0)continue;const g=ld(u);if(g===void 0||c.has(g)||!fd(i,g))continue;const m=gd(i,g);m!==void 0&&(c.add(g),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},Ed=(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 Y(i))s.push(...vd(a,o))}return s},Qn=(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},xd=e=>{const t=w(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!Ge(s)},Sd=e=>{const t=w(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Ad=e=>{const s=w(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!Ge(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},$e=e=>{const t=D(e);return t===void 0||gr(t.getSourceFile())},Ot=(e,t)=>{const s=w(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"&&$e(o);if(Qn(He(o),t))return!(r.isPropertyAccessExpression(o)&&In.has(o.getName()))||r.isExpressionStatement(w(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!$e(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}},De={kind:"opaque"},yd={kind:"unreached"},bd=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},kt=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=bd(s);return i===void 0||Bt(i)?void 0:i}const n=ie(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Xn=(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?De:c===void 0?a.some(l=>l.isRestParameter())?De:yd:c.isRestParameter()?De:{kind:"parameter",parameter:c}},Nd=e=>{const t=w(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=kt(s.getExpression());return n===void 0?De:Xn(n,s,t)},Pd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),wd=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Jn=e=>{const t=w(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=wd(s);if(n!==void 0)return A(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},Id=4,Zn=(e,t,s=0)=>{if(fr(e))return!0;if(xd(e)){const i=w(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||!Pd.has(c)}if(Sd(e)||Ad(e)||Jn(e)||Ot(e,t))return!0;const n=Nd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Cd(n.parameter,s+1)},$s=new WeakMap,Cd=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=$s.get(e.compilerNode);if(n!==void 0)return n;if(t>Id)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||Zn(a,void 0,t));return(o||t===0)&&$s.set(e.compilerNode,o),o},Vs=new WeakMap,Td=(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)})},Od=(e,t,s)=>{const{context:n,impl:i}=e,o=Vs.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)?Zn(g,n):!Ge(g),f=!Td(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 E=l.get(m);return E===void 0||c.includes(g)||D(g)?.compilerNode!==E?!0:u(g)});return Vs.set(i.compilerNode,f),f},Us=new WeakMap,kd=e=>{let t=Us.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Fr(s);return n===void 0?[]:[[n.compilerNode,s]]})),Us.set(e.compilerNode,t)),t},Rd=e=>{const t=kd(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:q(n)??n.getName()};return a!==void 0&&Od(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},mt="args",he=e=>{const t=zt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===mt?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=ie(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&oe(i)===mt||r.isIdentifier(o)&&o.getText()===mt?oe(s):void 0},Fd=new Set(["auth","identity","user"]),Rt=e=>{const t=i=>{const o=Vt(i);return o!==void 0&&o.length>0&&Fd.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=G(s);return n!==void 0&&t(n)},ei=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=he(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?G(n):void 0;if(o!==void 0)for(const a of ei(o,t-1))s.add(a)}return s},Le=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[...Le(n),...Le(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=he(h(u)??u);return g===void 0?[]:Le(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=he(h(n)??n),c=he(h(i)??i);return a!==void 0&&Rt(i)&&o.push(a),c!==void 0&&Rt(n)&&o.push(c),o},Dd=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)&&yr(i.getExpression(),"defineIdentityGuard")},Ld=e=>{if(!Dd(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=he(h(s)??s),o=t.some((a,c)=>c!==n&&Rt(a));return i!==void 0&&o?[i]:[]})},Md=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)},_d=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Ws=(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},Kd=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),zd=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&Ws(n,e)&&Md(n.getThenStatement()))for(const i of Le(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&Kd(n)&&Ws(n,e))for(const i of Ld(n))s.add(i);return s},Bd=(e,t)=>{const s=ei(t);if(s.size===0)return!1;const n=e.getFirstAncestor(_d);if(n===void 0)return!1;const i=zd(n,e.getStart());return[...s].every(o=>i.has(o))},$d=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Vd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Ft=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),ti=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Ud=e=>{const t=w(e),s=t.getParent();if(r.isVariableDeclaration(s))return A(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},Wd=e=>{const t=Ud(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ie(t)?[t]:void 0:ti(t)},ve=e=>e.isUnion()?e.getUnionTypes().every(t=>ve(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>ve(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ve=(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)},Me=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]},qd=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)&&Vd.get(s.getText())?.has(t.getName())===!0&&$e(s)},jd=e=>{const t=yt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=w(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ve(n,Cn)?n:void 0},Hd=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=w(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ve(n,$d,t)?n:void 0},Gd=(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},Yd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&A(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},qs=e=>{const t=w(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&qd(s);return Hd(s,t)??Gd(s,t)??Yd(s,t)??(n?s:jd(t))},Qd=5e4,si=()=>({inProgress:new Set,verdicts:new Map});class Xd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Qd&&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 Jd=8,Zd=8;class eu{budget;scope;taint;verdicts=si();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!ve(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)?ti(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Jd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(w(l),!0,a,0))&&(t===n||!ve(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=qs(o);m!==void 0;m=qs(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=w(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&ve(o.getType());if(Ge(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Wd(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=w(t).getParent();if(n>=Zd)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===w(t)?this.valueCompromises(i,!1,s,n+1):!Ve(i,Ft);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ie(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=w(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=>Me(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ve(t,Ft)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=kt(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!Ot(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(Ot(s,this.scope.context))return!1;const i=kt(t.getExpression()),o=i===void 0?void 0:Xn(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)||Jn(t)||A(yt(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=yt(t);return A(s,this.scope.impl)?void 0:s}}const tu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),su=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)},nu=new Set(["all","allSettled","any","race"]),js=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,ht=8;class iu{budget=new Xd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=si();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new eu(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,ht)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>pr(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=w(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)||!Ft.has(g.getName()))return!0;const m=a.getArguments().filter(E=>E!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(E=>this.isTaintedValue(E,!1))}const c=r.isVariableDeclaration(a)&&ie(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=w(g),E=m.getParent();return!r.isCallExpression(E)||E.getExpression()!==m||this.isCallSiteTainted(E,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"&&$e(i)&&nu.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:Me(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=js(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&&In.has(i)?!1:i!==void 0&&Cn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Me(a)!==void 0)&&(i===void 0||!tu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=He(i),c=r.isIdentifier(a)?js(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=Me(i);if(o===void 0)return!su(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=lr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Qn(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=ie(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=Bt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,ht))return!1;if(this.variableDepth>=ht)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Hs=new WeakMap,ru=e=>{const t=Hs.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new iu(e);return Hs.set(e.impl.compilerNode,s),s},ou=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),au=new Set(["insert","insertManyUnsafe","patch","replace"]),cu=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return au.has(t)&&Er(e.getExpression())?t:void 0},lu=(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},du=(e,t)=>{const s=zt(e);return s?.member===t?h(s.object):void 0},Gs=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,ni=(e,t,s,n=1)=>{const i=du(e,s);if(i!==void 0)return Gs(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&&oe(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ie(l)&&Gs(h(l.getInitializer()),t))}const a=ie(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&ni(a,t,s,n-1)},Dt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Dt(t.getWhenTrue()),...Dt(t.getWhenFalse())]:[t]},uu=(e,t,s)=>{const n=[],i=s===void 0?void 0:ru(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=S(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=S(o),c=o.getNameNode()),a===void 0||c===void 0||!ou.has(a))continue;const l=Dt(c).filter(f=>i===void 0?W(f)&&!xr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&ni(c,s.parameter,a),g=l.every(m=>Bd(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},fu=(e,t,s)=>{const n=cu(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=lu(i,n);if(o.length===0)return[];const a=x(e),c=Rd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>uu(u,l,c))},gu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=C(e,t,(c,l)=>fu(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return $t(o,s).map(c=>mr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},pu=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),mu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,hu=e=>{const t=B(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?mu(t.getInitializer()):void 0},vu=(e,t)=>{const s=P(e.getExpression());if(s===void 0||!pu.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?hu(n):void 0;return{callee:s,scope:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Eu=(e,t)=>C(e,t,vu),xu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Su=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Au=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=B(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},ii=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},ri=(e,t)=>e===t||e.startsWith(`${t}.`),oi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},Ys=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=>Ys(s));return r.isIdentifier(e)&&Ys(e)&&t.push(e),t},yu=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},bu=e=>{const t=ii(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},Nu=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:bu(e),i=new Set,o=a=>oi(a).some(c=>n.some(l=>ri(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 yu(a))i.add(l)}return{names:i,prefixes:n}},Pu=(e,t)=>oi(e).some(s=>t.prefixes.some(n=>ri(s.getText(),n)))?!0:ai(e).some(s=>t.names.has(s.getText())),wu=e=>{const t=dr(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Iu=(e,t,s)=>{const n=ii(e,0);if(n===void 0)return[];const i=Nu(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)||!bn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Pu(u,i))continue;const f=wu(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:x(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Cu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=Su(n),o=i===void 0?void 0:xu.get(i);if(o===void 0)continue;const a=Au(n,o);a!==void 0&&s.push(...Iu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Tu=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Cu(i,I(t,n)))}return s},Qs={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Xs=new Set(["account","credential","member","passkey","session","user"]),Ou=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ku=e=>{const s=Ou(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Xs.has(s)||Xs.has(n)},Ru=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Fu=(e,t)=>{const{objects:s,opaque:n}=jt(e,t);return Ua(s).some(i=>Ru(i))?!0:n?void 0:!1},Du=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!B(t,"captcha"),usesRateLimit:!!B(t,"rateLimit")}},Lu=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},_e={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mu=e=>{const t=Lu(e),s=t?P(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Du(t);return{..._e,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Qs?{..._e,[Qs[s]]:!0}:_e},_u=e=>{const t={..._e};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=Mu(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},Ku=new Set(["insert","insertMany","insertManyUnsafe","replace"]),zu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ku.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:ku(i.getLiteralText())},Bu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Js=new Set(["queues","scheduler","topics","workflows"]),$u=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Bu.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&Js.has(s.getName())&&Sr(s.getExpression()))return!0;s=s.getExpression()}const n=Vt(s);return n?.length===1&&Js.has(n[0]??"")},Vu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},ci=new Set(["generateObject","generateText","streamObject","streamText"]),Uu=e=>{const t=P(e.getExpression());return t!==void 0&&ci.has(t)},Wu=e=>{const t=P(e.getExpression());if(t===void 0||!ci.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!B(s,"maxOutputTokens")},qu=new Set(["log","span","trace"]),ju=new Set(["ai"]),Hu=new Set(["email","mail"]),Gu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),vt=(e,t)=>[...t].some(s=>Ye(e,s).length>0),li=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Yu=new Set(["every","filter","flatMap","forEach","map","some"]),Qu=new Set(["all","allSettled","race"]),di=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(Yu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Qu.has(n))return t},Xu=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(li.has(t.getKind())){const s=di(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Ju=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(li.has(t.getKind())){if(t=di(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Zu=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 E=m.getExpression();return r.isIdentifier(E)&&E.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},ef=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}},tf=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}},sf=e=>{let t=!1,s=!0;for(const n of[...Gu].flatMap(i=>Ye(e,i))){const i=tf(n);i&&(t=!0,!Xu(i)&&!ef(i)&&!Zu(i)&&!Ju(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},nf=e=>e.getDescendantsOfKind(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"}),Zs="lunora-advisor-exempt",rf=/^[\s*/]+/u,of=/[\w-]/u,af=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
1
+ import{existsSync as M,mkdirSync as _t,readFileSync as er,writeFileSync as tr,rmSync as Se,readdirSync as En}from"node:fs";import{dirname as Kt,join as v,relative as xn}from"node:path";import{performance as ft}from"node:perf_hooks";import{runAdvisor as sr}from"@lunora/advisor";import{LunoraError as j}from"@lunora/errors";import{serializeSchemaSnapshot as nr}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as ir}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,ts as rr,VariableDeclarationKind as or}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as I,bindingKeyName as oe,collectCallRows as C,findObjectProperty as B,collectSecurityCallRows as ar,propertyInitializer as F,listSecurityScanFiles as je,objectLiteralFromCallbackBody as Sn,limitNameOf as An,optionsObjectLiteral as yn,handlerOf as cr,collectNodeRows as ne,chainRootOf as He,outermostValueWrapper as w,isWriteTarget as Ge,isSameNode as A,unwrapExpression as h,isConstDeclaration as ie,memberAccessOf as zt,returningFunctionOf as yt,walkChain as lr,RUN_METHODS as bn,functionReferenceSegments as dr,isTestPath as ur,isFunctionLike as re,functionKeyOf as Nn}from"./isTestPath-B81lOULB.mjs";import{b as Y,d as q,f as D,g as Bt,c as x,a as Pn,w as $t,k as fr,l as gr,h as pr,m as mr,j as bt,i as hr}from"./attribution-hVBriwzy.mjs";import{a as Ps,r as gt,i as H,b as vr,m as wn,c as Ye,e as Vt,E as In,C as Cn,d as Er,f as xr,g as Sr}from"./context-root-D-pTjHtx.mjs";import{a as P,i as Ar,c as ee,d as Tn,e as yr,f as br}from"./classify-procedure-call-DUBO9bqm.mjs";import{a as S,r as On,s as Nr,b as Pr}from"./project-config-file-BV7RR-l6.mjs";import{a as wr,b as Qe}from"./module-specifiers-WF8iAydP.mjs";import{r as Xe,s as Ir}from"./parse-validator-IDBKIT7M.mjs";import Cr from"./discoverAuthApiCalls-xs0ONfI-.mjs";import{i as _,r as kn}from"./database-calls-DJgmh0Kv.mjs";import Tr from"./discoverHyperdriveCalls-DVIQ0i_e.mjs";import{diagnosticAt as Ne}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Ut,a as ze,s as Rn,d as Or}from"./index-iWQbulvu.mjs";import{MUTATORS_FILENAME as kr,isDefineMutatorCallee as Rr,mutatorServerImplOf as Fr,discoverMutators as Dr}from"./MUTATORS_FILENAME-Jkk8Zgkb.mjs";import Lr from"./discoverNondeterministicCalls-B6FUSWes.mjs";import{discoverNotifyConfig as Mr,discoverNotifyCalls as _r}from"./NOTIFY_FILENAME-DiYZjYts.mjs";import Kr from"./discoverR2sqlCalls-B9Q6xfi6.mjs";import zr from"./discoverRlsProcedures-Os1lrVX_.mjs";import{s as Wt,n as Br}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as $r,redact as Vr,isHeuristicSecretKind as Ur,isSecretishName as Wr}from"./redact-Cy14LEnc.mjs";import{a as Re,d as qr,r as jr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as Hr,discoverWorkflows as Gr}from"./WORKFLOWS_FILENAME-CdeS224T.mjs";import{r as Yr}from"./json-data-Chfs2Cz5.mjs";import{G as Qr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Xr}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as Yv,refreshCodegenProject as Qv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as Jr,usedCapabilities as Zr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Fn,isHyperdriveGlobalTable as Dn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as eo}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as to}from"./CONTAINERS_FILENAME-dFRtAyIe.mjs";import so from"./discoverCrons-DBnCama4.mjs";import{contextPropertiesRead as no,discoverFeatureUsage as io}from"./capabilitiesUsedBy-CF7sUwa8.mjs";import Ln from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as ro,findProjectConfigFile as oo}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{discoverQueueDeclarations as ao}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as co}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as lo}from"./readServiceBindings-DvqIThzd.mjs";import uo from"./discoverStorageRulesMetadata-BTD9Vs5X.mjs";import{resolveCodegenTarget as Nt,gatePlatformFeatures as fo,readTargetDiagnostics as go,vectorizeDimensionDiagnostics as po,liveStreamsDeliveryAuthorizationDiagnostic as mo,socketRoutesDeliveryAuthorizationDiagnostic as ho,studioPlatformFor as vo,platformFeatureAvailable as Eo}from"./DEFAULT_TARGET-BbWiB-rs.mjs";import{i as xo}from"./schema-BgM8A3XV.mjs";import{b as Mn,e as So}from"./shard-BtImwCVL.mjs";import{e as Ao,a as yo}from"./server-DAvi_bv_.mjs";import{emitDataModel as bo}from"./emitDataModel-BskFt9Wv.mjs";import{i as No,a as Po,e as wo,b as Io,d as Co,c as To}from"./unwrap-handler-return-CeaOifqX.mjs";import Oo from"./discoverFunctions-CIJja4zp.mjs";import ko from"./discoverHttpRoutes-WBAqBcfK.mjs";import Ro from"./discoverInserts-CednbRCq.mjs";import{e as _n}from"./exported-procedure-chains-DOFtzPZn.mjs";import Fo from"./discoverMigrations-C9mLIhGZ.mjs";import Do from"./discoverQueries-BezURxvr.mjs";import Lo from"./discoverRlsMetadata-DCgP2H39.mjs";import Mo from"./discoverSchema-BtsX-CN9.mjs";import{discoverShapes as _o}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as Ko}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as zo}from"./emitApp-DuJW6LKD.mjs";import{readJsonSync as Bo}from"@visulima/fs";import{buildSchemaSnapshot as $o}from"./SchemaSnapshotParseError-BRJT7c2k.mjs";import{buildOpenApiDocument as Vo,emitOpenApiModule as Uo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as Wo,emitOpenRpcModule as qo}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as jo,t as Ho,u as Go,s as Yo,w as Qo}from"./shard-runtime-BpoCV-aM.mjs";import{emitCollections as Xo,emitSeed as Jo,emitApi as Zo,emitInternalApi as ea}from"./emitApi-CDgIPAG2.mjs";import{emitCrons as ta,emitScheduler as sa,emitShardRegistry as na,emitDurableObjects as ia,emitVectors as ra,emitWranglerCronTriggers as oa}from"./emitCrons-BQW2lviZ.mjs";import aa from"./emitDrizzleSchema-DitcRZ1a.mjs";import{LAZY_FUNCTION_DIRECTORY as Kn,emitFunctions as ca,emitLazyFunctionModules as la}from"./emitFunctions-Cd0Tuw73.mjs";const zn=new Set(["delete","get","head","options","patch","post","put"]),da=new Set(["handler","stream"]),ua=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ws=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),fa=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()}},ga=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 fa(s)},pa=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(ws.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&ws.has(s.getText()))return!0}return!1},ma=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!da.has(n.getName()))return;const i=ga(s);if(!i||!ua.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&pa(o);return{exportName:q(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},ha=(e,t)=>{const s=[];for(const n of Y(e)){const i=ma(n,t);i&&s.push(i)}return s},va=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ha(i,I(t,n)))}return s},Ea=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}},xa=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)?oe(t):void 0}},Sa=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))&&Ps(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))&&Ps(i)},Is=(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=Ea(e);return n!==void 0&&xa(n)===t?!0:t==="args"&&Sa(e)},Bn=(e,t)=>r.isIdentifier(e)?Is(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Is(s,t)),Aa=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},Cs=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Bt(t)?t.getInitializer():void 0},Pt=e=>Bn(e,"args"),G=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 s.getDescendantsOfKind(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},W=e=>{if(Pt(e))return!0;const t=G(e);return t!==void 0&&Pt(t)},ya=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=G(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},ae=e=>{if(gt(e))return!0;const t=Cs(e);if(t!==void 0&&gt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=Cs(i);return o!==void 0&&gt(o)})},Fe=(e,t)=>Bn(e,t),ba=(e,t)=>{if(Fe(e,t))return!0;const s=G(e);if(s!==void 0&&Fe(s,t))return!0;const n=Aa(e);if(n!==void 0){const i=G(n);return i!==void 0&&Fe(i,t)}return!1},Na=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:H(e.getExpression(),["ai"]),Pa=(e,t)=>{if(!Na(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)||ae(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},wa=(e,t)=>C(e,t,Pa),Ia=new Set(["generateText","streamText"]),Ca=new Set(["messages","prompt","system"]),Ta=[{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"]}],Oa=(e,t)=>Ta.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ka=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[vr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Oa(i,s));return n===void 0?void 0:`${n}.${s}`},Ra=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ka(t);if(s!==void 0)return s}},Fa=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=oe(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Da=e=>{if(Pt(e))return!0;const t=Fa(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},La=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!Ca.has(S(t)))continue;const s=t.getInitializer();if(s!==void 0&&Da(s))return!0}return!1},Ma=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=P(n.getExpression());if(i===void 0||!Ia.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(P(c.getExpression())==="tool"&&(a=Ra(c),a!==void 0))break;a!==void 0&&s.push({scope:x(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:La(o)})}return s},_a=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ma(i,I(t,n)))}return s},Ka=e=>H(e,["fetch"]),za=(e,t)=>{if(!Ka(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!W(s)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},Ba=(e,t)=>C(e,t,za),qt=(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=Xe(s.getExpression());return n===void 0||qt(n,t)})}finally{t.delete(e)}},$a=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=B(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:Xe(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:qt(i)}},Va=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)?Xe(o):void 0;a===void 0?s=!0:(t.push(a),s||=qt(a))}n=i.getExpression()}return{objects:t,opaque:s}},jt=(e,t)=>t?Va(t):$a(e),$n=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=Xe(s.getExpression());return n===void 0?[]:$n(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[S(s)]:[]})}finally{t.delete(e)}},Ua=e=>e.flatMap(t=>$n(t,new Set)),Wa=new Set(["check","length","max"]),wt=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(Wa.has(s.getName()))return!0;t=n}},It=e=>wr(e)||e==="@lunora/values",qa=e=>{const t=new Set(["v"]);for(const s of Ar(e,"v",It))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&It(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},ja=(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},Ha=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Ga=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&It(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Ht=(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 Ha(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Ga(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Ya=(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)},Qa=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Xa=e=>r.isReturnStatement(e)?e.getExpression():void 0,Ja=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Qa(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Xa(t);return s?[s]:[]}),Vn=(e,t)=>{if(Ht(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Vn(e.getExpression(),t)},Za=(e,t)=>{const s=Ya(e.getExpression(),e.getSourceFile());if(!s)return[];const n=wt(e),i=new Set(Ja(s).map(o=>Vn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Ht(o,t);return a===void 0?[]:[{bounded:wt(o)||n&&i.has(o),factory:a}]})},ec=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Ht(s,t),i=n===void 0?[]:[{bounded:wt(s),factory:n}];return r.isCallExpression(s)?[...i,...Za(s,t)]:i}),tc=(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=ec(a,t),l=S(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}},sc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ee(n);if(i?.visibility!=="public")return;const{objects:o}=jt(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=tc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:q(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},nc=(e,t)=>{const s=[],n=qa(e),i={destructured:ja(e,n),namespaces:n};for(const o of Y(e)){const a=sc(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(...nc(i,I(t,n)))}return s},pt=e=>e?.getKind()===d.TrueKeyword,rc=e=>e?.getKind()===d.FalseKeyword,oc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,ac=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),cc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&P(t.getExpression())==="scim"),lc=e=>e!==void 0&&r.isCallExpression(e)&&ac.has(P(e.getExpression())??""),dc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),uc=e=>{const t=F(e,"advanced"),s=F(e,"emailAndPassword"),n=F(e,"session");return{analyzable:!0,disableCsrfCheck:pt(F(t,"disableCSRFCheck")),emailPasswordEnabled:pt(F(s,"enabled")),requireEmailVerification:pt(F(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:cc(F(e,"plugins"))&&lc(F(e,"database")),secureCookiesDisabled:rc(F(t,"useSecureCookies")),sessionFreshAgeZero:oc(F(n,"freshAge")),trustedOriginsWildcard:dc(F(e,"trustedOrigins"))}},fc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),gc=(e,t)=>{if(P(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?uc(s):fc();return{scope:x(e),file:t,line:e.getStartLineNumber(),...i}},pc=(e,t)=>ar(e,t,gc),mc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return wn(e.getExpression(),t.matchReceiver)?s:void 0},hc=(e,t,s)=>{const n=mc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!W(i)||ae(i))&&!(s.requireUnmodifiedReach===!0&&!ya(i)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:n}},Je=(e,t,s)=>C(e,t,(n,i)=>hc(n,i,s)),vc=new Set(["content","pdf","scrape","screenshot"]),Ec=(e,t)=>Je(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:vc}),xc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Sc=new Set(["RateLimiter"]),Ac=new Set(["extend"]),Ts="lunora",yc=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Un=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=S(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Ct=e=>e&&r.isObjectLiteralExpression(e)?Un(e):{analyzable:!1,presentKeys:[],trueKeys:[]},bc=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Sn(t.getBody());return s?Un(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Nc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=P(n.getExpression());i!==void 0&&(xc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Ct(n.getArguments()[0])}):Ac.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...bc(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=P(n.getExpression());i===void 0||!Sc.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Ct(n.getArguments()[0])})}return s},Pc=(e,t)=>{for(const s of yc){const n=v(t,s);if(!M(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))P(a.getExpression())===Ts&&o.push({callee:Ts,file:s,line:a.getStartLineNumber(),...Ct(a.getArguments()[0])});return o}return[]},wc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of je(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Nc(o,n))}return s.push(...Pc(e,Kt(t))),s},Os="ctx.containers.",Ic=e=>{if(!e.startsWith(Os))return!1;const t=e.slice(Os.length);return t.length>0&&!t.includes(".")},Cc=(e,t)=>Je(e,t,{argIndex:0,matchReceiver:Ic,methods:new Set(["get"])}),Tc=new Set(["allow","deny","setAllowed"]),Oc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=B(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},kc=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Oc(e)))return{detail:"enableInternet: true",scope:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Rc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Tc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Fc=(e,t)=>kc(e,t)??Rc(e,t),Dc=(e,t)=>C(e,t,Fc),Lc=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},Mc=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&_(s)?1:0]},_c=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Kc=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=>_c.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},zc=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return C(e,t,(i,o)=>{const a=Lc(i);if(a===void 0)return;const c=Kc(Mc(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:x(i),table:a}})},Bc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),$c=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Bc.has(s)?s:void 0},Vc=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=S(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(S(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Uc=(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 o.getDescendantsOfKind(d.CallExpression)){const c=$c(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Vc(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},Wc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),qc=new Set(["dbRateLimit","rateLimit"]),jc=e=>{const t=yn(e);if(!t)return!1;const s=B(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Hc=(e,t)=>{const s=P(e.getExpression());if(s===void 0)return;const n=Wc.get(s);if(n!==void 0)return{callee:s,scope:x(e),failOpen:jc(e.getArguments()[n]),file:t,limitName:qc.has(s)?An(e):"",line:e.getStartLineNumber()}},Gc=(e,t)=>C(e,t,Hc),Yc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ee(t);if(s?.kind!=="query")return;const n=cr(t,s.receiver);return n?{exportName:q(e)??e.getName(),handler:n}:void 0},ks=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Qc=e=>{const t=ks(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=ks(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Xc=(e,t)=>{const s=[];for(const n of Ye(e.handler,"flags"))s.push({callee:Qc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Jc=(e,t)=>{const s=[];for(const n of Y(e)){const i=Yc(n);i&&s.push(...Xc(i,t))}return s},Zc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Jc(i,I(t,n)))}return s},el=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:H(e.getExpression(),["flags"]),tl=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},sl=(e,t)=>{if(!el(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=tl(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:x(e),file:t,key:i,line:e.getStartLineNumber()}},nl=(e,t)=>C(e,t,sl),il=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},rl=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},ol=(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 i.getDescendantsOfKind(d.CallExpression))il(a)&&s.push({file:o,indexName:rl(a),line:a.getStartLineNumber()})}return s},Ae=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,Wn=e=>{const t=e.getArguments()[0],s=Ae(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=B(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?Ae(n.getInitializer()):void 0},al=new Set(["delete","get","head","options","patch","post","put"]),cl=new Set(["handler","stream"]),ll=new Set(["runAction","runMutation"]),dl=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),ye=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,qn=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(oe(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Rs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:qn(s,"ctx")},Fs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:qn(s,"request")},Ds=(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(ll.has(a)&&ye(c,t))return a;if(dl.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&ye(c.getExpression(),t))return`db.${a}`}},Ls=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&ye(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!ye(n.getInitializer(),t))){for(const o of i.getElements())if(oe(o)==="auth")return!0}}return!1},ul=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,fl=(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"&&ye(n.getExpression(),t)},gl=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],jn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:gl(s)},pl=(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)?jn(t,a.getText()):[]}return[]},ml=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=jn(s,t.getText());return n.length>0?n:pl(t,s)},Ms=(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=>fl(i,t)&&ml(i).some(o=>ul.test(o)))},hl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!cl.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(al.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},vl=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ae(e.getArguments()[0]),l=c&&Rs(c,!0);if(!c||l===void 0||Ms(c,Fs(c,!0)))return;const u=Ds(c,l);return u===void 0?void 0:{scope:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Ls(c,l),sideEffect:u}}const n=hl(e);if(n===void 0)return;const i=Ae(e.getArguments()[0]),o=i&&Rs(i,!1);if(!i||o===void 0||Ms(i,Fs(i,!1)))return;const a=Ds(i,o);return a===void 0?void 0:{scope:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Ls(i,o),sideEffect:a}},El=(e,t)=>C(e,t,vl),xl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Sl=new Set(["append","set"]),Hn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",_s=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>xl.has(P(n.getExpression())??"")&&Fe(n,t)),Al=(e,t)=>{if(_s(e,t))return!0;const s=G(e);return s!==void 0&&_s(s,t)},Tt=(e,t)=>ba(e,t)&&!Al(e,t),yl=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=G(e);return t!==void 0&&r.isNewExpression(t)&&P(t.getExpression())==="Headers"},Be=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=G(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Gt=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Tt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Hn(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Tt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:S(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=Be(n.getExpression());i!==void 0&&Gt(i,t,s)}},Gn=(e,t)=>{const s=Be(e);if(s===void 0)return;const n=B(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=Be(n.getInitializer());i!==void 0&&Gt(i,"response-init",t)},bl=(e,t)=>{const s=P(e.getExpression());if(s==="Response")Gn(e.getArguments()[1],t);else if(s==="Headers"){const n=Be(e.getArguments()[0]);n!==void 0&&Gt(n,"headers-ctor",t)}},Nl=(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"){Gn(e.getArguments()[1],t);return}if(Sl.has(n)&&yl(i)){const o=e.getArguments()[1];o!==void 0&&Tt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Hn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Pl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))bl(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Nl(s,t)},wl=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Ae(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 Pl(n,{scope:x(e),relativePath:t,requestName:o.getText(),rows:a}),a},Il=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...wl(n,t));return s},Cl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Il(i,I(t,n)))}return s},Yn="identity.ts",Tl=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Qe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Ol=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&&Qe(n.getModuleSpecifierValue())}return!1},kl=e=>{if(r.isIdentifier(e))return Tl(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Ol(t)}return!1},Rl=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!kl(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Ne(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Pn(s,"member");a!==void 0&&t.push({exportName:a})}return t},Fl=(e,t)=>{const s=v(t,Yn);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Rl(n);if(i.length!==0){if(i.length>1)throw Ne(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Dl=new Set(["auth","context.auth"]),Ll="userId",Ml=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(S(s))}return t},_l=(e,t)=>{const s=v(t,Yn);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(P(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Ml(o):void 0}},Ks=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Dl.has(t.getText())||H(t,["auth"])?e:void 0},Kl=e=>{if(r.isPropertyAccessExpression(e)&&Ks(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Ks(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},zs=(e,t,s)=>{const n=Kl(e);return n===void 0?void 0:{declared:n===Ll||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:x(e)}},zl=(e,t)=>{const s=_l(e,t);return s===void 0?[]:[...ne(e,t,d.PropertyAccessExpression,(n,i)=>zs(n,i,s)),...ne(e,t,d.ElementAccessExpression,(n,i)=>zs(n,i,s))]},Bl=(e,t)=>{if(P(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=F(s,"key");if(!(!n||!W(n)||ae(n)))return{scope:x(e),file:t,line:e.getStartLineNumber()}},$l=(e,t)=>C(e,t,Bl),Vl=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ul=(e,t,s=[])=>{const n=Je(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Vl});return $t(n,s)},Wl=new Set(["queue","send"]),Bs=new Set(["bcc","cc","to"]),ql=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Wl.has(t))return;const s=e.getExpression();return H(s,["mail"])||H(s,["email"])?t:void 0},jl=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Bs.has(S(t))&&W(n)&&!ae(n)}if(!r.isPropertyAssignment(t)||!Bs.has(S(t)))return!1;const s=t.getInitializer();return s!==void 0&&W(s)&&!ae(s)}):!1,Hl=(e,t)=>{const s=ql(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!jl(n)))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},Gl=(e,t)=>C(e,t,Hl),Yl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=ze(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=ze(l);if(u===void 0)continue;const f=Rn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Ql=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;return n?.receiver?Ut(n.receiver).flatMap(i=>Yl(i,q(e)??e.getName(),t)):[]},Xl=(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 Y(i))s.push(...Ql(a,o))}return s},Jl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Zl=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=B(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},ed=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return Rr(s.getExpression())?s:void 0},td=e=>{const t=ed(e),s=t===void 0?void 0:Zl(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?q(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Jl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},sd=e=>e.getVariableDeclarations().flatMap(t=>td(t)),nd=(e,t)=>{const s=v(t,kr);if(!M(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return sd(n)},id=new Set(["delete","get","patch"]),rd=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),od=new Set(["auth","identity","session","user"]),ad=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),cd=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():""},ld=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},dd=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),ud=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,fd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>dd(s.getExpression(),t)&&ud(s.getThenStatement())),gd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!id.has(i))continue;const o=n.getExpression();if(!(_(o)||r.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},pd=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Vt(He(s))!==void 0)),md=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>ad.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),hd=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(rd.has(t.getText()))return!0;return[...od].some(t=>Ye(e,t).length>0)?!0:pd(e)||md(e)},vd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ee(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Wn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Tn(n.receiver,"use","rls"),a=hd(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=cd(u);if(f===void 0)continue;const g=ld(u);if(g===void 0||c.has(g)||!fd(i,g))continue;const m=gd(i,g);m!==void 0&&(c.add(g),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},Ed=(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 Y(i))s.push(...vd(a,o))}return s},Qn=(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},xd=e=>{const t=w(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!Ge(s)},Sd=e=>{const t=w(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Ad=e=>{const s=w(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!Ge(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},$e=e=>{const t=D(e);return t===void 0||gr(t.getSourceFile())},Ot=(e,t)=>{const s=w(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"&&$e(o);if(Qn(He(o),t))return!(r.isPropertyAccessExpression(o)&&In.has(o.getName()))||r.isExpressionStatement(w(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!$e(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}},De={kind:"opaque"},yd={kind:"unreached"},bd=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},kt=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=bd(s);return i===void 0||Bt(i)?void 0:i}const n=ie(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Xn=(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?De:c===void 0?a.some(l=>l.isRestParameter())?De:yd:c.isRestParameter()?De:{kind:"parameter",parameter:c}},Nd=e=>{const t=w(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=kt(s.getExpression());return n===void 0?De:Xn(n,s,t)},Pd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),wd=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Jn=e=>{const t=w(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=wd(s);if(n!==void 0)return A(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},Id=4,Zn=(e,t,s=0)=>{if(fr(e))return!0;if(xd(e)){const i=w(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||!Pd.has(c)}if(Sd(e)||Ad(e)||Jn(e)||Ot(e,t))return!0;const n=Nd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Cd(n.parameter,s+1)},$s=new WeakMap,Cd=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=$s.get(e.compilerNode);if(n!==void 0)return n;if(t>Id)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||Zn(a,void 0,t));return(o||t===0)&&$s.set(e.compilerNode,o),o},Vs=new WeakMap,Td=(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)})},Od=(e,t,s)=>{const{context:n,impl:i}=e,o=Vs.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)?Zn(g,n):!Ge(g),f=!Td(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 E=l.get(m);return E===void 0||c.includes(g)||D(g)?.compilerNode!==E?!0:u(g)});return Vs.set(i.compilerNode,f),f},Us=new WeakMap,kd=e=>{let t=Us.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=Fr(s);return n===void 0?[]:[[n.compilerNode,s]]})),Us.set(e.compilerNode,t)),t},Rd=e=>{const t=kd(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:q(n)??n.getName()};return a!==void 0&&Od(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},mt="args",he=e=>{const t=zt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===mt?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=ie(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&oe(i)===mt||r.isIdentifier(o)&&o.getText()===mt?oe(s):void 0},Fd=new Set(["auth","identity","user"]),Rt=e=>{const t=i=>{const o=Vt(i);return o!==void 0&&o.length>0&&Fd.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=G(s);return n!==void 0&&t(n)},ei=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=he(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?G(n):void 0;if(o!==void 0)for(const a of ei(o,t-1))s.add(a)}return s},Le=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[...Le(n),...Le(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=he(h(u)??u);return g===void 0?[]:Le(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=he(h(n)??n),c=he(h(i)??i);return a!==void 0&&Rt(i)&&o.push(a),c!==void 0&&Rt(n)&&o.push(c),o},Dd=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)&&yr(i.getExpression(),"defineIdentityGuard")},Ld=e=>{if(!Dd(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=he(h(s)??s),o=t.some((a,c)=>c!==n&&Rt(a));return i!==void 0&&o?[i]:[]})},Md=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)},_d=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Ws=(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},Kd=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),zd=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&Ws(n,e)&&Md(n.getThenStatement()))for(const i of Le(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&Kd(n)&&Ws(n,e))for(const i of Ld(n))s.add(i);return s},Bd=(e,t)=>{const s=ei(t);if(s.size===0)return!1;const n=e.getFirstAncestor(_d);if(n===void 0)return!1;const i=zd(n,e.getStart());return[...s].every(o=>i.has(o))},$d=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Vd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Ft=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),ti=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Ud=e=>{const t=w(e),s=t.getParent();if(r.isVariableDeclaration(s))return A(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},Wd=e=>{const t=Ud(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ie(t)?[t]:void 0:ti(t)},ve=e=>e.isUnion()?e.getUnionTypes().every(t=>ve(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>ve(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ve=(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)},Me=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]},qd=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)&&Vd.get(s.getText())?.has(t.getName())===!0&&$e(s)},jd=e=>{const t=yt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=w(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ve(n,Cn)?n:void 0},Hd=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=w(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ve(n,$d,t)?n:void 0},Gd=(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},Yd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&A(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},qs=e=>{const t=w(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&qd(s);return Hd(s,t)??Gd(s,t)??Yd(s,t)??(n?s:jd(t))},Qd=5e4,si=()=>({inProgress:new Set,verdicts:new Map});class Xd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Qd&&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 Jd=8,Zd=8;class eu{budget;scope;taint;verdicts=si();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!ve(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)?ti(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Jd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(w(l),!0,a,0))&&(t===n||!ve(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=qs(o);m!==void 0;m=qs(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=w(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&ve(o.getType());if(Ge(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Wd(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=w(t).getParent();if(n>=Zd)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===w(t)?this.valueCompromises(i,!1,s,n+1):!Ve(i,Ft);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ie(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=w(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=>Me(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ve(t,Ft)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=kt(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!Ot(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(Ot(s,this.scope.context))return!1;const i=kt(t.getExpression()),o=i===void 0?void 0:Xn(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)||Jn(t)||A(yt(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=yt(t);return A(s,this.scope.impl)?void 0:s}}const tu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),su=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)},nu=new Set(["all","allSettled","any","race"]),js=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,ht=8;class iu{budget=new Xd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=si();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new eu(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,ht)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>pr(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=w(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)||!Ft.has(g.getName()))return!0;const m=a.getArguments().filter(E=>E!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(E=>this.isTaintedValue(E,!1))}const c=r.isVariableDeclaration(a)&&ie(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=w(g),E=m.getParent();return!r.isCallExpression(E)||E.getExpression()!==m||this.isCallSiteTainted(E,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"&&$e(i)&&nu.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:Me(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=js(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&&In.has(i)?!1:i!==void 0&&Cn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Me(a)!==void 0)&&(i===void 0||!tu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=He(i),c=r.isIdentifier(a)?js(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=Me(i);if(o===void 0)return!su(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=lr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Qn(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=ie(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=Bt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,ht))return!1;if(this.variableDepth>=ht)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Hs=new WeakMap,ru=e=>{const t=Hs.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new iu(e);return Hs.set(e.impl.compilerNode,s),s},ou=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),au=new Set(["insert","insertManyUnsafe","patch","replace"]),cu=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return au.has(t)&&Er(e.getExpression())?t:void 0},lu=(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},du=(e,t)=>{const s=zt(e);return s?.member===t?h(s.object):void 0},Gs=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,ni=(e,t,s,n=1)=>{const i=du(e,s);if(i!==void 0)return Gs(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&&oe(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ie(l)&&Gs(h(l.getInitializer()),t))}const a=ie(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&ni(a,t,s,n-1)},Dt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Dt(t.getWhenTrue()),...Dt(t.getWhenFalse())]:[t]},uu=(e,t,s)=>{const n=[],i=s===void 0?void 0:ru(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=S(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=S(o),c=o.getNameNode()),a===void 0||c===void 0||!ou.has(a))continue;const l=Dt(c).filter(f=>i===void 0?W(f)&&!xr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&ni(c,s.parameter,a),g=l.every(m=>Bd(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},fu=(e,t,s)=>{const n=cu(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=lu(i,n);if(o.length===0)return[];const a=x(e),c=Rd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>uu(u,l,c))},gu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=C(e,t,(c,l)=>fu(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return $t(o,s).map(c=>mr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},pu=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),mu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,hu=e=>{const t=B(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?mu(t.getInitializer()):void 0},vu=(e,t)=>{const s=P(e.getExpression());if(s===void 0||!pu.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?hu(n):void 0;return{callee:s,scope:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Eu=(e,t)=>C(e,t,vu),xu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Su=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Au=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=B(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},ii=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},ri=(e,t)=>e===t||e.startsWith(`${t}.`),oi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},Ys=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=>Ys(s));return r.isIdentifier(e)&&Ys(e)&&t.push(e),t},yu=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},bu=e=>{const t=ii(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},Nu=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:bu(e),i=new Set,o=a=>oi(a).some(c=>n.some(l=>ri(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 yu(a))i.add(l)}return{names:i,prefixes:n}},Pu=(e,t)=>oi(e).some(s=>t.prefixes.some(n=>ri(s.getText(),n)))?!0:ai(e).some(s=>t.names.has(s.getText())),wu=e=>{const t=dr(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Iu=(e,t,s)=>{const n=ii(e,0);if(n===void 0)return[];const i=Nu(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)||!bn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Pu(u,i))continue;const f=wu(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:x(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Cu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=Su(n),o=i===void 0?void 0:xu.get(i);if(o===void 0)continue;const a=Au(n,o);a!==void 0&&s.push(...Iu(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Tu=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Cu(i,I(t,n)))}return s},Qs={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Xs=new Set(["account","credential","member","passkey","session","user"]),Ou=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ku=e=>{const s=Ou(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Xs.has(s)||Xs.has(n)},Ru=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Fu=(e,t)=>{const{objects:s,opaque:n}=jt(e,t);return Ua(s).some(i=>Ru(i))?!0:n?void 0:!1},Du=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!B(t,"captcha"),usesRateLimit:!!B(t,"rateLimit")}},Lu=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},_e={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mu=e=>{const t=Lu(e),s=t?P(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Du(t);return{..._e,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Qs?{..._e,[Qs[s]]:!0}:_e},_u=e=>{const t={..._e};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=Mu(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},Ku=new Set(["insert","insertMany","insertManyUnsafe","replace"]),zu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ku.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:ku(i.getLiteralText())},Bu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Js=new Set(["queues","scheduler","topics","workflows"]),$u=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Bu.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&Js.has(s.getName())&&Sr(s.getExpression()))return!0;s=s.getExpression()}const n=Vt(s);return n?.length===1&&Js.has(n[0]??"")},Vu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},ci=new Set(["generateObject","generateText","streamObject","streamText"]),Uu=e=>{const t=P(e.getExpression());return t!==void 0&&ci.has(t)},Wu=e=>{const t=P(e.getExpression());if(t===void 0||!ci.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!B(s,"maxOutputTokens")},qu=new Set(["log","span","trace"]),ju=new Set(["ai"]),Hu=new Set(["email","mail"]),Gu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),vt=(e,t)=>[...t].some(s=>Ye(e,s).length>0),li=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Yu=new Set(["every","filter","flatMap","forEach","map","some"]),Qu=new Set(["all","allSettled","race"]),di=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(Yu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Qu.has(n))return t},Xu=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(li.has(t.getKind())){const s=di(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Ju=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(li.has(t.getKind())){if(t=di(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Zu=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 E=m.getExpression();return r.isIdentifier(E)&&E.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},ef=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}},tf=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}},sf=e=>{let t=!1,s=!0;for(const n of[...Gu].flatMap(i=>Ye(e,i))){const i=tf(n);i&&(t=!0,!Xu(i)&&!ef(i)&&!Zu(i)&&!Ju(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},nf=e=>e.getDescendantsOfKind(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"}),Zs="lunora-advisor-exempt",rf=/^[\s*/]+/u,of=/[\w-]/u,af=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
2
2
  `);for(const n of s.split(`
3
3
  `)){const i=n.replace(rf,"");if(!i.startsWith(Zs))continue;const o=i.slice(Zs.length);if(of.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:""}},cf=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=B(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},lf=(e,t)=>{const s=cf(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)},df=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(zu(l)&&(o=!0),$u(l)&&(t=!0),Vu(l)&&(i=!0),Uu(l)&&(s=!0),Wu(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=sf(e);return{callsMail:vt(e,Hu),emitsEvent:vt(e,qu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||vt(e,ju),throwsBareError:nf(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},uf=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ee(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?_u(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=lf(e,s);return{...o?df(o):{},...af(e),...i,analyzableBody:o!==void 0,exportName:q(e)??e.getName(),file:t,hasEmailArg:Fu(s,n.receiver),kind:n.kind,visibility:n.visibility}},ff=(e,t)=>{const s=[];for(const n of Y(e)){const i=uf(n,t);i&&s.push(i)}return s},gf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ff(i,I(t,n)))}return s},pf=new Set(["dbRateLimit","rateLimit"]),mf=e=>r.isArrowFunction(e)?e.getBody():e,hf=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},ui=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},fi=(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)})},vf=(e,t)=>W(e)||t!==void 0&&fi(e,t).some(s=>ui(s)),Ef=(e,t)=>t===void 0?ae(e):fi(e,t).some(s=>!ui(s)),xf=(e,t)=>{const s=P(e.getExpression());if(s===void 0||!pf.has(s))return;const n=F(yn(e.getArguments()[2]),"key");if(!n)return;const i=mf(n),o=hf(n);if(!(!vf(i,o)||Ef(i,o)))return{callee:s,scope:x(e),file:t,limitName:An(e),line:e.getStartLineNumber()}},Sf=(e,t)=>C(e,t,xf),Af=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),yf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Af.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()},bf=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()}},Nf=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},gi=(e,t=!1)=>{const s=Nf(e);if(r.isIdentifier(s)){if(t)return;const n=G(s);return n===void 0?void 0:gi(n,!0)}if(r.isCallExpression(s))return yf(s)??bf(s)},Pf=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(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},wf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ee(s);if(n?.kind!=="query")return[];const i=Wn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&br(n.receiver,"output"),a=n.receiver!==void 0&&Tn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Pf(i)){const f=gi(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:q(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},If=(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 Y(i))s.push(...wf(a,o))}return s},Cf=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(S(s));return t},Tf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=kn(o);if(a===void 0)continue;const c=Cf(F(a.options,"with"));c.length!==0&&i.push({exportName:q(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Of=(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 Y(i))s.push(...Tf(a,o))}return s},U=(e,t)=>`${e}:${t}`,en=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},kf=(e,t)=>[...ne(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?en(s,n,s.getName(),s.isExported()):void 0),...ne(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?en(i,n,s.getName(),i.isExported()):void 0})],Rf=(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(U(c,a))},Ff=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Df=(e,t)=>{const s=new Map(e.map(n=>[U(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(U(i.file,i.name))?.set(Ff(n),{fields:n.fields,method:n.method,table:n.table})}return s},Lf=(e,t,s)=>e.node.getDescendantsOfKind(d.CallExpression).map(n=>Rf(n,t,s)).filter(n=>n!==void 0),Mf=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(U(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(U(o.file,o.name))?.push(a)}},_f=(e,t,s)=>{const n=new Map(e.map(a=>[U(a.file,a.name),a])),i=new Map(e.map(a=>[`${Wt(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[U(a.file,a.name),Lf(a,n,t)]));return Mf(s,n,i,o),o},Kf=(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},zf=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(U(i.file,i.name))??[])Kf(t.get(U(i.file,i.name)),t.get(U(o.file,o.name)))&&(n=!0)}},Bf=(e,t,s,n)=>{const i=kf(e,t),o=Df(i,s);return zf(i,o,_f(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(U(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ue=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ue(e.getLeft()),s=Ue(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},$f=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&&Ue(t)!==void 0},Vf=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return S(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Uf=(e,t,s)=>Ur(e)?!ur(s)&&Wr(Vf(t)):!0,Wf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if($f(o))continue;const a=Ue(o);if(a===void 0)continue;const c=$r(a);if(c===void 0||!Uf(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:Vr(a)}))}return s},qf=(e,t)=>{const s=[];for(const n of y(t,{includeSkipped:!0})){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Wf(i,I(t,n)))}return s},jf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ee(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=kn(o);if(a===void 0)continue;const c=F(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&W(c);!l&&!u||i.push({exportName:q(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Hf=(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 Y(i))s.push(...jf(a,o))}return s},Gf=new Set(["query","unsafe"]),Yf=e=>!r.isPropertyAccessExpression(e)||!Gf.has(e.getName())?!1:H(e.getExpression(),["sql"]),Qf=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Xf=(e,t)=>{if(!Yf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Qf(s)))return{file:t,line:s.getStartLineNumber(),scope:x(e)}},Jf=(e,t)=>C(e,t,Xf),Zf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],eg=e=>{for(const[t,s]of Zf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},tg=(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=eg(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},sg=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ng=(e,t,s=[])=>{const n=Je(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:sg,requireUnmodifiedReach:!0});return $t(n,s)},ig=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),rg=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,og=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=S(i);t.push(o),o==="expiresInSeconds"&&(s=rg(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(S(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},ag=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=ig.get(t);return s===void 0?void 0:wn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},cg=(e,t)=>{const s=ag(e.getExpression());if(s!==void 0)return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...og(e.getArguments()[s.optionsIndex])}},lg=(e,t)=>C(e,t,cg),dg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),pi=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:dg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>re(i)||s(i));if(!(n===void 0||re(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},Yt=(e,t)=>A(e.getFirstAncestor(s=>A(s,t)||re(s)),t),ug=(e,t)=>A(e,t)||e.getFirstAncestor(s=>A(s,t))!==void 0,mi=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return A(e,t)||Yt(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=pi(e);return s!==void 0&&!ug(s,t)}return!1},hi=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)],fg=e=>hi(e).some(t=>mi(t,e)),gg=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},pg=e=>hi(e).some(t=>mi(t,e)||r.isBreakStatement(t)&&A(pi(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>gg(t)&&Yt(t,e)),mg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>Yt(t,e)),hg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),vg=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Et=(e,t)=>{const s=hg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||pg(e)||mg(e))return;const i=x(e);if(!(i.kind==="module"&&e.getFirstAncestor(re)!==void 0))return{file:t,kind:vg(e),line:e.getStartLineNumber(),scope:i}},Eg=(e,t)=>[...ne(e,t,d.WhileStatement,Et),...ne(e,t,d.ForStatement,Et),...ne(e,t,d.DoStatement,Et)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),xg=new Set(["when","where"]),xt=new Set(["definePolicy","defineShape"]),Sg=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return xt.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 xt.has(i)?i:void 0}const s=t.getText();return xt.has(s)?s:void 0},Ag=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,vi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Ag(e))return"empty-object";if(r.isParenthesizedExpression(e))return vi(e.getExpression())}},Qt=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),yg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Qt(t)===e),Ei=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>Qt(t)===e),bg=e=>{const t=yg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Ei(e).length>0},Ng=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>Qt(t)===e),Lt=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()==="",Pg=(e,t)=>Lt(e)||Lt(t),wg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),tn=e=>!Lt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Ig=(e,t,s)=>{const n=wg.get(e);if(n!==void 0)return Pg(t,s)?n==="positive"?"negative":"positive":tn(t)||tn(s)?void 0:n},Ee=e=>{if(r.isParenthesizedExpression(e))return Ee(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Ig(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=Ee(e.getLeft()),i=Ee(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},sn=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}}},Cg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Tg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Og=e=>{const t=[];for(const s of Ei(e)){const n=Ee(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Ng(e)){const n=Ee(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?sn(s.getThenStatement()):sn(s.getElseStatement())??Cg(s);i!==void 0&&t.push(Tg(i))}return t},kg=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},Rg=(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)||!xg.has(S(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&bg(a))for(const c of Og(a)){const l=vi(c);l!==void 0&&i.push({exportName:kg(e),file:s,form:l,key:S(o),line:c.getStartLineNumber(),owner:t})}}return i},Fg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=Sg(n);i!==void 0&&s.push(...Rg(n,i,t))}return s},Dg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Fg(i,I(t,n)))}return s},Lg=new Set(["query","upsert","upsertMany","upsertNow"]),fe=new Set,Mg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Lg.has(t))return H(e.getExpression(),["vectors"])?t:void 0},Xt=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},xi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},Si=e=>xi(e)?.getDeclarations()[0],_g=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},Ai=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},nn=(e,t,s)=>{const n=xi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Ai(Si(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return Jt(o,t,s-1)}return W(e)},Jt=(e,t,s)=>{const n=Xt(e);return ae(n)?!1:r.isIdentifier(n)?nn(n,t,s):W(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>_g(i)&&nn(i,t,s))},yi=e=>{const t=Ai(Si(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},Z=(e,t)=>{const s=Xt(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...Z(s.getWhenTrue(),t),...Z(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...Z(s.getLeft(),t),...Z(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=yi(s);return n===void 0?[]:Z(n,!1)}return[]},Kg=(e,t)=>{const s=Z(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>We(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},zg=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Bg=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),We=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Kg(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else zg(n)&&(s=[Bg(n)]);return s},$g=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]},Vg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return fe;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return fe;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??[]:[]))},Mt=(e,t=!0,s=fe)=>{const n=Xt(e);if(r.isIdentifier(n)){const o=t?yi(n):void 0;return o===void 0?[{node:n,parameters:s}]:Mt(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Mt(o.getExpression(),t,s):Z(o,!0).flatMap(a=>We(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=Jt(i.getExpression(),fe,1)?Vg(o):fe;return $g(o).flatMap(c=>Z(c,!0).flatMap(l=>We(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Ug=(e,t)=>{const s=Mg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Mt(n):Z(n,!0).flatMap(o=>We(o,!0).map(a=>({node:a,parameters:fe})))).some(({node:o,parameters:a})=>Jt(o,a,1))))return{scope:x(e),file:t,line:e.getStartLineNumber(),method:s}},Wg=(e,t)=>C(e,t,Ug),qg=(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:E}=s;return ir({adminRoutes:va(e,t),aiRawRuns:wa(e,t),aiToolSideEffects:_a(e,t),argumentDerivedFetches:Ba(e,t),argumentValidators:ic(e,t),authApiCalls:Cr(e,t),authConfigs:pc(e,t),browserUrlAccesses:Ec(e,t),callEdges:n.callEdges,configCalls:wc(e,t),containerKeyAccesses:Cc(e,t),containerOverrides:Dc(e,t),containers:i,countReads:zc(e,t,f.tables),cronTargets:o.flatMap(V=>V.functionPath===void 0?[]:[V.functionPath]),exportSinks:Uc(e,t),staleMigrationImports:tg(e,t),failOpenGuards:Gc(e,t),flagReads:Zc(e,t),flagSecurityDefaults:nl(e,t),geoIndexUsages:ol(e,t),httpActionGuards:El(e,t),httpHeaderWrites:Cl(e,t),hyperdriveCalls:Tr(e,t),identityClaimReads:zl(e,t),imageDeliveryUrlAccesses:$l(e,t),inserts:n.inserts,kvKeyAccesses:Ul(e,t,a),mailRecipientAccesses:Gl(e,t),maskProcedures:Or(e,t),maskStrategies:Xl(e,t),mutatorWrites:nd(e,t),nondeterministicCalls:Lr(e,t),normalizeIdAuthorizations:Ed(e,t),notifyCalls:_r(e,t),notifyConfig:Mr(e,t),mutators:l,ownerFieldWrites:gu(e,t,a,l),unrestrictedWhereBranches:Dg(e,t),paymentWebhooks:Eu(e,t),privilegedDispatches:Tu(e,t),procedureProtections:gf(e,t),queries:n.queries,queues:u,r2sqlCalls:Kr(e,t),ratelimitKeySelectors:Sf(e,t),rawRowReturns:If(e,t),relationLoads:Of(e,t),rlsProcedures:zr(e,t),schema:f,secretLiterals:qf(e,t),modules:c,shapes:g,softDeleteReads:Hf(e,t),sqlInterpolations:Jf(e,t),storageKeyAccesses:ng(e,t,a),storageUploads:lg(e,t),tableWrites:n.tableWrites,rowEffects:Bf(e,t,n.tableWrites,n.callEdges),unboundedLoops:Eg(e,t),vectorNamespaceAccesses:Wg(e,t),workflowCalls:n.workflowCalls,workflows:E,wranglerVariables:m})},jg=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"}),Hg=(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=>jg(i))]},Gg=()=>({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"}),Yg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",rn={error:"ERROR",info:"INFO",warn:"WARN"},on={ERROR:2,INFO:0,WARN:1},Qg=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"}),Xg=(e,t)=>{const{advisor:s}=On(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(rn,n)?rn[n]:void 0;return i===void 0?[...t,Qg(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=>Yg(o)||on[o.level]>=on[i])},Jg=(e,t)=>{const{advisor:s}=On(e),n=Hg(t,s?.accept??[]);return Xg(e,s?.acceptUnreadable===!0?[...n,Gg()]:n)},Zg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},ep="crons",tp=Hr.replace(/\.ts$/u,""),ue=(e,t)=>`${Wt(e)}:${t}`,St=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},sp=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Zg[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,...St("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...St("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...St("workflow",t.workflow,"workflow name")}))],np=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:np(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},rp=e=>sp(e).flatMap(t=>ip(t)),op=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:ep,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],ap=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),me=(e,t)=>t===void 0?e:{...e,module:t},cp=e=>{const t=new Map,s=new Map,n=ap(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(ue(c.file,c.exportName),l)};for(const c of e.functions){const l=ue(c.filePath,c.exportName),u=[...Br(c.filePath),c.exportName].join(".");o(me({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Re(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ue(c.filePath,c.exportName);o(me({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Re(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(me({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(me({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Re(e.modules,c.filePath)),ue(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(me({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Re(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ue(tp,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}},lp=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,dp=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ue(e.file,e.exportName))??{reason:lp(e.exportName)},up=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=dp(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`}},At=e=>`${e.from}|${e.kind}|${e.to}`,fp=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,gp=e=>{const{nodes:t,sites:s}=cp(e),n=new Map,i=new Map;for(const o of[...op(e),...rp(e)]){const a=up(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(At(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(fp(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>At(o).localeCompare(At(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}},pp=e=>`${Qr}export const architecture = ${Yr(e,"Record<string, unknown>")};
4
4
  `,an=(e,t="api")=>{const s=new Map;for(const n of e){const i=Wt(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 j("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})}}},mp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Fn(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=>Dn(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?[]:Jr)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)},hp=(e,t,s={})=>{if(t===void 0)return;const n=mp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
@@ -1,30 +1,30 @@
1
- import{LunoraError as x}from"@lunora/errors";import{L as ie,G as D,d as j,I as T,b as F,r as ce,c as le}from"./shared-DnCokNcE.mjs";import{renderAgentFunctionRegistry as ue,renderSandboxFunctionRegistry as de}from"./emitApi-CDgIPAG2.mjs";import{b as he,a as pe,r as I,c as me}from"./qualifiers-DEdXn5wP.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const ge=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),U=r=>r.column!==void 0,fe=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
1
+ import{LunoraError as P}from"@lunora/errors";import{L as ce,G as j,d as D,I as T,b as M,r as le,c as ue}from"./shared-DnCokNcE.mjs";import{renderAgentFunctionRegistry as de,renderSandboxFunctionRegistry as he}from"./emitApi-CDgIPAG2.mjs";import{b as pe,a as me,r as I,c as ge}from"./qualifiers-DEdXn5wP.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const fe=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),U=r=>r.column!==void 0,ye=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
2
2
  `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
3
3
  `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
4
4
  `;case"null":return`if (${t} !== null) return DEFER;
5
5
  `;default:return`if (typeof ${t} !== "string") return DEFER;
6
- `}},ye=(r,t)=>r.stringMaxLength===void 0?"":`if (${t}.length > ${String(r.stringMaxLength)}) return DEFER;
7
- `,$e=(r,t)=>{const n=r.literalValue?.trim();if(!(n===void 0||!ie.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
8
- `}},E=(r,t,n)=>{if(!U(r)&&!(r.unmodelledRefinement||r.sourceText!==void 0)){if(ge.has(r.kind))return r.kind==="any"?{out:t,pre:""}:{out:t,pre:fe(r.kind,t)+ye(r,t)};switch(r.kind){case"array":return we(r,t,n);case"literal":return $e(r,t);case"object":return be(r,t,n);default:return}}},we=(r,t,n)=>{const{inner:o}=r;if(!o)return;const a=n.next(),i=`__arr${String(a)}`,s=`__i${String(a)}`,c=`__e${String(a)}`,d=E(o,c,n);if(!d)return;const l=`if (!Array.isArray(${t})) return DEFER;
6
+ `}},$e=(r,t)=>r.stringMaxLength===void 0?"":`if (${t}.length > ${String(r.stringMaxLength)}) return DEFER;
7
+ `,we=(r,t)=>{const n=r.literalValue?.trim();if(!(n===void 0||!ce.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
8
+ `}},E=(r,t,n)=>{if(!U(r)&&!(r.unmodelledRefinement||r.sourceText!==void 0)){if(fe.has(r.kind))return r.kind==="any"?{out:t,pre:""}:{out:t,pre:ye(r.kind,t)+$e(r,t)};switch(r.kind){case"array":return Re(r,t,n);case"literal":return we(r,t);case"object":return Ne(r,t,n);default:return}}},Re=(r,t,n)=>{const{inner:o}=r;if(!o)return;const a=n.next(),i=`__arr${String(a)}`,s=`__i${String(a)}`,c=`__e${String(a)}`,d=E(o,c,n);if(!d)return;const l=`if (!Array.isArray(${t})) return DEFER;
9
9
  const ${i} = new Array(${t}.length);
10
10
  for (let ${s} = 0; ${s} < ${t}.length; ${s}++) {
11
11
  const ${c} = ${t}[${s}];
12
12
  ${d.pre}${i}[${s}] = ${d.out};
13
13
  }
14
- `;return{out:i,pre:l}},Re=(r,t,n,o)=>{const a=JSON.stringify(r);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||U(t))return;const{inner:s}=t;if(!s)return;const c=E(s,n,o);if(!c)return;const d=o.next(),l=`__has${String(d)}`,u=`__val${String(d)}`,f=`let ${l} = false;
14
+ `;return{out:i,pre:l}},ke=(r,t,n,o)=>{const a=JSON.stringify(r);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||U(t))return;const{inner:s}=t;if(!s)return;const c=E(s,n,o);if(!c)return;const d=o.next(),l=`__has${String(d)}`,u=`__val${String(d)}`,f=`let ${l} = false;
15
15
  let ${u};
16
16
  if (${n} !== undefined) {
17
17
  ${c.pre}${u} = ${c.out};
18
18
  ${l} = true;
19
19
  }
20
- `;return{entry:`...(${l} ? { ${a}: ${u} } : {})`,pre:f}}const i=E(t,n,o);if(i)return{entry:`${a}: ${i.out}`,pre:i.pre}},ke=new Set(Object.getOwnPropertyNames(Object.prototype)),J=(r,t,n)=>{let o="";const a=[];for(const i of Object.keys(r)){const s=r[i];if(!s)return;const c=JSON.stringify(i);let d=`${t}[${c}]`;if(ke.has(i)){const u=`__f${String(n.next())}`;o+=`const ${u} = Object.hasOwn(${t}, ${c}) ? ${t}[${c}] : undefined;
21
- `,d=u}const l=Re(i,s,d,n);if(!l)return;o+=l.pre,a.push(l.entry)}return{entries:a.join(", "),pre:o}},B=r=>{const t=`Object.getPrototypeOf(${r})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
22
- `},be=(r,t,n)=>{const o=r.shape??{},a=J(o,t,n);if(!a)return;const i=n.next(),s=`__obj${String(i)}`,c=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
20
+ `;return{entry:`...(${l} ? { ${a}: ${u} } : {})`,pre:f}}const i=E(t,n,o);if(i)return{entry:`${a}: ${i.out}`,pre:i.pre}},be=new Set(Object.getOwnPropertyNames(Object.prototype)),J=(r,t,n)=>{let o="";const a=[];for(const i of Object.keys(r)){const s=r[i];if(!s)return;const c=JSON.stringify(i);let d=`${t}[${c}]`;if(be.has(i)){const u=`__f${String(n.next())}`;o+=`const ${u} = Object.hasOwn(${t}, ${c}) ? ${t}[${c}] : undefined;
21
+ `,d=u}const l=ke(i,s,d,n);if(!l)return;o+=l.pre,a.push(l.entry)}return{entries:a.join(", "),pre:o}},B=r=>{const t=`Object.getPrototypeOf(${r})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
22
+ `},Ne=(r,t,n)=>{const o=r.shape??{},a=J(o,t,n);if(!a)return;const i=n.next(),s=`__obj${String(i)}`,c=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
23
23
  ${B(t)}${a.pre}const ${s} = { ${a.entries} };
24
24
  `;return{out:s,pre:c}},q=r=>{let t=0;const o=J(r,"source",{next:()=>(t+=1,t)});if(o)return`(source) => {
25
25
  if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
26
26
  ${B("source")}${o.pre}return { ${o.entries} };
27
- }`},Ne=(r,t)=>`lunora_${g(r)}_${String(t)}`,C=r=>JSON.stringify(Object.entries(r).toSorted(([t],[n])=>t.localeCompare(n)).map(([t,n])=>{const o=n.kind==="optional",a=o?n.inner??{kind:"unknown"}:n,i=a.kind==="array"?a.inner?.kind:void 0,s=a.kind==="id"?a.tableName:void 0;return{kind:a.kind,name:t,optional:o,...s===void 0?{}:{table:s},...i===void 0||i==="unknown"?{}:{element:i}}})),H=(r,t,n,o)=>{const a=new Map,i=s=>{a.has(s)||a.set(s,Ne(s,a.size))};for(const s of r)i(s.filePath);for(const s of t)i(s.filePath);for(const s of n)i(s.filePath);for(const s of o)i(s.filePath);return a},W=(r,t,n)=>new Set([...r.map(o=>o.filePath),...t.map(o=>o.filePath),...n.map(o=>o.filePath)]),N=r=>`${r}[functionPath]`,ve=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
27
+ }`},ve=(r,t)=>`lunora_${g(r)}_${String(t)}`,C=r=>JSON.stringify(Object.entries(r).toSorted(([t],[n])=>t.localeCompare(n)).map(([t,n])=>{const o=n.kind==="optional",a=o?n.inner??{kind:"unknown"}:n,i=a.kind==="array"?a.inner?.kind:void 0,s=a.kind==="id"?a.tableName:void 0;return{kind:a.kind,name:t,optional:o,...s===void 0?{}:{table:s},...i===void 0||i==="unknown"?{}:{element:i}}})),H=(r,t,n,o)=>{const a=new Map,i=s=>{a.has(s)||a.set(s,ve(s,a.size))};for(const s of r)i(s.filePath);for(const s of t)i(s.filePath);for(const s of n)i(s.filePath);for(const s of o)i(s.filePath);return a},z=(r,t,n)=>new Set([...r.map(o=>o.filePath),...t.map(o=>o.filePath),...n.map(o=>o.filePath)]),N=r=>`${r}[functionPath]`,Oe=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
28
28
  const registered = await loadFunction(functionPath);
29
29
 
30
30
  if (!registered) {
@@ -57,18 +57,18 @@ ${B("source")}${o.pre}return { ${o.entries} };
57
57
  }
58
58
 
59
59
  return (await registered.handler(context, args ?? {})) as R;
60
- };`,Oe=(r,t,n=[],o=[],a=!1)=>{const i=H(r,t,n,o),s=W(t,n,o),c=[...i.entries()].filter(([e])=>!a||s.has(e)?!0:r.some(p=>p.filePath===e&&p.channel?.kind==="room")).map(([e,p])=>{if(!T.test(e))throw new x("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);return`import ${a&&!s.has(e)?"type ":""}* as ${p} from "../${e}.js";`}).join(`
60
+ };`,Se=(r,t,n=[],o=[],a=!1)=>{const i=H(r,t,n,o),s=z(t,n,o),c=[...i.entries()].filter(([e])=>!a||s.has(e)?!0:r.some(p=>p.filePath===e&&p.channel?.kind==="room")).map(([e,p])=>{if(!T.test(e))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);return`import ${a&&!s.has(e)?"type ":""}* as ${p} from "../${e}.js";`}).join(`
61
61
  `),d=r.map(e=>!a||s.has(e.filePath)?` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`:` "${g(e.filePath)}:${e.exportName}": { args: {}, handler: unloadedFunctionHandler, ...${JSON.stringify({argumentDescriptors:JSON.parse(C(e.args)),kind:e.kind,...e.channel?{channel:e.channel}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}},...e.socket===void 0?{}:{auth:e.socket.auth,socketPath:e.socket.path}})} } satisfies RegisteredLunoraFunction & Pick<FunctionManifestEntry, "argumentDescriptors" | "channel" | "expose">,`).join(`
62
62
  `),l=t.map(e=>` ${JSON.stringify(e.id)}: ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredDataMigration,`).join(`
63
63
  `),u=n.map(e=>` "${g(e.filePath)}:${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredLunoraFunction,`).join(`
64
64
  `),f=o.map(e=>` "${e.exportName}": ${i.get(e.filePath)??""}.${e.exportName} as unknown as RegisteredShape,`).join(`
65
- `),y=n.map(e=>`${g(e.filePath)}:${e.exportName}`),$=[d,u].filter(e=>e.length>0).join(`
65
+ `),$=n.map(e=>`${g(e.filePath)}:${e.exportName}`),y=[d,u].filter(e=>e.length>0).join(`
66
66
  `),v=r.filter(e=>!a||s.has(e.filePath)).map(e=>{if(e.lifecycle||Object.keys(e.args).length===0)return;const p=q(e.args);return p===void 0?void 0:`installCompiledValidatorMap(${i.get(e.filePath)??""}.${e.exportName}.args, ${p});`}).filter(e=>e!==void 0).join(`
67
67
  `),O=r.filter(e=>e.channel?.kind==="room").map(e=>` ${JSON.stringify(e.channel?.name??"")}: RoomMessageOf<typeof ${i.get(e.filePath)??""}[${JSON.stringify(e.exportName)}]>;`).join(`
68
- `),k=[...r.map(e=>({args:e.args,definition:e,path:`${g(e.filePath)}:${e.exportName}`})),...n.map(e=>({args:e.args,definition:{...e,expose:void 0,kind:"mutation",lifecycle:void 0,visibility:void 0,x402:void 0},path:`${g(e.filePath)}:${e.exportName}`}))],S=a?k.filter(({definition:e})=>!s.has(e.filePath)):[];for(const{definition:e}of k)if(a&&e.x402&&e.x402.price===void 0)throw new x("INTERNAL",`@lunora/codegen: lazy function registry needs a literal \`.x402({ price })\` value in ${e.filePath}:${e.exportName}`);const b=a?S.map(({definition:e,path:p})=>{const R=i.get(e.filePath)??"",P="channel"in e?e.channel:void 0,L={argumentDescriptors:JSON.parse(C(e.args)),exportName:e.exportName,kind:e.kind,moduleId:R,...P?{channel:P}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}}};return` ${JSON.stringify(p)}: ${JSON.stringify(L)},`}).join(`
69
- `):"",h=[...new Set(S.map(({definition:e})=>e.filePath))],w=a?h.map(e=>{if(!T.test(e))throw new x("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);const p=i.get(e)??"";return` ${JSON.stringify(p)}: () => import(${JSON.stringify(`./fn/${p}.js`)}),`}).join(`
70
- `):"";return{dispatchBody:$.length>0?`
71
- ${$}
68
+ `),k=[...r.map(e=>({args:e.args,definition:e,path:`${g(e.filePath)}:${e.exportName}`})),...n.map(e=>({args:e.args,definition:{...e,expose:void 0,kind:"mutation",lifecycle:void 0,visibility:void 0,x402:void 0},path:`${g(e.filePath)}:${e.exportName}`}))],S=a?k.filter(({definition:e})=>!s.has(e.filePath)):[];for(const{definition:e}of k)if(a&&e.x402&&e.x402.price===void 0)throw new P("INTERNAL",`@lunora/codegen: lazy function registry needs a literal \`.x402({ price })\` value in ${e.filePath}:${e.exportName}`);const b=a?S.map(({definition:e,path:p})=>{const R=i.get(e.filePath)??"",x="channel"in e?e.channel:void 0,A={argumentDescriptors:JSON.parse(C(e.args)),exportName:e.exportName,kind:e.kind,moduleId:R,...x?{channel:x}:{},...e.expose?{expose:e.expose}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.visibility?{visibility:e.visibility}:{},...e.x402?.price===void 0?{}:{x402:{price:e.x402.price}}};return` ${JSON.stringify(p)}: ${JSON.stringify(A)},`}).join(`
69
+ `):"",h=[...new Set(S.map(({definition:e})=>e.filePath))],w=a?h.map(e=>{if(!T.test(e))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(e)}`);const p=i.get(e)??"";return` ${JSON.stringify(p)}: () => import(${JSON.stringify(`./fn/${p}.js`)}),`}).join(`
70
+ `):"";return{dispatchBody:y.length>0?`
71
+ ${y}
72
72
  `:"",importBlock:c.length>0?`${c}
73
73
 
74
74
  `:"",installBlock:v,manifestBody:b.length>0?`
@@ -77,9 +77,9 @@ ${b}
77
77
  ${l}
78
78
  `:"",moduleLoaders:w.length>0?`
79
79
  ${w}
80
- `:"",mutatorPaths:y,roomMessagesBody:O,shapeBody:f.length>0?`
80
+ `:"",mutatorPaths:$,roomMessagesBody:O,shapeBody:f.length>0?`
81
81
  ${f}
82
- `:""}},Se=r=>{const t=F(r,o=>{const a=I(ce(o.args),o.filePath),i=a==="{}"?"?":"",s=I(me(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${i}: ${a}) => Promise<AsyncIterable<${s}>>;`:`${o.exportName}: (args${i}: ${a}) => Promise<${s}>;`},"type");return{implementation:F(r,o=>`${le(o.exportName)}: (args) => callRegistered(context, "${g(o.filePath)}:${o.exportName}", args),`,"value"),types:t}},xe=r=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of r)!n.lifecycle||n.lifecycle==="socket"||t[n.lifecycle].push(`${g(n.filePath)}:${n.exportName}`);return t},Pe=r=>{const t=new Map,n=[];for(const o of r){if(o.lifecycle!=="socket"||o.socket===void 0)continue;const{auth:a,origin:i,path:s}=o.socket,c=`${g(o.filePath)}:${o.exportName}`,d=t.get(s);if(!(d?.origin!==void 0&&d.origin===i)){if(d!==void 0)throw new x("DUPLICATE_SOCKET_PATH",`two defineWebSocket routes serve "${s}" (${d.functionPath} and ${c}); socket paths must be unique.`);t.set(s,{functionPath:c,origin:i}),n.push(` ${JSON.stringify(s)}: { auth: ${String(a)}, functionPath: ${JSON.stringify(c)} },`)}}return`
82
+ `:""}},Pe=r=>{const t=M(r,o=>{const a=I(le(o.args),o.filePath),i=a==="{}"?"?":"",s=I(ge(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${i}: ${a}) => Promise<AsyncIterable<${s}>>;`:`${o.exportName}: (args${i}: ${a}) => Promise<${s}>;`},"type");return{implementation:M(r,o=>`${ue(o.exportName)}: (args) => callRegistered(context, "${g(o.filePath)}:${o.exportName}", args),`,"value"),types:t}},xe=r=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of r)!n.lifecycle||n.lifecycle==="socket"||t[n.lifecycle].push(`${g(n.filePath)}:${n.exportName}`);return t},Ae=r=>{const t=new Map,n=[];for(const o of r){if(o.lifecycle!=="socket"||o.socket===void 0)continue;const{auth:a,origin:i,path:s}=o.socket,c=`${g(o.filePath)}:${o.exportName}`,d=t.get(s);if(!(d?.origin!==void 0&&d.origin===i)){if(d!==void 0)throw new P("DUPLICATE_SOCKET_PATH",`two defineWebSocket routes serve "${s}" (${d.functionPath} and ${c}); socket paths must be unique.`);t.set(s,{functionPath:c,origin:i}),n.push(` ${JSON.stringify(s)}: { auth: ${String(a)}, functionPath: ${JSON.stringify(c)} },`)}}return`
83
83
  /**
84
84
  * Socket registry: the URL path of each \`defineWebSocket\` route → its function path + auth requirement.
85
85
  * Static, so building the worker never evaluates a route's module. The generated ShardDO's \`socketRoute\` override
@@ -89,7 +89,7 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
89
89
  ${n.join(`
90
90
  `)}
91
91
  };
92
- `},Le=(r,t)=>{const n=r.some(c=>c.lifecycle==="socket"),a=n&&t?Pe(r):n&&!t?`
92
+ `},Le=(r,t)=>{const n=r.some(c=>c.lifecycle==="socket"),a=n&&t?Ae(r):n&&!t?`
93
93
  /**
94
94
  * Socket registry: the URL path of each \`defineWebSocket\` route → its function
95
95
  * path + auth requirement. The generated ShardDO's \`socketRoute\` override
@@ -133,7 +133,7 @@ export const LUNORA_SOCKETS: Readonly<Record<string, { auth: boolean; functionPa
133
133
  * Set on a \`defineWebSocket\` registration: whether the route refuses an
134
134
  * anonymous upgrade. Read into \`LUNORA_SOCKETS\` alongside \`socketPath\`.
135
135
  */
136
- auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:a}},Ae=(r,t,n)=>r?{channelField:` /**
136
+ auth?: boolean;`:"",lifecycleMember:n?' | "socket"':"",registry:a}},Te=(r,t,n)=>r?{channelField:` /**
137
137
  * Set on a \`defineRoom\` registration: the room's name (without the \`room:\`
138
138
  * topic prefix). The generated \`LUNORA_ROOMS\` map keys it on the room's
139
139
  * \`room:<name>\` whisper topic so the ShardDO resolves a room topic to this
@@ -148,7 +148,7 @@ export type LunoraRoomMessages = {
148
148
  ${n}
149
149
  };
150
150
  `,typeImport:`import type { RoomMessageOf } from "${t}";
151
- `}:{channelField:"",messagesBlock:"",typeImport:""},Te=(r,t,n)=>r?t?`
151
+ `}:{channelField:"",messagesBlock:"",typeImport:""},Ee=(r,t,n)=>r?t?`
152
152
  /**
153
153
  * Room routes are static metadata so building the worker never evaluates user handlers.
154
154
  */
@@ -208,24 +208,24 @@ export const LUNORA_ROOMS: Readonly<Record<string, string>> = (() => {
208
208
 
209
209
  return registry;
210
210
  })();
211
- `:"",Ee=(r,t)=>{const n=Se(r),o=n.types?`
211
+ `:"",Fe=(r,t)=>{const n=Pe(r),o=n.types?`
212
212
  ${n.types}
213
213
  `:"",a=n.implementation?`
214
214
  ${n.implementation}
215
- `:"",i=pe(n.types),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
216
- `:"",c=r.length>0?"context":"_context";let d="";if(r.length>0){let l=ve;t||(l=l.replace("await loadFunction(functionPath)",N("LUNORA_FUNCTIONS"))),d=`${l}
215
+ `:"",i=me(n.types),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
216
+ `:"",c=r.length>0?"context":"_context";let d="";if(r.length>0){let l=Oe;t||(l=l.replace("await loadFunction(functionPath)",N("LUNORA_FUNCTIONS"))),d=`${l}
217
217
 
218
- `}return{callRegisteredHelper:d,dataModelImport:s,implementation:a,parameter:c,types:o}},De=r=>{const{agents:t=[],functions:n,lazyFunctions:o=!1,migrations:a=[],mutators:i=[],shapes:s=[],useUmbrella:c=!1,usesSandbox:d=!1}=r,l=j(c),{dispatchBody:u,importBlock:f,installBlock:y,manifestBody:$,migrationBody:v,moduleLoaders:O,mutatorPaths:k,roomMessagesBody:S,shapeBody:b}=Oe(n,a,i,s,o),h=ue(t,n),w=de(d,n),e=[h.lines,w.lines].filter(m=>m.length>0).join(`
218
+ `}return{callRegisteredHelper:d,dataModelImport:s,implementation:a,parameter:c,types:o}},De=r=>{const{agents:t=[],functions:n,lazyFunctions:o=!1,migrations:a=[],mutators:i=[],shapes:s=[],useUmbrella:c=!1,usesSandbox:d=!1}=r,l=D(c),{dispatchBody:u,importBlock:f,installBlock:$,manifestBody:y,migrationBody:v,moduleLoaders:O,mutatorPaths:k,roomMessagesBody:S,shapeBody:b}=Se(n,a,i,s,o),h=de(t,n),w=he(d,n),e=[h.lines,w.lines].filter(m=>m.length>0).join(`
219
219
  `);let p=u;e.length>0&&(p=u.length>0?`${u.trimEnd()}
220
220
  ${e}
221
221
  `:`
222
222
  ${e}
223
- `);const R=xe(n),P=o?"await loadFunction(functionPath)":N("LUNORA_FUNCTIONS"),L=o?` if (${N("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
223
+ `);const R=xe(n),x=o?"await loadFunction(functionPath)":N("LUNORA_FUNCTIONS"),A=o?` if (${N("LUNORA_FUNCTION_MANIFEST")}?.visibility === "internal") {
224
224
  throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
225
225
  }
226
226
 
227
- `:"",z=s.length>0?`import type { RegisteredShape } from "${l.server}";
228
- `:"",M=n.some(m=>m.channel?.kind==="room"),A=Ae(M,l.server,S),Q=s.length>0?`
227
+ `:"",W=s.length>0?`import type { RegisteredShape } from "${l.server}";
228
+ `:"",F=n.some(m=>m.channel?.kind==="room"),L=Te(F,l.server,S),Q=s.length>0?`
229
229
  /**
230
230
  * Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
231
231
  * The generated ShardDO's \`resolveShape\` override looks a shape up by name and
@@ -240,15 +240,15 @@ export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${b}};
240
240
  * protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
241
241
  */
242
242
  export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${k.map(m=>JSON.stringify(m)).join(", ")}]);
243
- `:"",V=Te(M,o,n),{fields:K,lifecycleMember:_,registry:Y}=Le(n,o),Z=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${l.values}";
244
- `:"",X=y.length>0?`
243
+ `:"",V=Ee(F,o,n),{fields:K,lifecycleMember:_,registry:Y}=Le(n,o),Z=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${l.values}";
244
+ `:"",X=$.length>0?`
245
245
  /**
246
246
  * AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
247
247
  * onto its function's live \`.args\` object and consulted by the interpreted
248
248
  * parser as a zero-allocation fast path; anything it can't model is deferred.
249
249
  */
250
- ${y}
251
- `:"",ee=Ee(n,o),{callRegisteredHelper:te,dataModelImport:re,implementation:ne,parameter:oe,types:se}=ee,ae=o?`
250
+ ${$}
251
+ `:"",ee=Fe(n,o),{callRegisteredHelper:te,dataModelImport:re,implementation:ne,parameter:oe,types:se}=ee,ae=o?`
252
252
  export interface FunctionManifestEntry {
253
253
  argumentDescriptors: ReadonlyArray<{ element?: string; kind: string; name: string; optional: boolean; table?: string }>;
254
254
  channel?: { kind: "room"; name: string };
@@ -262,7 +262,7 @@ export interface FunctionManifestEntry {
262
262
  }
263
263
 
264
264
  /** Static, codegen-derived facts. Request gates can inspect these without evaluating a user module. */
265
- export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${$}};
265
+ export const LUNORA_FUNCTION_MANIFEST: Readonly<Record<string, FunctionManifestEntry>> = {${y}};
266
266
 
267
267
  const MODULE_LOADERS: Record<string, () => Promise<Record<string, unknown>>> = {${O}};
268
268
  const loadedModules = new Map<string, Promise<Record<string, unknown>>>();
@@ -332,7 +332,34 @@ export const loadFunction = async (functionPath: string): Promise<RegisteredLuno
332
332
 
333
333
  return getLoadedFunction(functionPath);
334
334
  };
335
- `:"";return he(`${D}${f}${h.importLine}${w.importLine}${Z}${z}${A.typeImport}import { LunoraError } from "${l.server}";
335
+
336
+ `:"",ie=o&&y!==""?`
337
+ /**
338
+ * Evaluate every lazy module now and report the ones that fail, keyed by function path. A lazy
339
+ * registry defers a broken module's error to its first call; \`lunora build\` and \`deploy\` run this
340
+ * inside workerd so the error surfaces before the Worker ships instead of in front of a user.
341
+ */
342
+ export const loadAllFunctions = async (): Promise<{ checked: number; failures: ReadonlyArray<{ functionPath: string; message: string }> }> => {
343
+ const functionPaths = Object.keys(LUNORA_FUNCTION_MANIFEST);
344
+ // Concurrent, so the total is bounded by the slowest module rather than by all of them added up. A module
345
+ // shared by several functions is evaluated once (loadFunction keeps its pending promise), and failures keep manifest order.
346
+ const failures = (
347
+ await Promise.all(
348
+ functionPaths.map(async (functionPath) => {
349
+ try {
350
+ await loadFunction(functionPath);
351
+
352
+ return undefined;
353
+ } catch (error) {
354
+ return { functionPath, message: error instanceof Error ? error.message : String(error) };
355
+ }
356
+ }),
357
+ )
358
+ ).filter((failure) => failure !== undefined);
359
+
360
+ return { checked: functionPaths.length, failures };
361
+ };
362
+ `:"";return pe(`${j}${f}${h.importLine}${w.importLine}${Z}${W}${L.typeImport}import { LunoraError } from "${l.server}";
336
363
  import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
337
364
  ${re}
338
365
  /**
@@ -364,7 +391,7 @@ export interface RegisteredLunoraFunction {
364
391
  * to. \`whisper\` does have one — it runs under the asking socket's identity.
365
392
  */
366
393
  lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper"${_};${K}
367
- ${A.channelField} /**
394
+ ${L.channelField} /**
368
395
  * Hoisted by the builder when the \`.use()\` chain carries a step with a
369
396
  * per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
370
397
  * captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
@@ -380,13 +407,13 @@ ${A.channelField} /**
380
407
  */
381
408
  x402?: { readonly price: number | string };
382
409
  }
383
- ${h.prelude}${w.prelude}${ae}
410
+ ${h.prelude}${w.prelude}${ae}${ie}
384
411
  /**
385
412
  * Static dispatch table. The key matches the \`__lunoraRef\` the client
386
413
  * emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
387
414
  */
388
415
  export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${p}};
389
- ${X}${Q}${G}${V}${A.messagesBlock}${Y}
416
+ ${X}${Q}${G}${V}${L.messagesBlock}${Y}
390
417
  /**
391
418
  * Lifecycle manifest: the function paths the generated ShardDO dispatches when a
392
419
  * client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
@@ -418,7 +445,7 @@ export const LUNORA_LIFECYCLE_HOOKS: {
418
445
  * functions are treated as not-found so their existence never leaks to clients.
419
446
  */
420
447
  export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
421
- ${L} const registered = ${P};
448
+ ${A} const registered = ${x};
422
449
 
423
450
  if (!registered || registered.visibility === "internal") {
424
451
  throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
@@ -462,12 +489,12 @@ export interface RegisteredDataMigration {
462
489
  * shard DO's admin RPC and the CLI resolve migrations to run through this map.
463
490
  */
464
491
  export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${v}};
465
- `,c)},je="fn",Ue=r=>{if(r.lazyFunctions!==!0)return{};const{functions:t}=r,n=r.migrations??[],o=r.mutators??[],a=r.shapes??[],i=H(t,n,o,a),s=W(n,o,a),c=[...new Set(t.filter(u=>!s.has(u.filePath)).map(u=>u.filePath))],d=j(r.useUmbrella??!1),l={};for(const u of c){if(!T.test(u))throw new x("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(u)}`);const f=i.get(u)??"",y=`../../${u}.js`,$=t.filter(h=>h.filePath===u&&!h.lifecycle&&Object.keys(h.args).length>0).flatMap(h=>{const w=q(h.args);return w===void 0?[]:[`installCompiledValidatorMap(${f}.${h.exportName}.args, ${w});`]}),v=$.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
466
- `:"",O=$.length>0?`import * as ${f} from "${y}";
467
- `:"",k=$.length>0?`
492
+ `,c)},Ue="fn",Je=r=>{if(r.lazyFunctions!==!0)return{};const{functions:t}=r,n=r.migrations??[],o=r.mutators??[],a=r.shapes??[],i=H(t,n,o,a),s=z(n,o,a),c=[...new Set(t.filter(u=>!s.has(u.filePath)).map(u=>u.filePath))],d=D(r.useUmbrella??!1),l={};for(const u of c){if(!T.test(u))throw new P("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(u)}`);const f=i.get(u)??"",$=`../../${u}.js`,y=t.filter(h=>h.filePath===u&&!h.lifecycle&&Object.keys(h.args).length>0).flatMap(h=>{const w=q(h.args);return w===void 0?[]:[`installCompiledValidatorMap(${f}.${h.exportName}.args, ${w});`]}),v=y.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${d.values}";
493
+ `:"",O=y.length>0?`import * as ${f} from "${$}";
494
+ `:"",k=y.length>0?`
468
495
  /** Install the precompiled argument parsers before the module is dispatched. */
469
- ${$.join(`
496
+ ${y.join(`
470
497
  `)}
471
- `:"",b=t.some(h=>h.filePath===u&&h.exportName==="default")||n.some(h=>h.filePath===u&&h.exportName==="default")?`export { default } from "${y}";
472
- `:"";l[`${f}.ts`]=`${D}${v}${O}${k}export * from "${y}";
473
- ${b}`}return l};export{je as LAZY_FUNCTION_DIRECTORY,De as emitFunctions,Ue as emitLazyFunctionModules};
498
+ `:"",b=t.some(h=>h.filePath===u&&h.exportName==="default")||n.some(h=>h.filePath===u&&h.exportName==="default")?`export { default } from "${$}";
499
+ `:"";l[`${f}.ts`]=`${j}${v}${O}${k}export * from "${$}";
500
+ ${b}`}return l};export{Ue as LAZY_FUNCTION_DIRECTORY,De as emitFunctions,Je as emitLazyFunctionModules};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.327",
3
+ "version": "1.0.0-alpha.328",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",