@lunora/codegen 1.0.0-alpha.427 → 1.0.0-alpha.429

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 i,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as d,lintSchema as f,toAdvisorContext as m}from"./packem_shared/formatAdvisories-Bue5tbp6.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as S}from"./packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs";import{COMPANION_BINDING as u,COMPANION_SERVICE_NAME as N}from"./packem_shared/COMPANION_BINDING-Da_v9XpC.mjs";import{CodegenDiagnosticError as g,diagnosticAt as C}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as I,discoverAgents as _}from"./packem_shared/AGENTS_FILENAME-BSW65Q9R.mjs";import{isTestPath as L,listLunoraSourceFiles as M}from"./packem_shared/isTestPath-DJeZ18i9.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-DcvsgL5u.mjs";import{CONTAINERS_FILENAME as P,discoverContainers as D}from"./packem_shared/CONTAINERS_FILENAME-Dy3qWGfI.mjs";import{default as b}from"./packem_shared/discoverCrons-MpIC14pg.mjs";import{ENV_FILENAME as U}from"./packem_shared/ENV_FILENAME-DFx_jlpa.mjs";import{capabilitiesUsedBy as H,createTargetScope as j,foldCapabilitySignals as V,mayReadCapabilityContext as k,sourceCapabilitySignals as W}from"./packem_shared/capabilitiesUsedBy-BcDkRoOu.mjs";import{FLAGS_FILENAME as K,discoverFlags as Q}from"./packem_shared/FLAGS_FILENAME-CDaIBL6L.mjs";import{d as q}from"./packem_shared/index-BwLaIVqA.mjs";import{default as J}from"./packem_shared/discoverHttpRoutes-BtMgsfzG.mjs";import{default as Z}from"./packem_shared/discoverHyperdriveCalls-B--Nvx36.mjs";import{default as ee}from"./packem_shared/discoverInserts-Dx7Lxey3.mjs";import{d as oe}from"./packem_shared/index-CQuAXbal.mjs";import{default as ie}from"./packem_shared/discoverMigrations-DaBdK1Bv.mjs";import{MUTATORS_FILENAME as se,discoverMutators as de}from"./packem_shared/MUTATORS_FILENAME-SLAN2VXq.mjs";import{default as me}from"./packem_shared/discoverNondeterministicCalls-MeKjo_UX.mjs";import{ALL_NOTIFY_CHANNELS as ne,NOTIFY_FILENAME as ce,discoverNotifyCalls as le,discoverNotifyChannels as Se,discoverNotifyConfig as xe}from"./packem_shared/ALL_NOTIFY_CHANNELS-DI0zmZGs.mjs";import{default as Ae}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as Ne}from"./packem_shared/discoverQueries-BlhMsXuk.mjs";import{QUEUES_FILENAME as ge,discoverQueues as Ce}from"./packem_shared/QUEUES_FILENAME-CVkpGqoY.mjs";import{default as Ie}from"./packem_shared/discoverR2sqlCalls-DHvclvkv.mjs";import{default as Re}from"./packem_shared/discoverRlsProcedures-CUfhUqfY.mjs";import{default as Me}from"./packem_shared/discoverRlsMetadata-CO-pRHOx.mjs";import{discoverSandboxUsage as Fe}from"./packem_shared/discoverSandboxUsage-CdrJNRFd.mjs";import{default as Pe}from"./packem_shared/discoverSchema-CL9PLdOu.mjs";import{companionServiceBinding as ye,readBoundServiceBindings as be,readDevServiceBindings as Ge,readServiceBindings as Ue,resolveServiceBindings as Be}from"./packem_shared/companionServiceBinding-BZjm486n.mjs";import{SHAPES_FILENAME as je,discoverShapes as Ve}from"./packem_shared/SHAPES_FILENAME-Cf4sum4C.mjs";import{default as We}from"./packem_shared/discoverStorageRulesMetadata-D_pYyr1i.mjs";import{WORKFLOWS_FILENAME as Ke,discoverWorkflows as Qe}from"./packem_shared/WORKFLOWS_FILENAME-Dtxo_XBw.mjs";import{emitApp as qe}from"./packem_shared/emitApp-LFKtDRYu.mjs";import{isD1GlobalTable as Je,isHyperdriveGlobalTable as Xe}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as $e,emitOpenApi as er,emitOpenApiModule as rr}from"./packem_shared/buildOpenApiDocument-C3zlve6K.mjs";import{OPENRPC_VERSION as tr,buildOpenRpcDocument as ir,emitOpenRpc as ar,emitOpenRpcModule as sr}from"./packem_shared/OPENRPC_VERSION-DkWde9eh.mjs";import{DEFAULT_TARGET as fr,platformMatrixIds as mr,readProjectTarget as pr,resolveCodegenTarget as nr}from"./packem_shared/DEFAULT_TARGET-CnglMKg_.mjs";import{b as lr,r as Sr,c as xr,d as Er}from"./packem_shared/project-config-file-DR7xrrNB.mjs";import{PROJECT_CONFIG_FILENAMES as ur,findCodegenConfigFile as Nr,findProjectConfigFile as vr,projectConfigCandidatePaths as gr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Or,runCodegen as Ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-jjnAlXZN.mjs";import{SchemaSnapshotParseError as Rr,buildSchemaSnapshot as Lr,evaluateSchemaDrift as Mr,indexReferencesOf as Tr,parseSchemaSnapshot as Fr}from"./packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs";import{default as Pr}from"./packem_shared/fingerprintSchemaSources-BqPD3mw0.mjs";import{schemaFromIr as yr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Gr,validatorIrToJsonSchema as Ur}from"./packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs";import{SDK_LANGUAGES as Hr,SDK_TARGETS as jr,generateSdk as Vr}from"./sdk/index.mjs";import{redact as Wr,secretKindOf as zr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Qr}from"./packem_shared/emitDrizzleSchema-BzOChEYW.mjs";import{e as qr}from"./packem_shared/server-Dfxmm5Zw.mjs";import{e as Jr}from"./packem_shared/shard-CWAD5mYy.mjs";import{G as Zr}from"./packem_shared/shared-Cn7dMQ_u.mjs";import{MESSAGE_SOLUTIONS as eo,findSolutionByMessage as ro}from"@lunora/errors";import{createCodegenProject as to,findTsconfig as io,refreshCodegenProject as ao,tsconfigFingerprint as so}from"./packem_shared/createCodegenProject-C4XuJSap.mjs";import{t as mo,u as po,v as no}from"./packem_shared/shard-runtime-G5mZQjY0.mjs";import{emitApi as lo,emitCollections as So,emitInternalApi as xo}from"./packem_shared/emitApi-lwadq5G7.mjs";import{emitCrons as Ao,emitScheduler as uo,emitVectors as No,emitWranglerCronTriggers as vo}from"./packem_shared/emitCrons-CCRKs482.mjs";import{emitDataModel as Co}from"./packem_shared/emitDataModel-BvCZS4Yq.mjs";import{emitFunctions as Io}from"./packem_shared/emitFunctions-ppMX7E3X.mjs";import{isTypedSchema as Ro}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{I as AGENTS_FILENAME,ne as ALL_NOTIFY_CHANNELS,E as CAPABILITY_PROBES,u as COMPANION_BINDING,N as COMPANION_SERVICE_NAME,P as CONTAINERS_FILENAME,g as CodegenDiagnosticError,fr as DEFAULT_TARGET,U as ENV_FILENAME,K as FLAGS_FILENAME,Zr as GENERATED_HEADER,Gr as LUNORA_ERROR_CODES,eo as LUNORA_SOLUTION_RULES,se as MUTATORS_FILENAME,ce as NOTIFY_FILENAME,tr as OPENRPC_VERSION,ur as PROJECT_CONFIG_FILENAMES,ge as QUEUES_FILENAME,Or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Hr as SDK_LANGUAGES,jr as SDK_TARGETS,je as SHAPES_FILENAME,Rr as SchemaSnapshotParseError,e as VERSION,Ke as WORKFLOWS_FILENAME,$e as buildOpenApiDocument,ir as buildOpenRpcDocument,Lr as buildSchemaSnapshot,H as capabilitiesUsedBy,ye as companionServiceBinding,to as createCodegenProject,j as createTargetScope,n as describeErrorLevelFindings,C as diagnosticAt,i as diffSchemaSnapshots,_ as discoverAgents,F as discoverAuthApiCalls,D as discoverContainers,b as discoverCrons,Q as discoverFlags,q as discoverFunctions,J as discoverHttpRoutes,Z as discoverHyperdriveCalls,ee as discoverInserts,oe as discoverMaskProcedures,ie as discoverMigrations,de as discoverMutators,me as discoverNondeterministicCalls,le as discoverNotifyCalls,Se as discoverNotifyChannels,xe as discoverNotifyConfig,Ne as discoverQueries,Ce as discoverQueues,Ie as discoverR2sqlCalls,Me as discoverRlsMetadata,Re as discoverRlsProcedures,Fe as discoverSandboxUsage,Pe as discoverSchema,Ve as discoverShapes,We as discoverStorageRulesMetadata,Qe as discoverWorkflows,mo as emitAgents,lo as emitApi,qe as emitApp,So as emitCollections,po as emitContainers,Ao as emitCrons,Co as emitDataModel,Qr as emitDrizzleSchema,Io as emitFunctions,xo as emitInternalApi,er as emitOpenApi,rr as emitOpenApiModule,ar as emitOpenRpc,sr as emitOpenRpcModule,uo as emitScheduler,qr as emitServer,Jr as emitShard,No as emitVectors,no as emitWorkflows,vo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Mr as evaluateSchemaDrift,Nr as findCodegenConfigFile,ro as findLunoraSolution,vr as findProjectConfigFile,io as findTsconfig,Pr as fingerprintSchemaSources,V as foldCapabilitySignals,d as formatAdvisories,Vr as generateSdk,Tr as indexReferencesOf,Je as isD1GlobalTable,Xe as isHyperdriveGlobalTable,L as isTestPath,Ro as isTypedSchema,f as lintSchema,M as listLunoraSourceFiles,lr as loadProjectConfig,k as mayReadCapabilityContext,Fr as parseSchemaSnapshot,mr as platformMatrixIds,gr as projectConfigCandidatePaths,be as readBoundServiceBindings,Ge as readDevServiceBindings,Ae as readPackageDependencies,Sr as readProjectConfigLiterals,xr as readProjectLazyFunctions,Er as readProjectSecurityHeaders,pr as readProjectTarget,Ue as readServiceBindings,Wr as redact,ao as refreshCodegenProject,nr as resolveCodegenTarget,Be as resolveServiceBindings,Ir as runCodegen,yr as schemaFromIr,zr as secretKindOf,a as serializeSchemaSnapshot,S as sortedUniqueNames,W as sourceCapabilitySignals,m as toAdvisorContext,so as tsconfigFingerprint,Ur as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as i,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{formatAdvisories as d,lintSchema as f,toAdvisorContext as m}from"./packem_shared/formatAdvisories-Bue5tbp6.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as c,errorPlatformDiagnosticNames as l,sortedUniqueNames as S}from"./packem_shared/describeErrorLevelFindings-DlkgCw8a.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DCzOjTN7.mjs";import{COMPANION_BINDING as u,COMPANION_SERVICE_NAME as N}from"./packem_shared/COMPANION_BINDING-Da_v9XpC.mjs";import{CodegenDiagnosticError as g,diagnosticAt as C}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as I,discoverAgents as _}from"./packem_shared/AGENTS_FILENAME-BSW65Q9R.mjs";import{isTestPath as L,listLunoraSourceFiles as M}from"./packem_shared/isTestPath-DJeZ18i9.mjs";import{default as F}from"./packem_shared/discoverAuthApiCalls-DcvsgL5u.mjs";import{CONTAINERS_FILENAME as P,discoverContainers as D}from"./packem_shared/CONTAINERS_FILENAME-Dy3qWGfI.mjs";import{default as b}from"./packem_shared/discoverCrons-MpIC14pg.mjs";import{ENV_FILENAME as U}from"./packem_shared/ENV_FILENAME-DFx_jlpa.mjs";import{capabilitiesUsedBy as H,createTargetScope as j,foldCapabilitySignals as V,mayReadCapabilityContext as k,sourceCapabilitySignals as W}from"./packem_shared/capabilitiesUsedBy-BcDkRoOu.mjs";import{FLAGS_FILENAME as K,discoverFlags as Q}from"./packem_shared/FLAGS_FILENAME-CDaIBL6L.mjs";import{d as q}from"./packem_shared/index-BwLaIVqA.mjs";import{default as J}from"./packem_shared/discoverHttpRoutes-BtMgsfzG.mjs";import{default as Z}from"./packem_shared/discoverHyperdriveCalls-B--Nvx36.mjs";import{default as ee}from"./packem_shared/discoverInserts-Dx7Lxey3.mjs";import{d as oe}from"./packem_shared/index-CQuAXbal.mjs";import{default as ie}from"./packem_shared/discoverMigrations-DaBdK1Bv.mjs";import{MUTATORS_FILENAME as se,discoverMutators as de}from"./packem_shared/MUTATORS_FILENAME-SLAN2VXq.mjs";import{default as me}from"./packem_shared/discoverNondeterministicCalls-MeKjo_UX.mjs";import{ALL_NOTIFY_CHANNELS as ne,NOTIFY_FILENAME as ce,discoverNotifyCalls as le,discoverNotifyChannels as Se,discoverNotifyConfig as xe}from"./packem_shared/ALL_NOTIFY_CHANNELS-DI0zmZGs.mjs";import{default as Ae}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as Ne}from"./packem_shared/discoverQueries-BlhMsXuk.mjs";import{QUEUES_FILENAME as ge,discoverQueues as Ce}from"./packem_shared/QUEUES_FILENAME-CVkpGqoY.mjs";import{default as Ie}from"./packem_shared/discoverR2sqlCalls-DHvclvkv.mjs";import{default as Re}from"./packem_shared/discoverRlsProcedures-CUfhUqfY.mjs";import{default as Me}from"./packem_shared/discoverRlsMetadata-CO-pRHOx.mjs";import{discoverSandboxUsage as Fe}from"./packem_shared/discoverSandboxUsage-CdrJNRFd.mjs";import{default as Pe}from"./packem_shared/discoverSchema-CL9PLdOu.mjs";import{companionServiceBinding as ye,readBoundServiceBindings as be,readDevServiceBindings as Ge,readServiceBindings as Ue,resolveServiceBindings as Be}from"./packem_shared/companionServiceBinding-BZjm486n.mjs";import{SHAPES_FILENAME as je,discoverShapes as Ve}from"./packem_shared/SHAPES_FILENAME-Cf4sum4C.mjs";import{default as We}from"./packem_shared/discoverStorageRulesMetadata-D_pYyr1i.mjs";import{WORKFLOWS_FILENAME as Ke,discoverWorkflows as Qe}from"./packem_shared/WORKFLOWS_FILENAME-Dtxo_XBw.mjs";import{emitApp as qe}from"./packem_shared/emitApp-BJxszWDO.mjs";import{isD1GlobalTable as Je,isHyperdriveGlobalTable as Xe}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as $e,emitOpenApi as er,emitOpenApiModule as rr}from"./packem_shared/buildOpenApiDocument-C3zlve6K.mjs";import{OPENRPC_VERSION as tr,buildOpenRpcDocument as ir,emitOpenRpc as ar,emitOpenRpcModule as sr}from"./packem_shared/OPENRPC_VERSION-DkWde9eh.mjs";import{DEFAULT_TARGET as fr,platformMatrixIds as mr,readProjectTarget as pr,resolveCodegenTarget as nr}from"./packem_shared/DEFAULT_TARGET-CnglMKg_.mjs";import{b as lr,r as Sr,c as xr,d as Er}from"./packem_shared/project-config-file-DR7xrrNB.mjs";import{PROJECT_CONFIG_FILENAMES as ur,findCodegenConfigFile as Nr,findProjectConfigFile as vr,projectConfigCandidatePaths as gr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Or,runCodegen as Ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CoXEvSNg.mjs";import{SchemaSnapshotParseError as Rr,buildSchemaSnapshot as Lr,evaluateSchemaDrift as Mr,indexReferencesOf as Tr,parseSchemaSnapshot as Fr}from"./packem_shared/SchemaSnapshotParseError-CV7mmuPi.mjs";import{default as Pr}from"./packem_shared/fingerprintSchemaSources-BqPD3mw0.mjs";import{schemaFromIr as yr}from"./packem_shared/schemaFromIr-CByOxuZb.mjs";import{LUNORA_ERROR_CODES as Gr,validatorIrToJsonSchema as Ur}from"./packem_shared/LUNORA_ERROR_CODES-D7AVT7qF.mjs";import{SDK_LANGUAGES as Hr,SDK_TARGETS as jr,generateSdk as Vr}from"./sdk/index.mjs";import{redact as Wr,secretKindOf as zr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Qr}from"./packem_shared/emitDrizzleSchema-lRoq3OJs.mjs";import{e as qr}from"./packem_shared/server-Dfxmm5Zw.mjs";import{e as Jr}from"./packem_shared/shard-BbYT2omp.mjs";import{G as Zr}from"./packem_shared/shared-Cn7dMQ_u.mjs";import{MESSAGE_SOLUTIONS as eo,findSolutionByMessage as ro}from"@lunora/errors";import{createCodegenProject as to,findTsconfig as io,refreshCodegenProject as ao,tsconfigFingerprint as so}from"./packem_shared/createCodegenProject-C4XuJSap.mjs";import{t as mo,u as po,v as no}from"./packem_shared/shard-runtime-G5mZQjY0.mjs";import{emitApi as lo,emitCollections as So,emitInternalApi as xo}from"./packem_shared/emitApi-lwadq5G7.mjs";import{emitCrons as Ao,emitScheduler as uo,emitVectors as No,emitWranglerCronTriggers as vo}from"./packem_shared/emitCrons-CCRKs482.mjs";import{emitDataModel as Co}from"./packem_shared/emitDataModel-Cen7mAmM.mjs";import{emitFunctions as Io}from"./packem_shared/emitFunctions-ppMX7E3X.mjs";import{isTypedSchema as Ro}from"./packem_shared/isTypedSchema-CDv3pJB6.mjs";const e="0.0.0";export{I as AGENTS_FILENAME,ne as ALL_NOTIFY_CHANNELS,E as CAPABILITY_PROBES,u as COMPANION_BINDING,N as COMPANION_SERVICE_NAME,P as CONTAINERS_FILENAME,g as CodegenDiagnosticError,fr as DEFAULT_TARGET,U as ENV_FILENAME,K as FLAGS_FILENAME,Zr as GENERATED_HEADER,Gr as LUNORA_ERROR_CODES,eo as LUNORA_SOLUTION_RULES,se as MUTATORS_FILENAME,ce as NOTIFY_FILENAME,tr as OPENRPC_VERSION,ur as PROJECT_CONFIG_FILENAMES,ge as QUEUES_FILENAME,Or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Hr as SDK_LANGUAGES,jr as SDK_TARGETS,je as SHAPES_FILENAME,Rr as SchemaSnapshotParseError,e as VERSION,Ke as WORKFLOWS_FILENAME,$e as buildOpenApiDocument,ir as buildOpenRpcDocument,Lr as buildSchemaSnapshot,H as capabilitiesUsedBy,ye as companionServiceBinding,to as createCodegenProject,j as createTargetScope,n as describeErrorLevelFindings,C as diagnosticAt,i as diffSchemaSnapshots,_ as discoverAgents,F as discoverAuthApiCalls,D as discoverContainers,b as discoverCrons,Q as discoverFlags,q as discoverFunctions,J as discoverHttpRoutes,Z as discoverHyperdriveCalls,ee as discoverInserts,oe as discoverMaskProcedures,ie as discoverMigrations,de as discoverMutators,me as discoverNondeterministicCalls,le as discoverNotifyCalls,Se as discoverNotifyChannels,xe as discoverNotifyConfig,Ne as discoverQueries,Ce as discoverQueues,Ie as discoverR2sqlCalls,Me as discoverRlsMetadata,Re as discoverRlsProcedures,Fe as discoverSandboxUsage,Pe as discoverSchema,Ve as discoverShapes,We as discoverStorageRulesMetadata,Qe as discoverWorkflows,mo as emitAgents,lo as emitApi,qe as emitApp,So as emitCollections,po as emitContainers,Ao as emitCrons,Co as emitDataModel,Qr as emitDrizzleSchema,Io as emitFunctions,xo as emitInternalApi,er as emitOpenApi,rr as emitOpenApiModule,ar as emitOpenRpc,sr as emitOpenRpcModule,uo as emitScheduler,qr as emitServer,Jr as emitShard,No as emitVectors,no as emitWorkflows,vo as emitWranglerCronTriggers,c as errorAdvisoryNames,l as errorPlatformDiagnosticNames,Mr as evaluateSchemaDrift,Nr as findCodegenConfigFile,ro as findLunoraSolution,vr as findProjectConfigFile,io as findTsconfig,Pr as fingerprintSchemaSources,V as foldCapabilitySignals,d as formatAdvisories,Vr as generateSdk,Tr as indexReferencesOf,Je as isD1GlobalTable,Xe as isHyperdriveGlobalTable,L as isTestPath,Ro as isTypedSchema,f as lintSchema,M as listLunoraSourceFiles,lr as loadProjectConfig,k as mayReadCapabilityContext,Fr as parseSchemaSnapshot,mr as platformMatrixIds,gr as projectConfigCandidatePaths,be as readBoundServiceBindings,Ge as readDevServiceBindings,Ae as readPackageDependencies,Sr as readProjectConfigLiterals,xr as readProjectLazyFunctions,Er as readProjectSecurityHeaders,pr as readProjectTarget,Ue as readServiceBindings,Wr as redact,ao as refreshCodegenProject,nr as resolveCodegenTarget,Be as resolveServiceBindings,Ir as runCodegen,yr as schemaFromIr,zr as secretKindOf,a as serializeSchemaSnapshot,S as sortedUniqueNames,W as sourceCapabilitySignals,m as toAdvisorContext,so as tsconfigFingerprint,Ur as validatorIrToJsonSchema};
@@ -0,0 +1,57 @@
1
+ import{existsSync as K,readFileSync as Ie,statSync as fi,realpathSync as To,mkdirSync as vt,writeFileSync as Co,rmSync as Ee,readdirSync as vs}from"node:fs";import{dirname as Se,join as E,relative as xe,sep as Es,basename as Ss,resolve as pi}from"node:path";import{performance as Vt}from"node:perf_hooks";import{RUNTIME_LINTS as Oo,STATIC_LINTS as ko,runAdvisor as Ro}from"@lunora/advisor";import{LunoraError as F}from"@lunora/errors";import{serializeSchemaSnapshot as Lo}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Fo}from"./formatAdvisories-Bue5tbp6.mjs";import{Node as r,SyntaxKind as u,Project as Et,VariableDeclarationKind as xs,ts as T}from"ts-morph";import{listLunoraSourceFiles as b,lunoraRelativePath as C,declarationLineOf as gi,collectCallRows as R,descendantsOfKind as S,bindingKeyName as fe,findObjectProperty as V,collectSecurityCallRows as Do,propertyInitializer as M,listSecurityScanFiles as Ue,objectLiteralFromCallbackBody as mi,limitNameOf as hi,optionsObjectLiteral as vi,handlerOf as _o,memberAccessOf as ys,chainRootOf as St,unwrapExpression as v,collectNodeRows as ce,isConstDeclaration as J,outermostValueWrapper as O,isWriteTarget as Te,isSameNode as P,returningFunctionOf as Xt,walkChain as Mo,staticNumberValue as Ei,RUN_METHODS as As,functionReferenceSegments as Ko,isTestPath as $o,isFunctionLike as pe,functionKeyOf as Si,withSourceListMemo as zo}from"./isTestPath-DJeZ18i9.mjs";import{j as se,h as ee,c as N,a as bs,w as Ns,k as Bo,d as $,l as Vo,b as xi,f as Wo,m as Uo,g as Jt,i as jo}from"./attribution-B8xa6AeK.mjs";import{i as Y,a as Ne,r as qo,b as Ho,c as yi,d as Go,s as je,e as Yo,f as Qo,g as Xo}from"./ip-reads-D8rPYtZ6.mjs";import{e as Z,f as Jo,m as Ai,b as xt,g as yt,E as bi,C as Ni,d as wi,h as Zo,j as ea,a as ta}from"./context-root-CO8PbZi5.mjs";import{a as k,i as Pi,c as le,d as Ii,e as Ti,f as sa,b as na,g as ia,h as ra}from"./classify-procedure-call-BK_MMoue.mjs";import{a as y,s as ws}from"./property-name-7cBlgK_O.mjs";import{b as oa,a as Ci}from"./module-specifiers-BctA0m_p.mjs";import{r as At,s as aa}from"./parse-validator-BisfC8bR.mjs";import ca from"./discoverAuthApiCalls-DcvsgL5u.mjs";import{i as z,r as Oi}from"./database-calls-Cug60vT9.mjs";import{i as Zt,p as ki,w as la,d as da}from"./index-BwLaIVqA.mjs";import ua from"./discoverHyperdriveCalls-B--Nvx36.mjs";import{PROJECT_CONFIG_FILENAMES as fa,findProjectConfigFile as Ri,findCodegenConfigFile as pa}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{contextPropertiesRead as ga,createTargetScope as ma,fileWiresRequestSecretTool as ha,discoverFeatureUsage as va}from"./capabilitiesUsedBy-BcDkRoOu.mjs";import{diagnosticAt as Ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Ps,a as lt,s as Li,d as Ea}from"./index-CQuAXbal.mjs";import{MUTATORS_FILENAME as Sa,isDefineMutatorCallee as xa,mutatorServerImplOf as ya,discoverMutators as Aa}from"./MUTATORS_FILENAME-SLAN2VXq.mjs";import ba from"./discoverNondeterministicCalls-MeKjo_UX.mjs";import{discoverNotifyConfig as Na,discoverNotifyCalls as wa}from"./ALL_NOTIFY_CHANNELS-DI0zmZGs.mjs";import Pa from"./discoverR2sqlCalls-DHvclvkv.mjs";import Ia from"./discoverRlsProcedures-CUfhUqfY.mjs";import{s as Is,n as Ta}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Ca,redact as Oa,isHeuristicSecretKind as ka,isSecretishName as Ra}from"./redact-Cy14LEnc.mjs";import{r as Fi,p as La,c as Fa,a as Da,e as _a,d as Ma}from"./project-config-file-DR7xrrNB.mjs";import{a as tt,d as Ka,r as $a}from"./modules-isOWiSYI.mjs";import{WORKFLOWS_FILENAME as za,discoverWorkflows as Ba}from"./WORKFLOWS_FILENAME-Dtxo_XBw.mjs";import{r as Va}from"./json-data-Chfs2Cz5.mjs";import{a as Wa,I as Ua,g as ja,G as Di,d as qa,i as Ha}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as Ga}from"./createCodegenProject-C4XuJSap.mjs";import{findTsconfig as p0,refreshCodegenProject as g0,tsconfigFingerprint as m0}from"./createCodegenProject-C4XuJSap.mjs";import{wranglerString as Ya,wranglerValue as Qa,companionName as Xa,COMPANION_FILES as Ja}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as Za,usedCapabilities as ec}from"./CAPABILITY_PROBES-DCzOjTN7.mjs";import{isD1GlobalTable as _i,isHyperdriveGlobalTable as Mi}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as tc}from"./AGENTS_FILENAME-BSW65Q9R.mjs";import{discoverContainers as sc}from"./CONTAINERS_FILENAME-Dy3qWGfI.mjs";import nc from"./discoverCrons-MpIC14pg.mjs";import{discoverEnv as ic}from"./ENV_FILENAME-DFx_jlpa.mjs";import Ki from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as rc}from"./QUEUES_FILENAME-CVkpGqoY.mjs";import{discoverSandboxUsage as oc}from"./discoverSandboxUsage-CdrJNRFd.mjs";import{resolveServiceBindings as ac}from"./companionServiceBinding-BZjm486n.mjs";import cc from"./discoverStorageRulesMetadata-D_pYyr1i.mjs";import{resolveCodegenTarget as Fe,gatePlatformFeatures as lc,needsCloudflareModuleWalk as dc,readTargetDiagnostics as uc,vectorizeDimensionDiagnostics as fc,liveStreamsDeliveryAuthorizationDiagnostic as pc,socketRoutesDeliveryAuthorizationDiagnostic as gc,studioPlatformFor as mc,platformFeatureAvailable as hc,gateAdminTokenRevocation as vc}from"./DEFAULT_TARGET-CnglMKg_.mjs";import{i as Ec}from"./schema-BgM8A3XV.mjs";import{b as $i,e as Sc}from"./shard-BbYT2omp.mjs";import{e as xc,a as yc}from"./server-Dfxmm5Zw.mjs";import{emitDataModel as Ac}from"./emitDataModel-Cen7mAmM.mjs";import{i as bc,b as Nc,e as wc,d as Pc,f as Ic,c as Tc}from"./unwrap-handler-return-BnsKyz9W.mjs";import Cc from"./discoverHttpRoutes-BtMgsfzG.mjs";import Oc from"./discoverInserts-Dx7Lxey3.mjs";import{e as zi}from"./exported-procedure-chains-ej9ozyZB.mjs";import kc from"./discoverMigrations-DaBdK1Bv.mjs";import gn from"./discoverQueries-BlhMsXuk.mjs";import Rc from"./discoverRlsMetadata-CO-pRHOx.mjs";import Lc from"./discoverSchema-CL9PLdOu.mjs";import{discoverShapes as Fc}from"./SHAPES_FILENAME-Cf4sum4C.mjs";import{i as Dc}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as _c,emitApp as Mc}from"./emitApp-BJxszWDO.mjs";import{readJsonSync as Kc}from"@visulima/fs";import{indexReferencesOf as $c,buildSchemaSnapshot as zc}from"./SchemaSnapshotParseError-CV7mmuPi.mjs";import{buildOpenApiDocument as Bc,emitOpenApiModule as Vc}from"./buildOpenApiDocument-C3zlve6K.mjs";import{buildOpenRpcDocument as Wc,emitOpenRpcModule as Uc}from"./OPENRPC_VERSION-DkWde9eh.mjs";import{w as jc,u as qc,v as Hc,t as Gc,x as Yc}from"./shard-runtime-G5mZQjY0.mjs";import{emitCollections as Qc,emitSeed as Xc,emitApi as Jc,emitInternalApi as Zc}from"./emitApi-lwadq5G7.mjs";import{emitCrons as el,emitScheduler as tl,emitAdminRevocations as sl,emitShardRegistry as nl,emitDurableObjects as il,emitVectors as rl,emitWranglerCronTriggers as ol}from"./emitCrons-CCRKs482.mjs";import al from"./emitDrizzleSchema-lRoq3OJs.mjs";import{LAZY_FUNCTION_DIRECTORY as Bi,emitFunctions as cl,emitLazyFunctionModules as ll}from"./emitFunctions-ppMX7E3X.mjs";const dl=(e,t=!1)=>{if(e.length===0)return"";const s=qa(t),n=e.map(c=>{if(Wa(c.exportName,"live stream export name"),!Ua.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(d=>{ja(d.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${d.name}"]`,p=`LiveTopicRef<LiveTopicPayload<${f}>>`,g=JSON.stringify(c.id);if(d.fields.length===0)return` ${d.name}: (): ${p} => ({ __lunoraLive: ${g}, topic: ${JSON.stringify(d.name)} }),`;const h=d.fields.map(x=>`\${encodeURIComponent(key.${x})}`).join(":");return` ${d.name}: (key: LiveTopicKey<${f}>): ${p} => ({
2
+ __lunoraLive: ${g},
3
+ topic: \`${d.name}:${h}\`,
4
+ }),`});return` ${c.exportName}: {
5
+ ${l.join(`
6
+ `)}
7
+ },`}),a=e.some(c=>c.topics.some(l=>l.fields.length>0))?"LiveTopicKey, LiveTopicPayload, LiveTopicRef":"LiveTopicPayload, LiveTopicRef";return`${Di}import type { ${a} } from "${s.server}";
8
+
9
+ ${n.join(`
10
+ `)}
11
+
12
+ /**
13
+ * A typed reference to each declared live topic, grouped by the stream's export name:
14
+ * \`live.posts.post({ postId })\`. Pass one to \`ctx.live.publish(ref, payload)\` on the server, or to a
15
+ * live-topic hook in the browser. A reference is plain data and carries no server code.
16
+ */
17
+ export const live = {
18
+ ${i.join(`
19
+ `)}
20
+ };
21
+ `},Vi=new Set(["delete","get","head","options","patch","post","put"]),ul=new Set(["handler","stream"]),fl=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,mn=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),pl=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Vi.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()}},gl=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)||Vi.has(n.getName()))break;s=n.getExpression()}return pl(s)},ml=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(mn.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&mn.has(s.getText()))return!0}return!1},hl=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!ul.has(n.getName()))return;const i=gl(s);if(!i||!fl.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&ml(o);return{exportName:ee(e)??e.getName(),file:t,line:gi(e),method:i.method,path:i.path,usesGuard:a}},vl=(e,t)=>{const s=[];for(const n of se(e)){const i=hl(n,t);i&&s.push(i)}return s},El=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vl(i,C(t,n)))}return s},Sl=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Z(e.getExpression(),["ai"]),xl=(e,t)=>{if(!Sl(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Y(s)||Ne(s)))return{scope:N(e),file:t,line:e.getStartLineNumber()}},yl=(e,t)=>R(e,t,xl),Al=new Set(["generateText","streamText"]),bl=new Set(["messages","prompt","system"]),Nl=[{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"]}],wl=(e,t)=>Nl.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),Pl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Jo(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&wl(i,s));return n===void 0?void 0:`${n}.${s}`},Il=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=Pl(t);if(s!==void 0)return s}},Tl=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=fe(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Cl=e=>{if(qo(e))return!0;const t=Tl(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},Ol=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!bl.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&Cl(s))return!0}return!1},kl=(e,t)=>{const s=[];for(const n of S(e,u.CallExpression)){const i=k(n.getExpression());if(i===void 0||!Al.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(k(c.getExpression())==="tool"&&(a=Il(c),a!==void 0))break;a!==void 0&&s.push({scope:N(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Ol(o)})}return s},Rl=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...kl(i,C(t,n)))}return s},Ll=e=>Z(e,["fetch"]),Fl=(e,t)=>{if(!Ll(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Y(s)))return{scope:N(e),file:t,line:e.getStartLineNumber()}},Dl=(e,t)=>R(e,t,Fl),Ts=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=At(s.getExpression());return n===void 0||Ts(n,t)})}finally{t.delete(e)}},_l=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=V(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:At(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Ts(i)}},Ml=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)?At(o):void 0;a===void 0?s=!0:(t.push(a),s||=Ts(a))}n=i.getExpression()}return{objects:t,opaque:s}},Cs=(e,t)=>t?Ml(t):_l(e),Wi=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=At(s.getExpression());return n===void 0?[]:Wi(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Kl=e=>e.flatMap(t=>Wi(t,new Set)),$l=new Set(["check","length","max"]),es=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($l.has(s.getName()))return!0;t=n}},ts=e=>oa(e)||e==="@lunora/values",zl=e=>{const t=new Set(["v"]);for(const s of Pi(e,"v",ts))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&ts(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Bl=(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},Vl=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Wl=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&ts(t.getFirstAncestorByKindOrThrow(u.ImportDeclaration).getModuleSpecifierValue())),Os=(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 Vl(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Wl(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Ul=(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)},jl=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},ql=e=>r.isReturnStatement(e)?e.getExpression():void 0,Hl=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(u.ReturnStatement).filter(t=>jl(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=ql(t);return s?[s]:[]}),Ui=(e,t)=>{if(Os(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Ui(e.getExpression(),t)},Gl=(e,t)=>{const s=Ul(e.getExpression(),e.getSourceFile());if(!s)return[];const n=es(e),i=new Set(Hl(s).map(o=>Ui(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Os(o,t);return a===void 0?[]:[{bounded:es(o)||n&&i.has(o),factory:a}]})},Yl=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Os(s,t),i=n===void 0?[]:[{bounded:es(s),factory:n}];return r.isCallExpression(s)?[...i,...Gl(s,t)]:i}),Ql=(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=Yl(a,t),l=y(o);c.some(d=>d.factory==="any")?s.push(l):c.some(d=>d.factory==="string"&&!d.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Xl=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=le(n);if(i?.visibility!=="public")return;const{objects:o}=Cs(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Ql(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:ee(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Jl=(e,t)=>{const s=[],n=zl(e),i={destructured:Bl(e,n),namespaces:n};for(const o of se(e)){const a=Xl(o,t,i);a&&s.push(a)}return s},Zl=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Jl(i,C(t,n)))}return s},Wt=e=>e?.getKind()===u.TrueKeyword,ed=e=>e?.getKind()===u.FalseKeyword,td=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,sd=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),nd=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&k(t.getExpression())==="scim"),id=e=>e!==void 0&&r.isCallExpression(e)&&sd.has(k(e.getExpression())??""),rd=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),od=e=>{const t=M(e,"advanced"),s=M(e,"emailAndPassword"),n=M(e,"session");return{analyzable:!0,disableCsrfCheck:Wt(M(t,"disableCSRFCheck")),emailPasswordEnabled:Wt(M(s,"enabled")),requireEmailVerification:Wt(M(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:nd(M(e,"plugins"))&&id(M(e,"database")),secureCookiesDisabled:ed(M(t,"useSecureCookies")),sessionFreshAgeZero:td(M(n,"freshAge")),trustedOriginsWildcard:rd(M(e,"trustedOrigins"))}},ad=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),cd=(e,t)=>{if(k(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?od(s):ad();return{scope:N(e),file:t,line:e.getStartLineNumber(),...i}},ld=(e,t)=>Do(e,t,cd),dd=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Ai(e.getExpression(),t.matchReceiver)?s:void 0},ud=(e,t,s)=>{const n=dd(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex],o=a=>s.scope==="identity"?yi(a)||Go(e,a):Ne(a);if(!(!i||!Y(i)||o(i))&&!(s.requireUnmodifiedReach===!0&&!Ho(i)))return{scope:N(e),file:t,line:e.getStartLineNumber(),method:n}},bt=(e,t,s)=>R(e,t,(n,i)=>ud(n,i,s)),fd=new Set(["content","pdf","scrape","screenshot"]),pd=(e,t)=>bt(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:fd}),gd=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),md=new Set(["RateLimiter"]),hd=new Set(["extend"]),hn="lunora",vd=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ji=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=y(i);t.push(o),i.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},ss=e=>e&&r.isObjectLiteralExpression(e)?ji(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Ed=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&mi(t.getBody());return s?ji(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Sd=(e,t)=>{const s=[];for(const n of S(e,u.CallExpression)){const i=k(n.getExpression());i!==void 0&&(gd.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...ss(n.getArguments()[0])}):hd.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Ed(n.getArguments()[0])}))}for(const n of S(e,u.NewExpression)){const i=k(n.getExpression());i===void 0||!md.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...ss(n.getArguments()[0])})}return s},xd=e=>{for(const t of vd){const s=E(e,t);if(!K(s))continue;const n=new Et({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Ie(s,"utf8")),i=[];for(const o of S(n,u.CallExpression))k(o.getExpression())===hn&&i.push({callee:hn,file:t,line:o.getStartLineNumber(),...ss(o.getArguments()[0])});return i}return[]},yd=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ue(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Sd(o,n))}return s.push(...xd(Se(t))),s},vn="ctx.containers.",Ad=e=>{if(!e.startsWith(vn))return!1;const t=e.slice(vn.length);return t.length>0&&!t.includes(".")},bd=(e,t)=>bt(e,t,{argIndex:0,scope:"identity",matchReceiver:Ad,methods:new Set(["get"])}),Nd=new Set(["allow","deny","setAllowed"]),wd=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=V(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},Pd=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!wd(e)))return{detail:"enableInternet: true",scope:N(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Id=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Nd.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:N(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Td=(e,t)=>Pd(e,t)??Id(e,t),Cd=(e,t)=>R(e,t,Td),Od=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if(z(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&z(s.getExpression())?s.getName():void 0},kd=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&z(s)?1:0]},Rd=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ld=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=>Rd.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Fd=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return R(e,t,(i,o)=>{const a=Od(i);if(a===void 0)return;const c=Ld(kd(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:N(i),table:a}})},Dd=new Set(["defineExportSink","r2Sink","webhookExportSink"]),_d=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Dd.has(s)?s:void 0},Md=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=y(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(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Kd=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ue(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of S(o,u.CallExpression)){const c=_d(a);if(c===void 0)continue;const l=a.getArguments()[0],d=l&&r.isObjectLiteralExpression(l)?Md(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},$d=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),zd=new Set(["dbRateLimit","rateLimit"]),Bd=e=>{const t=vi(e);if(!t)return!1;const s=V(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===u.TrueKeyword},Vd=(e,t)=>{const s=k(e.getExpression());if(s===void 0)return;const n=$d.get(s);if(n!==void 0)return{callee:s,scope:N(e),failOpen:Bd(e.getArguments()[n]),file:t,limitName:zd.has(s)?hi(e):"",line:e.getStartLineNumber()}},Wd=(e,t)=>R(e,t,Vd),Ud=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=le(t);if(s?.kind!=="query")return;const n=_o(t,s.receiver);return n?{exportName:ee(e)??e.getName(),handler:n}:void 0},En=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},jd=e=>{const t=En(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=En(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},qd=(e,t)=>{const s=[];for(const n of xt(e.handler,"flags"))s.push({callee:jd(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Hd=(e,t)=>{const s=[];for(const n of se(e)){const i=Ud(n);i&&s.push(...qd(i,t))}return s},Gd=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hd(i,C(t,n)))}return s},Yd=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Z(e.getExpression(),["flags"]),Qd=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},Xd=(e,t)=>{if(!Yd(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Qd(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:N(e),file:t,key:i,line:e.getStartLineNumber()}},Jd=(e,t)=>R(e,t,Xd),Zd=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},eu=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},tu=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=C(t,n);for(const a of S(i,u.CallExpression))Zd(a)&&s.push({file:o,indexName:eu(a),line:a.getStartLineNumber()})}return s},su=new Set(["delete","get","head","options","patch","post","put"]),nu=new Set(["handler","stream"]),iu=new Set(["runAction","runMutation"]),ru=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),ze=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,qi=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(fe(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Sn=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:qi(s,"ctx")},xn=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:qi(s,"request")},yn=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(u.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(iu.has(a)&&ze(c,t))return a;if(ru.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&ze(c.getExpression(),t))return`db.${a}`}},An=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(u.PropertyAccessExpression))if(n.getName()==="auth"&&ze(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(u.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!ze(n.getInitializer(),t))){for(const o of i.getElements())if(fe(o)==="auth")return!0}}return!1},ou=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,au=(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"&&ze(n.getExpression(),t)},cu=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(u.StringLiteral).map(t=>t.getLiteralText())],Hi=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:cu(s)},lu=(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)?Hi(t,a.getText()):[]}return[]},du=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=Hi(s,t.getText());return n.length>0?n:lu(t,s)},bn=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(u.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>au(i,t)&&du(i).some(o=>ou.test(o)))},uu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!nu.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(su.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},fu=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Zt(e.getArguments()[0]),l=c&&Sn(c,!0);if(!c||l===void 0||bn(c,xn(c,!0)))return;const d=yn(c,l);return d===void 0?void 0:{scope:N(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:An(c,l),sideEffect:d}}const n=uu(e);if(n===void 0)return;const i=Zt(e.getArguments()[0]),o=i&&Sn(i,!1);if(!i||o===void 0||bn(i,xn(i,!1)))return;const a=yn(i,o);return a===void 0?void 0:{scope:N(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:An(i,o),sideEffect:a}},pu=(e,t)=>R(e,t,fu),gu=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),mu=new Set(["append","set"]),Gi=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Nn=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(n=>gu.has(k(n.getExpression())??"")&&Qo(n,t)),hu=(e,t)=>{if(Nn(e,t))return!0;const s=je(e);return s!==void 0&&Nn(s,t)},ns=(e,t)=>Yo(e,t)&&!hu(e,t),vu=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=je(e);return t!==void 0&&r.isNewExpression(t)&&k(t.getExpression())==="Headers"},dt=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=je(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},ks=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&ns(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Gi(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();ns(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=dt(n.getExpression());i!==void 0&&ks(i,t,s)}},Yi=(e,t)=>{const s=dt(e);if(s===void 0)return;const n=V(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=dt(n.getInitializer());i!==void 0&&ks(i,"response-init",t)},Eu=(e,t)=>{const s=k(e.getExpression());if(s==="Response")Yi(e.getArguments()[1],t);else if(s==="Headers"){const n=dt(e.getArguments()[0]);n!==void 0&&ks(n,"headers-ctor",t)}},Su=(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"){Yi(e.getArguments()[1],t);return}if(mu.has(n)&&vu(i)){const o=e.getArguments()[1];o!==void 0&&ns(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Gi(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},xu=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))Eu(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))Su(s,t)},yu=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Zt(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 xu(n,{scope:N(e),relativePath:t,requestName:o.getText(),rows:a}),a},Au=(e,t)=>{const s=[];for(const n of S(e,u.CallExpression))s.push(...yu(n,t));return s},bu=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Au(i,C(t,n)))}return s},Nu=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token","tokenHash"]),wu=new Set(["__proto__","email","exp","expiresAtMs","iat","name","nbf","orgId","role","roles","sub","teamId","userId"]),Ut=32,Pu=/^[A-Z_]\w{0,63}$/i,Iu={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},Tu=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Cu=(e,t)=>{const s=v(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return v(e.getDescendantsOfKind(u.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},Ou=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(y(s));if(!r.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=v(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),ku=new Set(["durable"]),Ru=new Set(["rollback"]),Qi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Lu="defineApp",De="app",wn=(e,t)=>e.getDescendantsOfKind(u.PropertyAssignment).some(s=>y(s)===De&&s.getInitializer()?.getText()===t)||t===De&&e.getDescendantsOfKind(u.ShorthandPropertyAssignment).some(s=>y(s)===De),Fu=e=>{if(e===void 0||!fa.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&y(e)===De;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return y(t)===De;if(r.isVariableDeclaration(t))return wn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&wn(e.getSourceFile(),s)},Du="AppBuilder",Xi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},Ji=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Du&&s.getDeclarations().some(n=>Xi(n))},_u=e=>e.getText()===Lu&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Xi(t)),Rs=(e,t,s=new Set)=>{const n=St(t);if(n===void 0||!r.isIdentifier(n))return!1;if(_u(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return Fu(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Rs(e,a.getInitializer(),s)}}return!1},Zi=(e,t)=>{const s=ys(t.getExpression());return s?.member==="deliveryAuthorization"&&(Rs(e,s.object)||Ji(s.object))},Mu=new Map([["defineContainer",{keys:Tu,signal:"containerEgressPolicy"}],["defineStep",{keys:Ru,signal:"workflowRollback"}],["stream",{keys:ku,signal:"durableStreams"}]]),Ku=(e,t)=>{const s=Mu.get(Qi(t));if(s!==void 0)return t.getArguments().some(n=>Ou(Cu(e,n),s.keys))?s.signal:void 0},$u=(e,t)=>Iu[Qi(t)]??(Zi(e,t)?"deliveryAuthorization":void 0),zu=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of b(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=ga(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=S(o,u.CallExpression);for(const c of a){const l=Ku(o,c)??$u(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>Ii(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Et({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Ie(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(u.CallExpression).some(o=>Zi(i,o))}return n},Be={claims:[],diagnostics:[]},ae=e=>({claims:[],diagnostics:[e]}),Nt=e=>r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)?Nt(e.getExpression()):e,er=e=>{if(r.isSpreadAssignment(e))return!0;const t=e.getNameNode();return r.isComputedPropertyName(t)&&ws(t)===void 0},we=e=>e.getProperties().some(t=>er(t)),tr=(e,t)=>e.getProperties().findLast(s=>!r.isSpreadAssignment(s)&&y(s)===t),sr=(e,t)=>{const s=tr(e,t);return r.isPropertyAssignment(s)?s.getInitializer():void 0},nr=(e,t)=>{const s=sr(e,t);return s!==void 0&&Nt(s).getKind()===u.FalseKeyword},Ve="unreadable",Ls=(e,t)=>{const s=tr(e,t);if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer()??Ve:r.isShorthandPropertyAssignment(s)?s.getNameNode():Ve},Pn=e=>{if(e===void 0||!r.isBlock(e))return e;const t=e.getStatements().filter(s=>r.isReturnStatement(s));return t.length===1?t[0]?.getExpression():void 0},ue=(e,t=0)=>{if(t>4)return;const s=Nt(e);if(r.isObjectLiteralExpression(s))return s;if(r.isArrowFunction(s)||r.isFunctionExpression(s)){const c=Pn(s.getBody());return c===void 0?void 0:ue(c,t+1)}if(!r.isIdentifier(s))return;const n=s.getParent(),i=r.isShorthandPropertyAssignment(n)?n.getValueSymbol():s.getSymbol(),o=i?.isAlias()?i.getAliasedSymbol():i,[a]=o?.getDeclarations()??[];if(r.isVariableDeclaration(a)){const c=a.getInitializer();return c===void 0?void 0:ue(c,t+1)}if(r.isFunctionDeclaration(a)){const c=Pn(a.getBody());return c===void 0?void 0:ue(c,t+1)}},Bu=e=>{if(e===void 0)return;const t=Nt(e);if(r.isArrayLiteralExpression(t))return"string";if(!(!r.isStringLiteral(t)&&!r.isNoSubstitutionTemplateLiteral(t)))switch(t.getLiteralValue()){case"boolean":return"boolean";case"date":case"string":return"string";case"number":return"number";default:return}},Vu=e=>nr(e,"returned"),Wu=(e,t)=>{if(!Pu.test(e))return{reason:`\`${e}\` is not an identifier of at most 64 characters`};if(wu.has(e)||Nu.has(e))return{reason:`\`${e}\` is reserved or secret-bearing, so the session never forwards it`};const s=ue(t);if(s===void 0||we(s))return{reason:`\`${e}\` is not a literal field definition`};const n=Bu(sr(s,"type"));return n===void 0?{reason:`\`${e}\` is not a scalar (string, number, boolean or date) column`}:{claim:{name:e,type:n,writable:!nr(s,"input")}}},Uu=e=>{if(r.isSpreadAssignment(e))return;if(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e))return{reason:`\`${e.getName()}\` is a method or accessor, not a field definition`};const t=r.isPropertyAssignment(e)?y(e):e.getName(),s=r.isPropertyAssignment(e)?e.getInitializer():e.getNameNode(),n=s===void 0?void 0:ue(s);if(!(n!==void 0&&!we(n)&&Vu(n)))return s===void 0?{reason:`\`${t}\` has no initializer`}:Wu(t,s)},ju=e=>{const t=[],s=[];for(const n of e.getProperties()){const i=Uu(n);i?.claim!==void 0?t.push(i.claim):i!==void 0&&s.push(`${i.reason??"the entry cannot be a claim"}; it is not added to ctx.auth`)}return t.length>Ut&&s.push(`${t.length.toString()} claims declared; the first ${Ut.toString()} are forwarded, the rest are not`),{claims:t.slice(0,Ut),diagnostics:s}},qu=e=>{if(we(e))return ae("`user` has a spread or a computed key, so the user columns cannot be read");const t=Ls(e,"additionalFields");if(t===void 0)return Be;const s=t===Ve?void 0:ue(t);return s===void 0||we(s)?ae("`user.additionalFields` is not an object literal, so the user columns cannot be read"):ju(s)},Hu=e=>{if(we(e))return ae("the auth options contain a spread or a computed key, so the user columns cannot be read");const t=Ls(e,"user");if(t===void 0)return Be;const s=t===Ve?void 0:ue(t);return s===void 0?ae("`user` is not an object literal, so the user columns cannot be read"):qu(s)},Gu=(e,t)=>{const s=t.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="auth")return!1;const n=s.getExpression();return Rs(e,n)||Ji(n)},Yu=e=>{const t=e.getProperties(),s=t.findLastIndex(n=>!r.isSpreadAssignment(n)&&y(n)==="options");return t.some((n,i)=>i>s&&er(n))},Qu=e=>{const[t]=e.getArguments();if(t===void 0)return Be;if(!r.isObjectLiteralExpression(t))return ae(".auth() is not called with an object literal, so its user columns cannot be read");const s=Ls(t,"options");if(s===void 0)return we(t)?ae("the .auth() argument has a spread or a computed key, so its options cannot be read"):Be;if(Yu(t))return ae("a spread or computed key after `options` in .auth() may replace it, so the user columns cannot be read");const n=s===Ve?void 0:ue(s);return n===void 0?ae("`.auth({ options })` does not resolve to an object literal, so the user columns cannot be read"):Hu(n)},ir=(e,t)=>{const s=[];for(const{filePath:o}of Ue(t)){const a=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...S(a,u.CallExpression).filter(c=>Gu(a,c)))}const[n,...i]=s;return n===void 0?Be:i.length===0?Qu(n):ae(`the app builder's .auth() is called ${s.length.toString()} times, so which declaration applies cannot be read`)},rr="identity.ts",Xu=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ci(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Ju=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(u.ImportDeclaration);return n!==void 0&&Ci(n.getModuleSpecifierValue())}return!1},Zu=e=>{if(r.isIdentifier(e))return Xu(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Ju(t)}return!1},ef=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==u.CallExpression||!Zu(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Ce(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=bs(s,"member");a!==void 0&&t.push({exportName:a})}return t},tf=(e,t)=>{const s=E(t,rr);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=ef(n);if(i.length!==0){if(i.length>1)throw Ce(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},or=new Set(["auth","context.auth"]),sf="userId",nf=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(y(s))}return t},rf=(e,t)=>{const s=E(t,rr);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(u.CallExpression)){if(k(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?nf(o):void 0}},of=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return or.has(t.getText())||Z(t,["auth"])?e:void 0},is=(e,t=!1)=>r.isAwaitExpression(e)?is(e.getExpression(),!0):r.isParenthesizedExpression(e)||r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isTypeAssertion(e)||r.isNonNullExpression(e)?is(e.getExpression(),t):{awaited:t,value:e},ar=e=>{if(e===void 0)return;const{awaited:t,value:s}=is(e);if(!t||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||n.getName()!=="getIdentity")return;const i=n.getExpression();return or.has(i.getText())||Z(i,["auth"])?s:void 0},cr=e=>{if(r.isPropertyAccessExpression(e))return e.getName();const t=v(e.getArgumentExpression());return r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0},af=e=>{if(!r.isPropertyAccessExpression(e)&&!r.isElementAccessExpression(e)||Te(e))return;const t=e.getExpression();return of(t)!==void 0||ar(t)!==void 0?cr(e):void 0},rs=(e,t,s,n)=>({declared:t===sf||n.has(t),file:s,key:t,line:e.getStartLineNumber(),scope:N(e)}),In=(e,t,s)=>{const n=af(e);return n===void 0?void 0:rs(e,n,t,s)},cf=(e,t,s)=>{if(ar(e.getInitializer())===void 0)return[];const n=e.getNameNode();return r.isObjectBindingPattern(n)?n.getElements().filter(i=>i.getDotDotDotToken()===void 0).flatMap(i=>{const o=ws(i.getPropertyNameNode()??i.getNameNode());return o===void 0?[]:[rs(i,o,t,s)]}):!r.isIdentifier(n)||!J(e)?[]:n.findReferencesAsNodes().filter(i=>i!==n).flatMap(i=>{const o=O(i),a=o.getParent();if(!r.isPropertyAccessExpression(a)&&!r.isElementAccessExpression(a)||Te(a))return[];const c=a.getExpression()===o?cr(a):void 0;return c===void 0?[]:[rs(a,c,t,s)]})},lf=(e,t)=>{const s=rf(e,t);if(s===void 0)return[];const n=ir(e,t).claims.filter(o=>!o.writable).map(o=>o.name),i=new Set([...s,...n]);return[...ce(e,t,u.PropertyAccessExpression,(o,a)=>In(o,a,i)),...ce(e,t,u.ElementAccessExpression,(o,a)=>In(o,a,i)),...ce(e,t,u.VariableDeclaration,(o,a)=>cf(o,a,i))]},df=(e,t)=>{if(k(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=M(s,"key");if(!(!n||!Y(n)||Ne(n)))return{scope:N(e),file:t,line:e.getStartLineNumber()}},uf=(e,t)=>R(e,t,df),ff=new Set(["delete","get","getRaw","getWithMetadata","put"]),pf=(e,t,s=[])=>{const n=bt(e,t,{argIndex:0,scope:"identity",matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ff});return Ns(n,s)},gf=new Set(["queue","send"]),Tn=new Set(["bcc","cc","to"]),mf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!gf.has(t))return;const s=e.getExpression();return Z(s,["mail"])||Z(s,["email"])?t:void 0},hf=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Tn.has(y(t))&&Y(n)&&!Ne(n)}if(!r.isPropertyAssignment(t)||!Tn.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&Y(s)&&!Ne(s)}):!1,vf=(e,t)=>{const s=mf(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!hf(n)))return{scope:N(e),file:t,line:e.getStartLineNumber(),method:s}},Ef=(e,t)=>R(e,t,vf),Sf=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=lt(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 d=lt(l);if(d===void 0)continue;const f=Li(l);f!=="custom"&&i.push({column:d,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},xf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;return n?.receiver?Ps(n.receiver).flatMap(i=>Sf(i,ee(e)??e.getName(),t)):[]},yf=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=C(t,n);for(const a of se(i))s.push(...xf(a,o))}return s},Af=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),lr=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===xs.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!z(s.getExpression())))return{database:s.getExpression(),table:s.getName()}},wt=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!t.has(s.getName()))return;const n=s.getName(),i=s.getExpression(),o=lr(i);if(o!==void 0)return{database:o.database,method:n,table:o.table};if(r.isPropertyAccessExpression(i)&&z(i.getExpression()))return{database:i.getExpression(),method:n,table:i.getName()}},bf=new Set(["replace"]),Nf=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="replace"&&z(t.getExpression())?!0:wt(e,bf)!==void 0},wf=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=V(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Pf=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return xa(s.getExpression())?s:void 0},If=e=>{const t=Pf(e),s=t===void 0?void 0:wf(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?ee(e)??n.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>Nf(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Tf=e=>e.getVariableDeclarations().flatMap(t=>If(t)),Cf=(e,t)=>{const s=E(t,Sa);if(!K(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Tf(n)},Of=new Set(["delete","get","patch"]),kf=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Rf=new Set(["auth","identity","session","user"]),Lf=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),Ff=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!z(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Df=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},_f=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),Mf=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,Kf=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>_f(s.getExpression(),t)&&Mf(s.getThenStatement())),$f=(e,t)=>{for(const s of S(e,u.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Of.has(i))continue;const o=n.getExpression(),a=z(o);if(!(a||r.isPropertyAccessExpression(o)&&z(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},zf=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>yt(St(s))!==void 0)),Bf=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>Lf.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Vf=e=>{for(const t of S(e,u.Identifier))if(kf.has(t.getText()))return!0;return[...Rf].some(t=>xt(e,t).length>0)?!0:zf(e)||Bf(e)},Wf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=le(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=ki(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Ti(n.receiver,"use","rls"),a=Vf(i),c=new Set,l=[];for(const d of S(i,u.CallExpression)){const f=Ff(d);if(f===void 0)continue;const p=Df(d);if(p===void 0||c.has(p)||!Kf(i,p))continue;const g=$f(i,p);g!==void 0&&(c.add(p),l.push({exportName:ee(e)??e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:g,table:f,usesRls:o,visibility:n.visibility}))}return l},Uf=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=C(t,n);for(const a of se(i))s.push(...Wf(a,o))}return s},dr=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?$(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(u.Parameter)?.compilerNode===t.compilerNode},jf=e=>{const t=O(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!Te(s)},qf=e=>{const t=O(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Hf=e=>{const s=O(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!Te(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},ut=e=>{const t=$(e);return t===void 0||Vo(t.getSourceFile())},os=(e,t)=>{const s=O(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=v(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&ut(o);if(dr(St(o),t))return!(r.isPropertyAccessExpression(o)&&bi.has(o.getName()))||r.isExpressionStatement(O(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!ut(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}},nt={kind:"opaque"},Gf={kind:"unreached"},Yf=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},as=e=>{const t=v(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?$(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=Yf(s);return i===void 0||xi(i)?void 0:i}const n=J(s)?v(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},ur=(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(u.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?nt:c===void 0?a.some(l=>l.isRestParameter())?nt:Gf:c.isRestParameter()?nt:{kind:"parameter",parameter:c}},Qf=e=>{const t=O(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=as(s.getExpression());return n===void 0?nt:ur(n,s,t)},Xf=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Jf=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,fr=e=>{const t=O(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=Jf(s);if(n!==void 0)return P(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==u.PlusPlusToken&&s.getOperatorToken()!==u.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=u.FirstAssignment&&i<=u.LastAssignment,a=i===u.QuestionQuestionToken||i===u.BarBarToken||i===u.AmpersandAmpersandToken;return!o&&!a},Zf=4,pr=(e,t,s=0)=>{if(Bo(e))return!0;if(jf(e)){const i=O(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||!Xf.has(c)}if(qf(e)||Hf(e)||fr(e)||os(e,t))return!0;const n=Qf(e);return n?.kind==="unreached"||n?.kind==="parameter"&&ep(n.parameter,s+1)},Cn=new WeakMap,ep=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Cn.get(e.compilerNode);if(n!==void 0)return n;if(t>Zf)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(u.Identifier).every(a=>a===s||a.getText()!==s.getText()||$(a)?.compilerNode!==e.compilerNode||pr(a,void 0,t));return(o||t===0)&&Cn.set(e.compilerNode,o),o},On=new WeakMap,tp=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(u.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(u.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=$(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},sp=(e,t,s)=>{const{context:n,impl:i}=e,o=On.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(u.BindingElement).flatMap(p=>{const g=p.getNameNode();return r.isIdentifier(g)?[g]:[]}),l=new Map(c.map(p=>[p.getText(),p.getParentOrThrow().compilerNode])),d=p=>r.isIdentifier(a)?pr(p,n):!Te(p),f=!tp(i,s)&&c.every(p=>(p.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(u.Identifier).every(p=>{const g=p.getText();if(g==="arguments")return!1;const h=l.get(g);return h===void 0||c.includes(p)||$(p)?.compilerNode!==h?!0:d(p)});return On.set(i.compilerNode,f),f},kn=new WeakMap,np=e=>{let t=kn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=ya(s);return n===void 0?[]:[[n.compilerNode,s]]})),kn.set(e.compilerNode,t)),t},ip=e=>{const t=np(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:ee(n)??n.getName()};return a!==void 0&&sp(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},cs="args",Rn=e=>{if(!r.isIdentifier(e))return!1;if(e.getText()===cs)return!0;const t=$(e);return r.isBindingElement(t)&&t.getDotDotDotToken()===void 0&&fe(t)===cs},_e=e=>{const t=ys(e);if(t!==void 0)return Rn(v(t.object))?t.member:void 0;if(!r.isIdentifier(e))return;const s=$(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=J(i)?v(i.getInitializer()):void 0;return r.isBindingElement(i)&&fe(i)===cs||Rn(o)?fe(s):void 0},rp=new Set(["auth","identity","user"]),op=new Set(["activeOrganization.id","activeOrganizationId","id","organizationId","orgId","subject","userId"]),ls=(e,t=!1)=>{const s=o=>{const a=yt(o);return a===void 0||!rp.has(a[0]??"")?!1:a.length===1?t:op.has(a.slice(1).join("."))},n=v(e)??e;if(s(n))return!0;const i=je(n);return i!==void 0&&s(i)},gr=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=_e(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?je(n):void 0;if(o!==void 0)for(const a of gr(o,t-1))s.add(a)}return s},it=e=>{const t=v(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===u.BarBarToken)return[...it(n),...it(i)];if(s===u.AmpersandAmpersandToken){const l=(d,f)=>{const p=_e(v(d)??d);return p===void 0?[]:it(f).filter(g=>g===p)};return[...l(n,i),...l(i,n)]}if(s!==u.ExclamationEqualsEqualsToken&&s!==u.ExclamationEqualsToken)return[];const o=[],a=_e(v(n)??n),c=_e(v(i)??i);return a!==void 0&&ls(i)&&o.push(a),c!==void 0&&ls(n)&&o.push(c),o},ap=e=>{const t=v(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=v(n.getInitializer());return r.isCallExpression(i)&&sa(i.getExpression(),"defineIdentityGuard")},cp=e=>{if(!ap(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=_e(v(s)??s),o=t.some((a,c)=>c!==n&&(ls(a,!0)||yt(a)?.length===0));return i!==void 0&&o?[i]:[]})},lp=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)},dp=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Ln=(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},up=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),fp=(e,t)=>{const s=new Set;for(const n of S(e,u.IfStatement))if(n.getEnd()<=t&&Ln(n,e)&&lp(n.getThenStatement()))for(const i of it(n.getExpression()))s.add(i);for(const n of S(e,u.CallExpression))if(n.getEnd()<=t&&up(n)&&Ln(n,e))for(const i of cp(n))s.add(i);return s},pp=(e,t)=>{const s=gr(t);if(s.size===0)return!1;const n=e.getFirstAncestor(dp);if(n===void 0)return!1;const i=fp(n,e.getStart());return[...s].every(o=>i.has(o))},gp=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),mp=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),ds=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),mr=e=>e.getNameNode().getDescendantsOfKind(u.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),hp=e=>{const t=O(e),s=t.getParent();if(r.isVariableDeclaration(s))return P(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},vp=e=>{const t=hp(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||J(t)?[t]:void 0:mr(t)},Me=e=>e.isUnion()?e.getUnionTypes().every(t=>Me(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Me(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),ft=(e,t,s)=>{const n=r.isCallExpression(e)?v(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},rt=e=>{const t=v(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(u.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Ep=e=>{const t=r.isCallExpression(e)?v(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&mp.get(s.getText())?.has(t.getName())===!0&&ut(s)},Sp=e=>{const t=Xt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=O(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&ft(n,Ni)?n:void 0},xp=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=O(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:ft(n,gp,t)?n:void 0},yp=(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===u.QuestionQuestionToken||s===u.BarBarToken||s===u.AmpersandAmpersandToken?e:void 0},Ap=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&P(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},Fn=e=>{const t=O(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Ep(s);return xp(s,t)??yp(s,t)??Ap(s,t)??(n?s:Sp(t))},bp=5e4,hr=()=>({inProgress:new Set,verdicts:new Map});class Np{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>bp&&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 wp=8,Pp=8;class Ip{budget;scope;taint;verdicts=hr();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Me(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)?mr(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,d)=>d&&s>=wp?this.budget.cut():(i(l,d?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(O(l),!0,a,0))&&(t===n||!Me(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let g=Fn(o);g!==void 0;g=Fn(o)){if(r.isCallExpression(g)&&this.callbackCompromises(g,n))return!0;o=O(g)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Me(o.getType());if(Te(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const d=vp(o);if(d!==void 0)return d.some(g=>n(g,!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 p=this.nestedReturningFunctionOf(o);return p!==void 0?this.resultCompromises(p,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=O(t).getParent();if(n>=Pp)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===O(t)?this.valueCompromises(i,!1,s,n+1):!ft(i,ds);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||J(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=O(c),d=l.getParent();return!r.isCallExpression(d)||d.getExpression()!==l||this.valueCompromises(d,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>rt(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=ft(t,ds)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=as(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!os(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(os(s,this.scope.context))return!1;const i=as(t.getExpression()),o=i===void 0?void 0:ur(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)||fr(t)||P(Xt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(v(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Xt(t);return P(s,this.scope.impl)?void 0:s}}const Tp=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Cp=e=>{const t=v(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=$(t),n=r.isVariableDeclaration(s)?v(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Op=new Set(["all","allSettled","any","race"]),Dn=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(u.Parameter):void 0,jt=8;class kp{budget=new Np;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=hr();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Ip(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(u.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,jt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(u.Identifier)).some(i=>Wo(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=$(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(u.BindingElement).map(p=>p.getInitializer())].some(p=>p!==void 0&&this.isTaintedValue(p,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(p=>p.compilerNode===t.compilerNode):-1,o=O(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 p=v(a.getExpression());if(!r.isPropertyAccessExpression(p)||!ds.has(p.getName()))return!0;const g=a.getArguments().filter(h=>h!==o);return this.isTaintedValue(p.getExpression(),!0)||g.some(h=>this.isTaintedValue(h,!1))}const c=r.isVariableDeclaration(a)&&J(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,d=l?.getNameNode();if(l===void 0||!r.isIdentifier(d))return!0;const f=this.referencesTo(l,d.getText());return f.length===0||f.some(p=>{const g=O(p),h=g.getParent();return!r.isCallExpression(h)||h.getExpression()!==g||this.isCallSiteTainted(h,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=v(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&ut(i)&&Op.has(n.getName())?v(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(p=>!r.isSpreadElement(p)&&this.isRootedInContext(p,s))}const c=r.isCallExpression(a)?v(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?v(a.getArguments()[0]):void 0,d=l===void 0?void 0:rt(l);return d!==void 0&&d.length>0&&d.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=$(t),i=Dn(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(u.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=v(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&bi.has(i)?!1:i!==void 0&&Ni.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>rt(a)!==void 0)&&(i===void 0||!Tp.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=St(i),c=r.isIdentifier(a)?Dn($(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=rt(i);if(o===void 0)return!Cp(i)&&n(i);const a=v(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=Mo(t,d=>this.callChainVerdict(d,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(dr(i,this.scope.context))return!0;const o=r.isIdentifier(i)?$(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(u.VariableDeclaration):o,c=J(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=xi(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,jt))return!1;if(this.variableDepth>=jt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const _n=new WeakMap,Rp=e=>{const t=_n.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new kp(e);return _n.set(e.impl.compilerNode,s),s},Lp=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Fp=new Set(["insert","insertMany","insertManyUnsafe","patch","replace"]),Dp=new Set(["insert","insertMany","patch","patchMany","replace","upsert","upsertMany"]),st=(e,t)=>e===void 0||!r.isObjectLiteralExpression(e)?[]:t.flatMap(s=>{const n=V(e,s),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;return i===void 0?[]:[i]}),Mn=e=>e!==void 0&&r.isArrayLiteralExpression(e)?e.getElements():[],_p=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Fp.has(t)&&wi(e.getExpression())?t:void 0},Mp=(e,t)=>{const[s]=t.getArguments();if(e==="upsert")return st(s,["create","update"]);if(e==="upsertMany")return st(s,["rows"]).flatMap(i=>Mn(i).flatMap(o=>st(o,["create","update"])));if(e==="patchMany")return(s!==void 0&&r.isArrayLiteralExpression(s)?Mn(s):[s]).flatMap(o=>st(o,["values"]));const n=e==="patch"||e==="replace"?t.getArguments()[1]:s;return n===void 0?[]:[n]},Kp=e=>{const t=e.getExpression(),s=_p(t);if(s!==void 0){const i=s==="patch"||s==="replace"?2:1,o=e.getArguments()[i];return o===void 0?void 0:{documentArguments:[o],method:s}}const n=wt(e,Dp);if(!(n===void 0||!wi(n.database)))return{documentArguments:Mp(n.method,e),method:n.method}},$p=(e,t)=>{if(t!=="insertManyUnsafe"&&t!=="insertMany")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},zp=(e,t)=>{const s=ys(e);return s?.member===t?v(s.object):void 0},Kn=(e,t)=>r.isIdentifier(e)&&$(e)?.compilerNode===t.compilerNode,vr=(e,t,s,n=1)=>{const i=zp(e,s);if(i!==void 0)return Kn(i,t);const o=r.isIdentifier(e)?$(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&fe(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||J(l)&&Kn(v(l.getInitializer()),t))}const a=J(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&vr(a,t,s,n-1)},us=e=>{const t=v(e)??e;return r.isConditionalExpression(t)?[...us(t.getWhenTrue()),...us(t.getWhenFalse())]:[t]},Bp=(e,t,s)=>{const n=[],i=s===void 0?void 0:Rp(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Lp.has(a))continue;const l=us(c).filter(f=>i===void 0?Y(f)&&!Zo(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&vr(c,s.parameter,a),p=l.every(g=>pp(t.call,g));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...p&&{guarded:!0}})}}return n},Vp=e=>{const t=new Map;for(const s of e){const n=t.get(s.field);if(n===void 0)t.set(s.field,s);else{const i={...n};s.ownerScoped!==!0&&delete i.ownerScoped,s.guarded!==!0&&delete i.guarded,t.set(s.field,i)}}return[...t.values()]},Wp=(e,t,s)=>{const n=Kp(e);if(n===void 0)return[];const{method:i}=n,o=n.documentArguments.flatMap(f=>$p(f,i));if(o.length===0)return[];const a=N(e),c=ip(e),l={call:e,method:i,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a},d=o.flatMap(f=>Bp(f,l,c));return i==="upsert"?Vp(d):d},Up=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=R(e,t,(c,l)=>Wp(c,l,d=>i.get(`${l}:${d}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Ns(o,s).map(c=>Uo(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},jp=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),qp=e=>{const t=V(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?Ei(t.getInitializer()):void 0},Hp=(e,t)=>{const s=k(e.getExpression());if(s===void 0||!jp.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?qp(n):void 0;return{callee:s,scope:N(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Gp=(e,t)=>R(e,t,Hp),Yp=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Qp=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Xp=(e,t)=>{const s=e.getArguments()[t];if(!(!s||!r.isObjectLiteralExpression(s)))return ea(V(s,"handler"))},Er=(e,t)=>e.getParameters()[t]?.getNameNode(),Sr=e=>{const t=new Map;for(const s of e){const n=s.getNameNode();r.isIdentifier(n)&&t.set(s.getPropertyNameNode()?.getText()??n.getText(),n.getText())}return t},xr=(e,t)=>e===t||e.startsWith(`${t}.`),yr=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},$n=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)},Ar=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>$n(s));return r.isIdentifier(e)&&$n(e)&&t.push(e),t},Jp=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},Zp=new Set(["every","filter","flatMap","forEach","map","some"]),eg=e=>{const t=Er(e,1);return t&&r.isIdentifier(t)?`${t.getText()}.messages`:t&&r.isObjectBindingPattern(t)?Sr(t.getElements()).get("messages"):void 0},tg=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Zp.has(s.getName())||s.getExpression().getText()!==t)return;const n=e.getArguments()[0];if(!n||!(r.isArrowFunction(n)||r.isFunctionExpression(n)))return;const i=n.getParameters()[0]?.getNameNode();return i&&r.isIdentifier(i)?i.getText():void 0},sg=e=>{const t=eg(e);if(t===void 0)return[];const s=[t];for(const n of e.getDescendantsOfKind(u.ForOfStatement)){if(n.getExpression().getText()!==t)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}for(const n of e.getDescendantsOfKind(u.CallExpression)){const i=tg(n,t);i!==void 0&&s.push(`${i}.body`)}return s},ng=e=>{const t=Er(e,0);if(t&&r.isIdentifier(t))return{params:void 0,receiver:t.getText(),runCallees:[]};if(!t||!r.isObjectBindingPattern(t))return{params:void 0,receiver:void 0,runCallees:[]};const s=Sr(t.getElements());return{params:s.get("params"),receiver:void 0,runCallees:[...s].filter(([n])=>As.has(n)).map(([,n])=>n)}},ig=(e,t,s)=>{const n=s.receiver===void 0?[]:[`${s.receiver}.params`],i=t==="workflow"?n:sg(e),o=new Set(t==="workflow"&&s.params!==void 0?[s.params]:[]),a=c=>yr(c).some(l=>i.some(d=>xr(l.getText(),d)))?!0:Ar(c).some(l=>o.has(l.getText()));for(const c of e.getDescendantsOfKind(u.VariableDeclaration)){const l=c.getInitializer();if(l&&a(l))for(const d of Jp(c))o.add(d)}return{names:o,prefixes:i}},rg=(e,t)=>yr(e).some(s=>t.prefixes.some(n=>xr(s.getText(),n)))?!0:Ar(e).some(s=>t.names.has(s.getText())),og=e=>{const t=Ko(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},ag=(e,t,s)=>{const n=ng(e),i=ig(e,t,n),o=new Set([...n.receiver===void 0?[]:[n.receiver],...i.prefixes.filter(l=>l.endsWith(".body")).map(l=>l.slice(0,-5))]),a=new Set(n.runCallees),c=[];for(const l of e.getDescendantsOfKind(u.CallExpression)){const d=l.getExpression(),f=r.isPropertyAccessExpression(d)&&As.has(d.getName())&&o.has(d.getExpression().getText()),p=r.isIdentifier(d)&&a.has(d.getText());if(!f&&!p)continue;const g=l.getArguments()[1];if(!g||!rg(g,i))continue;const h=og(l.getArguments()[0]);h!==void 0&&c.push({dispatchKind:t,file:s,scope:N(l),line:l.getStartLineNumber(),targetExport:h.exportName,targetFile:h.file})}return c},cg=(e,t)=>{const s=[];for(const n of S(e,u.CallExpression)){const i=Qp(n),o=i===void 0?void 0:Yp.get(i);if(o===void 0)continue;const a=Xp(n,o);a!==void 0&&s.push(...ag(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},lg=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...cg(i,C(t,n)))}return s},br=/^\s*\/\/\s*lunora-advisor-exempt(?![\w-])(.*)$/u,dg=/^([a-z][\w-]*)(?=\s|--|$)/iu,Fs=e=>{const t=e.trimStart();if(!(t.startsWith("--")||t===""))return dg.exec(t)?.[1]},ug=new Set(["notify_missing_push_config"]),fg=new Set(ko.map(e=>e.name)),pg=new Set(Oo.map(e=>e.name)),gg=/^lunora\//u,mg=/\.(?:ts|tsx|js|mts)$/u,zn=e=>e.replace(gg,"").replace(mg,""),Nr=["wrangler.jsonc","wrangler.json"],hg=e=>{if(e.getKind()===T.SyntaxKind.EndOfFileToken)return;const t=e.getStart();let s=e;for(;;){const n=s.getParent();if(n===void 0||r.isSourceFile(n)||r.isSyntaxList(n)||n.getStart()!==t)break;s=n}return{first:e.getStartLineNumber(),last:s.getEndLineNumber()}},Bn=e=>e.getKind()===T.SyntaxKind.SingleLineCommentTrivia||e.getKind()===T.SyntaxKind.MultiLineCommentTrivia,vg=(e,t)=>{const s=e.getDescendantAtPos(t)??e.getLastToken();let n=s;if(Bn(s)){if(s.getKind()!==T.SyntaxKind.SingleLineCommentTrivia||s.getStart()!==t)return;for(;Bn(n);)n=e.getDescendantAtPos(n.getEnd())??e.getLastToken();return n}return s.getStart()<=t?void 0:(T.getLeadingCommentRanges(e.getFullText(),s.getPos())??[]).some(o=>o.pos===t&&o.kind===T.SyntaxKind.SingleLineCommentTrivia)?s:void 0},Eg=(e,t,s)=>{const n=e.getFullText().split(`
22
+ `),i=[];let o=0;return n.forEach((a,c)=>{const l=o;o+=a.length+1;const f=br.exec(a.trimEnd())?.[1];if(f===void 0)return;const p=Fs(f),g=p===void 0?void 0:vg(e,l+a.indexOf("//"));if(p===void 0||g===void 0)return;const h=f.indexOf("--"),x=h===-1?"":f.slice(h+2).trim();i.push({display:t,key:s,line:c+1,reason:x,rule:p,span:hg(g)})}),i},Sg=new Set([T.SyntaxKind.ConflictMarkerTrivia,T.SyntaxKind.MultiLineCommentTrivia,T.SyntaxKind.NewLineTrivia,T.SyntaxKind.ShebangTrivia,T.SyntaxKind.SingleLineCommentTrivia,T.SyntaxKind.WhitespaceTrivia]),xg=e=>{const t=T.createScanner(T.ScriptTarget.Latest,!1,T.LanguageVariant.Standard,e),s=new Set,n=[];for(let i=t.scan();i!==T.SyntaxKind.EndOfFileToken;i=t.scan())i===T.SyntaxKind.SingleLineCommentTrivia?s.add(t.getTokenStart()):Sg.has(i)||n.push({kind:i,start:t.getTokenStart(),value:t.getTokenValue()});return{lineComments:s,tokens:n}},yg=(e,t,s)=>{const n=e.findIndex(a=>a.start>=s),i=e[n];return i===void 0?void 0:{key:i.kind===T.SyntaxKind.StringLiteral&&e[n+1]?.kind===T.SyntaxKind.ColonToken?i.value:void 0,line:t.slice(0,i.start).split(`
23
+ `).length}},Ag=e=>{const t=Nr.find(l=>K(E(e,l)));if(t===void 0)return[];const s=Ie(E(e,t),"utf8"),n=s.split(`
24
+ `),i=[],{lineComments:o,tokens:a}=xg(s);let c=0;return n.forEach((l,d)=>{const f=c;c+=l.length+1;const g=br.exec(l.trimEnd())?.[1];if(g===void 0||!o.has(f+l.indexOf("//")))return;const h=Fs(g);if(h===void 0)return;const x=g.indexOf("--"),D=x===-1?"":g.slice(x+2).trim(),w=yg(a,s,c),U=w?.key;i.push({display:t,key:t,line:d+1,reason:D,rule:h,span:w===void 0?void 0:{first:w.line,last:w.line},...U===void 0?{}:{variable:U}})}),i},bg=(e,t)=>xe(e,t).split(Es).join("/"),Vn=(e,t,s)=>{const{display:n,line:i,rule:o}=t;return{cacheKey:`${e}:${n}:${i.toString()}`,categories:["SCHEMA"],description:"An inline `// lunora-advisor-exempt <rule> -- <reason>` directive accepts one advisor finding at the site it sits above. Each directive needs a rule id that can be suppressed and a non-empty reason, and must match a finding, or it does nothing.",detail:s,facing:"INTERNAL",level:"WARN",metadata:{file:n,line:i,rule:o},name:e,remediation:"Fix the directive so it names a suppressible rule with a reason after `--` and sits directly above the code it accepts, or delete it.",title:"Advisor suppression directive does not apply"}},Wn=e=>e.span===void 0?Number.POSITIVE_INFINITY:e.span.last-e.span.first,Ng=e=>{if(pg.has(e.rule))return`\`${e.rule}\` is a runtime lint, which has no source site to suppress.`;if(ug.has(e.rule))return`\`${e.rule}\` reports no source location, so a directive cannot match it.`;if(!fg.has(e.rule))return`\`${e.rule}\` is not a known advisor rule.`;if(e.reason==="")return`The \`${e.rule}\` directive gives no reason after \`--\`, so it suppresses nothing.`},wg=(e,t,s,n)=>{const i=[...Ag(t)];for(const d of e.getSourceFiles()){const f=d.getFilePath(),p=xe(s,f).split(Es).join("/"),g=bg(t,f);(p!==""&&!p.startsWith("..")||!g.startsWith("..")&&!g.split("/").includes("node_modules")&&!d.isDeclarationFile())&&i.push(...Eg(d,g,zn(p)))}const o=[],a=[];for(const d of i){const f=Ng(d);f===void 0?o.push(d):a.push(Vn("advisor_suppression_invalid",d,f))}const c=new Set,l=n.map(d=>{if(d.suppressed!==void 0)return d;const{file:f,key:p,line:g}=d.metadata;if(typeof f!="string"||typeof g!="number")return d;const[h]=o.filter(x=>x.rule===d.name&&x.key===zn(f)&&x.span!==void 0&&(!Nr.includes(x.key)||x.variable===p)&&x.span.first<=g&&g<=x.span.last).toSorted((x,D)=>Wn(x)-Wn(D));return h===void 0?d:(c.add(h),{...d,suppressed:{file:h.display,line:h.line,reason:h.reason}})});for(const d of o)c.has(d)||a.push(Vn("advisor_suppression_unused",d,`The \`${d.rule}\` directive suppresses no finding: nothing of that rule is reported on the code below it.`));return[...l,...a]},Un={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},jn=new Set(["account","credential","member","passkey","session","user"]),Pg=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),wr=e=>{const s=Pg(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return jn.has(s)||jn.has(n)},Ig=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Tg=(e,t)=>{const{objects:s,opaque:n}=Cs(e,t);return Kl(s).some(i=>Ig(i))?!0:n?void 0:!1},Cg=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!V(t,"captcha"),usesRateLimit:!!V(t,"rateLimit")}},ot={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Og=e=>{const t=ia(e),s=t?k(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Cg(t);return{...ot,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Un?{...ot,[Un[s]]:!0}:ot},kg=e=>{const t={...ot};for(const s of na(e)){const n=s.name==="use"?s.call.getArguments()[0]:void 0;if(!n)continue;const i=Og(n);t.usesCaptcha||=i.usesCaptcha,t.usesEmailGate||=i.usesEmailGate,t.usesMask||=i.usesMask,t.usesRateLimit||=i.usesRateLimit,t.usesRls||=i.usesRls}return t},Rg=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Lg=new Set(["insert","insertMany","replace","upsert","upsertMany"]),Fg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Rg.has(t.getName()))return!1;const s=t.getExpression();if(!z(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:wr(i.getLiteralText())},Dg=e=>{if(Fg(e))return!0;const t=wt(e,Lg);return t!==void 0&&wr(t.table)},_g=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),qn=new Set(["queues","scheduler","topics","workflows"]),Mg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!_g.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&qn.has(s.getName())&&ta(s.getExpression()))return!0;s=s.getExpression()}const n=yt(s);return n?.length===1&&qn.has(n[0]??"")},Kg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return z(s)},Pr=new Set(["generateObject","generateText","streamObject","streamText"]),$g=e=>{const t=k(e.getExpression());return t!==void 0&&Pr.has(t)},zg=e=>{const t=k(e.getExpression());if(t===void 0||!Pr.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!V(s,"maxOutputTokens")},Bg=new Set(["log","span","trace"]),Vg=new Set(["ai"]),Wg=new Set(["email","mail"]),Ug=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),qt=(e,t)=>[...t].some(s=>xt(e,s).length>0),Ir=new Set([u.ArrowFunction,u.FunctionDeclaration,u.FunctionExpression,u.GetAccessor,u.MethodDeclaration,u.SetAccessor]),jg=new Set(["every","filter","flatMap","forEach","map","some"]),qg=new Set(["all","allSettled","race"]),Tr=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(jg.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&qg.has(n))return t},Hg=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(Ir.has(t.getKind())){const s=Tr(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Gg=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Ir.has(t.getKind())){if(t=Tr(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Yg=e=>{const t=e.getFirstAncestor(d=>r.isArrowFunction(d)||r.isFunctionExpression(d)),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(u.TryStatement).some(d=>{const f=d.getTryBlock().getDescendantsOfKind(u.CallExpression).some(g=>{const h=g.getExpression();return r.isIdentifier(h)&&h.getText()===l&&r.isAwaitExpression(g.getParent())}),p=d.getCatchClause();return f&&p!==void 0&&p.getDescendantsOfKind(u.ThrowStatement).length>0})},Qg=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}},Xg=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}},Jg=e=>{let t=!1,s=!0;for(const n of[...Ug].flatMap(i=>xt(e,i))){const i=Xg(n);i&&(t=!0,!Hg(i)&&!Qg(i)&&!Yg(i)&&!Gg(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Zg=e=>S(e,u.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),Hn="lunora-advisor-exempt",em=/^[\s*/]+/u,tm=/[\w-]/u,sm=e=>{const s=(e.getFirstAncestorByKind(u.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
25
+ `);for(const n of s.split(`
26
+ `)){const i=n.replace(em,"");if(!i.startsWith(Hn))continue;const o=i.slice(Hn.length);if(tm.test(o.charAt(0))||n.trimStart().startsWith("//")&&Fs(o)!==void 0)continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},nm=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=V(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},im=(e,t)=>{const s=nm(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)},rm=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of S(e,u.CallExpression))if(Dg(l)&&(o=!0),Mg(l)&&(t=!0),Kg(l)&&(i=!0),$g(l)&&(s=!0),zg(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Jg(e);return{callsMail:qt(e,Wg),emitsEvent:qt(e,Bg),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||qt(e,Vg),throwsBareError:Zg(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},om=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=le(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?kg(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=im(e,s);return{...o?rm(o):{},...sm(e),...i,analyzableBody:o!==void 0,exportName:ee(e)??e.getName(),file:t,hasEmailArg:Tg(s,n.receiver),kind:n.kind,line:gi(e),visibility:n.visibility}},am=(e,t)=>{const s=[];for(const n of se(e)){const i=om(n,t);i&&s.push(i)}return s},cm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...am(i,C(t,n)))}return s},lm=new Set(["dbRateLimit","rateLimit"]),dm=e=>r.isArrowFunction(e)?e.getBody():e,um=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Cr=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Or=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(u.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},fm=(e,t)=>Y(e)||t!==void 0&&Or(e,t).some(s=>Cr(s)),pm=(e,t)=>t===void 0?Ne(e):Or(e,t).some(s=>!Cr(s)),gm=(e,t)=>{const s=k(e.getExpression());if(s===void 0||!lm.has(s))return;const n=M(vi(e.getArguments()[2]),"key");if(!n)return;const i=dm(n),o=um(n);if(!(!fm(i,o)||pm(i,o)))return{callee:s,scope:N(e),file:t,limitName:hi(e),line:e.getStartLineNumber()}},mm=(e,t)=>R(e,t,gm),hm=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),vm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!hm.has(t.getName()))return;const s=t.getExpression();if(z(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&z(s.getExpression()))return s.getName()},Em=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&z(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Sm=e=>{let t=v(e)??e;for(;r.isAwaitExpression(t);)t=v(t.getExpression())??t.getExpression();return t},kr=(e,t=!1)=>{const s=Sm(e);if(r.isIdentifier(s)){if(t)return;const n=Xo(s),i=n!==void 0&&r.isIdentifier(n.getNameNode())?n.getInitializer():void 0;return i===void 0||!r.isIdentifier(n?.getNameNode())?void 0:kr(i,!0)}if(r.isCallExpression(s))return vm(s)??Em(s)},xm=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of S(e,u.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},ym=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=le(s);if(n?.kind!=="query")return[];const i=ki(s);if(i===void 0)return[];const o=n.receiver!==void 0&&ra(n.receiver,"output"),a=n.receiver!==void 0&&Ti(n.receiver,"use","mask"),c=new Set,l=[];for(const d of xm(i)){const f=kr(d);f===void 0||c.has(f)||(c.add(f),l.push({exportName:ee(e)??e.getName(),file:t,line:d.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Am=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=C(t,n);for(const a of se(i))s.push(...ym(a,o))}return s},bm=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(y(s));return t},Nm=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;if(!n)return[];const i=[];for(const o of S(e,u.CallExpression)){const a=Oi(o);if(a===void 0)continue;const c=bm(M(a.options,"with"));c.length!==0&&i.push({exportName:ee(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},wm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=C(t,n);for(const a of se(i))s.push(...Nm(a,o))}return s},X=(e,t)=>`${e}:${t}`,Gn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Pm=(e,t)=>[...ce(e,t,u.FunctionDeclaration,(s,n)=>s.getParent().getKind()===u.SourceFile?Gn(s,n,s.getName(),s.isExported()):void 0),...ce(e,t,u.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===u.SourceFile?Gn(i,n,s.getName(),i.isExported()):void 0})],Im=(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=C(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(X(c,a))},Tm=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Cm=(e,t)=>{const s=new Map(e.map(n=>[X(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(X(i.file,i.name))?.set(Tm(n),{fields:n.fields,method:n.method,table:n.table})}return s},Om=(e,t,s)=>S(e.node,u.CallExpression).map(n=>Im(n,t,s)).filter(n=>n!==void 0),km=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(X(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(X(o.file,o.name))?.push(a)}},Rm=(e,t,s)=>{const n=new Map(e.map(a=>[X(a.file,a.name),a])),i=new Map(e.map(a=>[`${Is(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[X(a.file,a.name),Om(a,n,t)]));return km(s,n,i,o),o},Lm=(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},Fm=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(X(i.file,i.name))??[])Lm(t.get(X(i.file,i.name)),t.get(X(o.file,o.name)))&&(n=!0)}},Dm=(e,t,s,n)=>{const i=Pm(e,t),o=Cm(i,s);return Fm(i,o,Rm(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(X(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},pt=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=pt(e.getLeft()),s=pt(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},_m=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&pt(t)!==void 0},Mm=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return y(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===u.EqualsToken)return t.getLeft().getText()}},Km=(e,t,s)=>ka(e)?!$o(s)&&Ra(Mm(t)):!0,$m=(e,t)=>{const s=[],n=[...S(e,u.BinaryExpression),...S(e,u.StringLiteral),...S(e,u.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(_m(o))continue;const a=pt(o);if(a===void 0)continue;const c=Ca(a);if(c===void 0||!Km(c,o,t))continue;const l=o.getStartLineNumber(),d=`${String(l)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:l,preview:Oa(a)}))}return s},zm=(e,t)=>{const s=[],n=new Et({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of b(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Ie(i,"utf8"),{overwrite:!0});s.push(...$m(o,C(t,i)))}return s},Bm=e=>{const t=M(e,"includeDeleted");if(t!==void 0||!r.isObjectLiteralExpression(e))return t;const s=V(e,"includeDeleted");return r.isShorthandPropertyAssignment(s)?s.getNameNode():void 0},Vm=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?le(s):void 0;if(!n)return[];const i=[];for(const o of S(e,u.CallExpression)){const a=Oi(o);if(a===void 0)continue;const c=Bm(a.options);if(c===void 0)continue;const l=r.isTrueLiteral(c),d=!l&&Y(c);!l&&!d||i.push({exportName:ee(e)??e.getName(),file:t,fromArgs:d,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Wm=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=C(t,n);for(const a of se(i))s.push(...Vm(a,o))}return s},Um=new Set(["query","unsafe"]),Rr=3,jm=e=>!r.isPropertyAccessExpression(e)||!Um.has(e.getName())?!1:Z(e.getExpression(),["sql"]),fs=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(!(!J(t)||!r.isIdentifier(t.getNameNode())))return t.getInitializer()},qm=e=>{const t=fs(e);if(t!==void 0||!r.isIdentifier(e))return t;const s=e.getSymbol()?.getDeclarations()[0],n=r.isBindingElement(s)?s.getParent().getParent():void 0;if(!r.isBindingElement(s)||!J(n))return;const i=n.getInitializer(),o=v(i),a=v(o!==void 0&&r.isIdentifier(o)?fs(o):o),c=d=>r.isSpreadAssignment(d)||r.isPropertyAssignment(d)&&r.isComputedPropertyName(d.getNameNode()),l=r.isObjectLiteralExpression(a)&&!a.getProperties().some(d=>c(d))?a.getProperty(fe(s)):void 0;return r.isShorthandPropertyAssignment(l)?l.getNameNode():r.isPropertyAssignment(l)?l.getInitializer():i},Hm=e=>{const t=v(e);if(!t)return!1;if(r.isTemplateExpression(t))return!0;if(r.isBinaryExpression(t))return t.getOperatorToken().getKind()===u.PlusToken;if(!r.isCallExpression(t))return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)&&["concat","join"].includes(s.getName())},Gm=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return!1;const n=e.getArguments().every(o=>t(o));if(s.getName()==="concat")return n&&t(s.getExpression());const i=v(s.getExpression());return s.getName()==="join"&&n&&r.isArrayLiteralExpression(i)&&i.getElements().every(o=>t(o))},ye=(e,t=Rr)=>{const s=v(e);return s?r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)||r.isNumericLiteral(s)?!0:r.isTemplateExpression(s)?s.getTemplateSpans().every(n=>ye(n.getExpression(),t)):r.isBinaryExpression(s)?s.getOperatorToken().getKind()===u.PlusToken&&ye(s.getLeft(),t)&&ye(s.getRight(),t):r.isIdentifier(s)?t>0&&ye(fs(s),t-1):r.isCallExpression(s)?Gm(s,n=>ye(n,t)):!1:!1},Ym=e=>{const t=v(e);if(!t||ye(t))return!1;let s=t;for(let n=0;s!==void 0&&n<=Rr;n+=1){if(Hm(s)||Y(s))return!0;const i=qm(s);s=i===void 0?void 0:v(i)}return!1},Qm=(e,t)=>{if(!jm(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ym(s)))return{file:t,line:s.getStartLineNumber(),scope:N(e)}},Xm=(e,t)=>R(e,t,Qm),Jm=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Zm=e=>{for(const[t,s]of Jm)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},eh=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Zm(a);c!==void 0&&s.push({file:C(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},th=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),sh=(e,t,s=[])=>{const n=bt(e,t,{argIndex:0,scope:"identity",matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:th,requireUnmodifiedReach:!0});return Ns(n,s)},nh=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),ih=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=y(i);t.push(o),o==="expiresInSeconds"&&(s=Ei(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},rh=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=nh.get(t);return s===void 0?void 0:Ai(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},oh=(e,t)=>{const s=rh(e.getExpression());if(s!==void 0)return{scope:N(e),file:t,line:e.getStartLineNumber(),method:s.method,...ih(e.getArguments()[s.optionsIndex])}},ah=(e,t)=>R(e,t,oh),ch=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Lr=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:ch(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>pe(i)||s(i));if(!(n===void 0||pe(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},Ds=(e,t)=>P(e.getFirstAncestor(s=>P(s,t)||pe(s)),t),lh=(e,t)=>P(e,t)||e.getFirstAncestor(s=>P(s,t))!==void 0,Fr=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return P(e,t)||Ds(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Lr(e);return s!==void 0&&!lh(s,t)}return!1},Dr=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(u.BreakStatement),...e.getDescendantsOfKind(u.ContinueStatement),...e.getDescendantsOfKind(u.ReturnStatement),...e.getDescendantsOfKind(u.ThrowStatement)],dh=e=>Dr(e).some(t=>Fr(t,e)),uh=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},fh=e=>Dr(e).some(t=>Fr(t,e)||r.isBreakStatement(t)&&P(Lr(t),e))||e.getDescendantsOfKind(u.CallExpression).some(t=>uh(t)&&Ds(t,e)),ph=e=>e.getDescendantsOfKind(u.YieldExpression).some(t=>Ds(t,e)),gh=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),mh=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Ht=(e,t)=>{const s=gh(e);if(!(s===void 0||r.isTrueLiteral(v(s)))||fh(e)||ph(e))return;const i=N(e);if(!(i.kind==="module"&&e.getFirstAncestor(pe)!==void 0))return{file:t,kind:mh(e),line:e.getStartLineNumber(),scope:i}},hh=(e,t)=>[...ce(e,t,u.WhileStatement,Ht),...ce(e,t,u.ForStatement,Ht),...ce(e,t,u.DoStatement,Ht)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),vh=new Set(["when","where"]),Gt=new Set(["definePolicy","defineShape"]),Eh=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Gt.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 Gt.has(i)?i:void 0}const s=t.getText();return Gt.has(s)?s:void 0},Sh=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,_r=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Sh(e))return"empty-object";if(r.isParenthesizedExpression(e))return _r(e.getExpression())}},_s=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),xh=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>_s(t)===e),Mr=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>_s(t)===e),yh=e=>{const t=xh(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Mr(e).length>0},Ah=e=>e.getDescendantsOfKind(u.IfStatement).filter(t=>_s(t)===e),ps=e=>e.getKind()===u.NullKeyword||e.getKind()===u.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",bh=(e,t)=>ps(e)||ps(t),Nh=new Map([[u.EqualsEqualsEqualsToken,"positive"],[u.EqualsEqualsToken,"positive"],[u.ExclamationEqualsEqualsToken,"negative"],[u.ExclamationEqualsToken,"negative"]]),Yn=e=>!ps(e)&&(r.isLiteralExpression(e)||e.getKind()===u.TrueKeyword),wh=(e,t,s)=>{const n=Nh.get(e);if(n!==void 0)return bh(t,s)?n==="positive"?"negative":"positive":Yn(t)||Yn(s)?void 0:n},Ke=e=>{if(r.isParenthesizedExpression(e))return Ke(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===u.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=wh(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===u.AmpersandAmpersandToken||t===u.BarBarToken){const n=Ke(e.getLeft()),i=Ke(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Qn=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}}},Ph=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(u.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Ih=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Th=e=>{const t=[];for(const s of Mr(e)){const n=Ke(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Ah(e)){const n=Ke(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Qn(s.getThenStatement()):Qn(s.getElseStatement())??Ph(s);i!==void 0&&t.push(Ih(i))}return t},Ch=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},Oh=(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)||!vh.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&yh(a))for(const c of Th(a)){const l=_r(c);l!==void 0&&i.push({exportName:Ch(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},kh=(e,t)=>{const s=[];for(const n of S(e,u.CallExpression)){const i=Eh(n);i!==void 0&&s.push(...Oh(n,i,t))}return s},Rh=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...kh(i,C(t,n)))}return s},Lh=new Set(["query","upsert","upsertMany","upsertNow"]),be=new Set,Fh=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Lh.has(t))return Z(e.getExpression(),["vectors"])?t:void 0},Ms=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},Kr=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},$r=e=>Kr(e)?.getDeclarations()[0],Dh=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},zr=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},Xn=(e,t,s)=>{const n=Kr(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=zr($r(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return Ks(o,t,s-1)}return Y(e)},Ks=(e,t,s)=>{const n=Ms(e);return yi(n)?!1:r.isIdentifier(n)?Xn(n,t,s):Y(n)?!0:n.getDescendantsOfKind(u.Identifier).some(i=>Dh(i)&&Xn(i,t,s))},Br=e=>{const t=zr($r(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},oe=(e,t)=>{const s=Ms(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...oe(s.getWhenTrue(),t),...oe(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===u.BarBarToken||n===u.QuestionQuestionToken||n===u.AmpersandAmpersandToken)return[...oe(s.getLeft(),t),...oe(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Br(s);return n===void 0?[]:oe(n,!1)}return[]},_h=(e,t)=>{const s=oe(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>gt(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Mh=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Kh=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),gt=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=_h(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Mh(n)&&(s=[Kh(n)]);return s},$h=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(u.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},zh=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return be;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return be;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(u.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},gs=(e,t=!0,s=be)=>{const n=Ms(e);if(r.isIdentifier(n)){const o=t?Br(n):void 0;return o===void 0?[{node:n,parameters:s}]:gs(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?gs(o.getExpression(),t,s):oe(o,!0).flatMap(a=>gt(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=Ks(i.getExpression(),be,1)?zh(o):be;return $h(o).flatMap(c=>oe(c,!0).flatMap(l=>gt(l,!0).map(d=>({node:d,parameters:a}))))}return[{node:n,parameters:s}]},Bh=(e,t)=>{const s=Fh(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?gs(n):oe(n,!0).flatMap(o=>gt(o,!0).map(a=>({node:a,parameters:be})))).some(({node:o,parameters:a})=>Ks(o,a,1))))return{scope:N(e),file:t,line:e.getStartLineNumber(),method:s}},Vh=(e,t)=>R(e,t,Bh),Wh=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:d,schema:f,shapes:p,topics:g,wranglerVariables:h,workflows:x}=s;return Fo({adminRoutes:El(e,t),aiRawRuns:yl(e,t),aiToolSideEffects:Rl(e,t),argumentDerivedFetches:Dl(e,t),argumentValidators:Zl(e,t),authApiCalls:ca(e,t),authConfigs:ld(e,t),browserUrlAccesses:pd(e,t),callEdges:n.callEdges,configCalls:yd(e,t),containerKeyAccesses:bd(e,t),containerOverrides:Cd(e,t),containers:i,countReads:Fd(e,t,f.tables),crons:o,cronTargets:o.flatMap(D=>D.functionPath===void 0?[]:[D.functionPath]),exportSinks:Kd(e,t),staleMigrationImports:eh(e,t),failOpenGuards:Wd(e,t),flagReads:Gd(e,t),flagSecurityDefaults:Jd(e,t),geoIndexUsages:tu(e,t),httpActionGuards:pu(e,t),httpHeaderWrites:bu(e,t),hyperdriveCalls:ua(e,t),identityClaimReads:lf(e,t),imageDeliveryUrlAccesses:uf(e,t),inserts:n.inserts,kvKeyAccesses:pf(e,t,a),mailRecipientAccesses:Ef(e,t),maskProcedures:Ea(e,t),maskStrategies:yf(e,t),mutatorWrites:Cf(e,t),nondeterministicCalls:ba(e,t),normalizeIdAuthorizations:Uf(e,t),notifyCalls:wa(e,t),notifyConfig:Na(e,t),mutators:l,ownerFieldWrites:Up(e,t,a,l),unrestrictedWhereBranches:Rh(e,t),paymentWebhooks:Gp(e,t),privilegedDispatches:lg(e,t),procedureProtections:cm(e,t),queries:n.queries,queues:d,r2sqlCalls:Pa(e,t),ratelimitKeySelectors:mm(e,t),rawRowReturns:Am(e,t),relationLoads:wm(e,t),rlsProcedures:Ia(e,t),schema:f,secretLiterals:zm(e,t),modules:c,shapes:p,topics:g,softDeleteReads:Wm(e,t),sqlInterpolations:Xm(e,t),storageKeyAccesses:sh(e,t,a),storageUploads:ah(e,t),tableWrites:n.tableWrites,rowEffects:Dm(e,t,n.tableWrites,n.callEdges),unboundedLoops:hh(e,t),vectorNamespaceAccesses:Vh(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:h})},Uh=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"}),jh=(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=>Uh(i))]},qh=()=>({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"}),Hh=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",Jn={error:"ERROR",info:"INFO",warn:"WARN"},Zn={ERROR:2,INFO:0,WARN:1},Gh=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"}),Yh=(e,t)=>{const{advisor:s}=Fi(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(Jn,n)?Jn[n]:void 0;return i===void 0?[...t,Gh(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=>Hh(o)||Zn[o.level]>=Zn[i])},Qh=(e,t)=>{const{advisor:s}=Fi(e),n=jh(t,s?.accept??[]);return Yh(e,s?.acceptUnreadable===!0?[...n,qh()]:n)},Xh={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Jh="crons",Zh=za.replace(/\.ts$/u,""),Ae=(e,t)=>`${Is(e)}:${t}`,Yt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},ev=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Xh[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,...Yt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Yt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Yt("workflow",t.workflow,"workflow name")}))],tv=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",sv=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:tv(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},nv=e=>ev(e).flatMap(t=>sv(t)),iv=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:Jh,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],rv=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),Le=(e,t)=>t===void 0?e:{...e,module:t},ov=e=>{const t=new Map,s=new Map,n=rv(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(Ae(c.file,c.exportName),l)};for(const c of e.functions){const l=Ae(c.filePath,c.exportName),d=[...Ta(c.filePath),c.exportName].join(".");o(Le({detail:c.kind,id:`function:${l}`,kind:"function",name:d},tt(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=Ae(c.filePath,c.exportName);o(Le({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},tt(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(Le({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(Le({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},tt(e.modules,c.filePath)),Ae(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(Le({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},tt(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},Ae(Zh,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}},av=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,cv=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(Ae(e.file,e.exportName))??{reason:av(e.exportName)},lv=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=cv(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`}},Qt=e=>`${e.from}|${e.kind}|${e.to}`,dv=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,uv=e=>{const{nodes:t,sites:s}=ov(e),n=new Map,i=new Map;for(const o of[...iv(e),...nv(e)]){const a=lv(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(Qt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(dv(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>Qt(o).localeCompare(Qt(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}},fv=e=>`${Di}export const architecture = ${Va(e,"Record<string, unknown>")};
27
+ `,ei=(e,t="api")=>{const s=new Map;for(const n of e){const i=Is(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 F("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})}}},pv=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>_i(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=>Mi(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?[]:Za)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(d=>d.name===c.name)===l)},gv=(e,t,s={})=>{if(t===void 0)return;const n=pv(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
28
+ `);throw new F("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
29
+ ${i}
30
+
31
+ Install them with your package manager, then re-run codegen.`)},$s="cloudflare:",Pt=[".d.ts",".d.mts",".d.cts"],$e=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],mv={".cjs":[".cts"],".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"]},hv=e=>!e.isTypeOnly(),vv=e=>{const t=e.getModuleReference();if(e.isTypeOnly()||!r.isExternalModuleReference(t))return;const s=t.getExpression();return s!==void 0&&r.isStringLiteral(s)?s.getLiteralValue():void 0},Ev=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralValue()==="require",Sv=e=>{const t=e.getExpression(),[s]=e.getArguments();if(!(!(t.getKind()===u.ImportKeyword||r.isIdentifier(t)&&t.getText()==="require"||r.isPropertyAccessExpression(t)&&t.getName()==="require"||r.isElementAccessExpression(t)&&Ev(t.getArgumentExpression()))||s===void 0)){if(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s))return s.getLiteralValue();if(r.isTemplateExpression(s)){const i=s.getHead().getLiteralText();return i.startsWith($s)?`${i}*`:void 0}}},xv=e=>{const t=new Set,s=n=>{n!==void 0&&t.add(n)};for(const n of e.getImportDeclarations())hv(n)&&s(n.getModuleSpecifierValue());for(const n of e.getExportDeclarations())n.isTypeOnly()||s(n.getModuleSpecifierValue());for(const n of S(e,u.ImportEqualsDeclaration))s(vv(n));for(const n of S(e,u.CallExpression))s(Sv(n));return[...t]},ms=e=>{try{return fi(e).isFile()}catch{return!1}},yv=new Set(["browser","worker","workerd"]),hs=(e,t=!0)=>{if(typeof e=="string")return[e];if(e===null||typeof e!="object")return[];const s=e;return t&&Object.hasOwn(s,".")?hs(s["."],!1):Object.entries(s).filter(([n])=>!yv.has(n)).flatMap(([,n])=>hs(n,!1))},Av=e=>{try{return fi(e).isDirectory()}catch{return!1}},bv=e=>{let t;try{t=JSON.parse(Ie(E(e,"package.json"),"utf8"))}catch{return[]}if(t===null||typeof t!="object"||Array.isArray(t))return[];const s=t;return[...[s.main,s.module].filter(n=>typeof n=="string"),...hs(s.exports)]},Vr=e=>Pt.some(t=>e.endsWith(t)),mt=(e,t=new Set)=>{if(t.has(e))return[];t.add(e);const s=Pt.find(a=>e.endsWith(a));if(s!==void 0)return mt(e.slice(0,-s.length),t);const n=$e.find(a=>e.endsWith(a)),o=(n===void 0?[e,...$e.map(a=>e+a)]:[e,...(mv[n]??[]).map(a=>e.slice(0,-n.length)+a)]).filter(a=>ms(a));if(Av(e)){o.push(...$e.map(a=>E(e,`index${a}`)).filter(a=>ms(a)));for(const a of bv(e))o.push(...mt(pi(e,a),t))}return[...new Set(o)].filter(a=>!Vr(a))},Nv=(e,t)=>mt(pi(Se(e),t)),wv=(e,t)=>{const s=[...Pt,...$e].find(o=>e.endsWith(o))??"",n=e.slice(0,e.length-s.length),i=$e.find(o=>t.endsWith(o));return i!==void 0?n+i:Ss(n)==="index"&&!t.endsWith("index")?Se(n):n},Pv=(e,t)=>xe(e,t).split(Es).some(s=>s==="_generated"||s==="node_modules"),Iv=(e,t,s)=>{const n=T.resolveModuleName(s,t,e.getCompilerOptions(),e.getModuleResolutionHost()).resolvedModule;return n===void 0||n.isExternalLibraryImport===!0?[]:mt(wv(n.resolvedFileName,s))},Tv=(e,t)=>!Pt.some(s=>t.endsWith(s))&&!Pv(e,t),Cv=(e,t,s,n)=>n.filter(i=>!i.startsWith($s)).flatMap(i=>i.startsWith(".")?Nv(s,i):Iv(e,s,i)).filter(i=>Tv(t,i)),ti=e=>{try{return To(e)}catch{return e}},Ov=(e,t,s)=>{const n=Se(t),i=E(t,"schema.ts"),o=[...new Set([...b(t),...[i,...s===void 0?[]:[s]].filter(d=>ms(d))])].filter(d=>!Vr(d)),a=new Et({compilerOptions:{allowJs:!0},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1}),c=new Set(o.map(d=>ti(d))),l=[];for(let d=o.shift();d!==void 0;d=o.shift()){const f=xv(e.getSourceFile(d)??a.getSourceFile(d)??a.addSourceFileAtPath(d)),p=f.filter(g=>g.startsWith($s));p.length>0&&l.push({module:xe(n,d)||Ss(d),specifiers:p});for(const g of Cv(e,n,d,f)){const h=ti(g);c.has(h)||(c.add(h),o.push(g))}}return l},kv=(e,t)=>{const s=ma();for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(ha(i,s))return!0}return!1},Rv="createWorker",Lv="extend",si=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,ni=e=>{const t=[],s=si(M(e,"backupCron"));s!==void 0&&t.push({cron:s,handler:"backupCron"});const n=M(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=si(i.getNameNode());o!==void 0&&t.push({cron:o,handler:"crons"})}return t},Fv=e=>{const t=k(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Rv)return r.isObjectLiteralExpression(s)?ni(s):[];if(t!==Lv||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=mi(s.getBody());return n===void 0?[]:ni(n)},Dv=(e,t)=>{const s=[];for(const{filePath:n}of Ue(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of S(i,u.CallExpression))s.push(...Fv(o))}return[...new Map(s.map(n=>[`${n.handler} ${n.cron}`,n])).values()]},Wr=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Wr(e.inner)},_v=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Wr(n);return i!==void 0&&t.has(i)}))},Mv=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new F("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new F("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Kv=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=tf(s,t),a=ir(s,t),c=a.claims;for(const I of a.diagnostics)console.warn(`@lunora/codegen: ${I}.`);const l=ic(s,t),d=Ba(s,t),{queues:f,topics:p}=rc(s,t),g=ac(n),h=tc(s,t);Mv(d,h);const x=sc(s,t),D=cc(s,t),w=nc(s,t,d,h),U=Dv(s,t),ne=[...new Set(U.map(I=>I.cron))],A=zu(s,t,Ri(n)),j=oc(s,t),ge=kv(s,t),ie=va(s,t);ie.browser=ie.browser||j.usesSandboxBrowser;const te=Fe(n,e.target),_=lc(ie,te,{agents:h.length>0,cloudflareModuleImports:dc(te)?Ov(s,t,e.workerEntry):[],commitOrderedTables:i.tables.some(I=>I.commitOrdered===!0),cronTriggers:w.length>0,cronWorkflowTriggers:w.some(I=>I.workflow!==void 0),crossShardFanout:i.tables.some(I=>Ec(I)),containerEgressPolicy:A.containerEgressPolicy,containerRuntimeScheduling:x.some(I=>I.schedulingPolicy==="durable_object"),containerSandboxTools:x.some(I=>I.sandbox===!0),deliveryAuthorization:A.deliveryAuthorization,durableStreams:A.durableStreams,globalTables:i.tables.some(I=>I.shardMode==="global"),liveContext:A.liveContext,liveStreams:A.liveStreams,typedWebSockets:A.typedWebSockets,queues:f.length>0,relationGraph:_v(i),secretValues:ge,secrets:A.secrets,services:g.length>0,topics:p.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:j.usesSandboxLoader,workflowRollback:A.workflowRollback,workflowSchedules:d.some(I=>I.schedules!==void 0)}),L=_.usage,de=ec(L),re=_.signals.vectorStore!==!1,B=_.signals.services===!1?[]:g,W=Ki(n),He=W??new Set,q=He.has("lunorash");gv(i,W,{hasVectors:re,scheduler:L.scheduler||w.length>0,storage:L.storage||D.rules.length>0||Object.keys($i(i)).length>0,usage:L});const H=K(E(t,"flags.ts")),G=K(E(t,"notify.ts"));return{agents:h,capabilities:de,containers:x,crons:w,dataModelContent:Ac(i),declaredDependencies:W,dependencies:He,entryCronTriggers:ne,workerEntryCrons:U,env:l,featureUsage:L,hasFlags:H,hasNotify:G,authClaims:c,identity:o,platformGate:{..._,diagnostics:[...uc(n,e.target),..._.diagnostics,...fc(te,i.vectorIndexes),...A.liveStreams&&A.deliveryAuthorization?[pc(te)]:[],...A.socketRoutes&&A.deliveryAuthorization?[gc(te)]:[]]},queues:f,serverContent:xc({agents:h,capabilities:de,containers:x,env:l,hasVectors:re,hasFlags:H,authClaims:c,hasNotify:G,identity:o,queues:f,schema:i,services:B,storageRuleBuckets:D.rules.map(I=>I.bucket),topics:p,useUmbrella:q,workflows:d}),services:B,storageRulesMetadata:D,topics:p,usesSandbox:j.usesSandboxBrowser||j.usesSandboxContainer||j.usesSandboxFs,useUmbrella:q,workflows:d}},Ur=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},$v=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},zv=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Bv=/^[\w$]+:[\w$]+$/u,Vv=(e,t)=>{const s=Si(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},ii=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Wv=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return ii(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===xs.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?ii(s):void 0}}},Uv=(e,t,s)=>({schedule:{argKeys:Wv(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),jv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(As.has(s))return Vv(s,n);if((s==="runAfter"||s==="runAt")&&$v(t)){const l=Si(i)??(r.isStringLiteral(i)&&Bv.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Uv(s,n,o)}}const a=zv.get(s),c=a===void 0?void 0:Ur(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},qv=new Set([u.AmpersandAmpersandEqualsToken,u.AmpersandAmpersandToken,u.BarBarEqualsToken,u.BarBarToken,u.QuestionQuestionEqualsToken,u.QuestionQuestionToken]),jr=e=>T.isOptionalChain(e.compilerNode),Hv=(e,t)=>r.isIfStatement(t)?!P(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?P(e,t.getStatement()):r.isForStatement(t)?P(e,t.getStatement())||P(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:pe(t)?t.getFirstAncestor(pe)!==void 0:r.isConditionalExpression(t)?!P(e,t.getCondition()):r.isBinaryExpression(t)?!P(e,t.getLeft())&&qv.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&jr(t)?!P(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&dh(s)),Gv=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&P(t,s.getRight())&&s.getOperatorToken().getKind()===u.EqualsToken,i=e.getFirstAncestor(pe);return n||i?.getDescendantsOfKind(u.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&P(o.getFirstAncestor(pe),i))===!0},Yv=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&P(e,t.getStatement())||r.isForStatement(t)&&(P(e,t.getStatement())||P(t.getIncrementor(),e)),Qv=(e,t)=>{if(jr(e)||t==="schedule"&&Gv(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Hv(s,i)){if(!Yv(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},ri=(e,t,s)=>{if(s===void 0)return;const n=Qv(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:N(e)}},Xv=(e,t)=>[...R(e,t,(s,n)=>ri(s,n,jv(s))),...ce(e,t,u.PropertyAccessExpression,(s,n)=>{const i=Ur(s,"services");return ri(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Jv=new Set(["boolean","number","object","string"]),Zv=e=>{const t=e.getName();if(!Jv.has(t))return;const s=e.getExpression();return Z(s,["flags"])||Z(s,["flags","details"])?t:void 0},eE=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Zv(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},tE=(e,t)=>{const s=new Map;for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of S(i,u.CallExpression)){const a=eE(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},sE=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||bc(o))return;const a=e.getSourceFile().getFilePath();if(Nc(i,e,a)){const c=wc(i,e,a,0,new Set);return c===void 0&&Pc(o),c}return o},nE=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=ws(t.getNameNode());return s===void 0||s==="namespace"}),iE=(e,t)=>{for(const{filePath:s}of Ue(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of S(n,u.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||nE(a)))return i}}},rE="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",oE=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Ce(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${rE}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},aE="room:",cE="__lunora_socket__:",lE=/^[A-Za-z]\w*$/u,oi=e=>lE.test(e),dE=e=>`${e}:`.startsWith(aE)||`${e}:`.startsWith(cE),qr=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Hr=e=>qr(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),ai=e=>y(e),zs=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&y(s)===t),ve=(e,t)=>{const s=Ce(e,`defineLiveStream ${t}`);return new F("LIVE_STREAM_NOT_LITERAL",s.message)},Gr=(e,t,s)=>{const n=zs(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ve(n??e,`needs ${s} so codegen can read its topics`);if(Hr(i))throw ve(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},uE=(e,t)=>{const s=ai(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ve(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Hr(n))throw ve(n,`cannot spread into or compute the keys of topic "${s}"`);if(!oi(s)||dE(s))throw new F("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(zs(n,"key")===void 0)return{fields:[],name:s};const a=Gr(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>ai(l)),c=a.find(l=>!oi(l));if(c!==void 0)throw new F("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},fE=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ve(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(qr(n))throw ve(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=zs(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ve(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Gr(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:C(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>uE(a,l))}},pE=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new F("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},gE=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},mE=(e,t)=>S(e,u.CallExpression).filter(s=>Ii(s,"defineLiveStream")).map(s=>{const n=gE(s),i=r.isVariableDeclaration(n)?bs(n,"binding"):void 0;if(i===void 0)throw new F("LIVE_STREAM_NOT_EXPORTED",Ce(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return fE(s,i,t)}),hE=(e,t)=>{const s=b(t).flatMap(n=>mE(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return pE(s),s},vE=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,EE=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?vE(e):!0,Yr=(e,t=!1)=>{for(const s of e.getProperties()){if(EE(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Yr(n,!0))return!0}return!1},SE=(e,t)=>{for(const s of b(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of zi(n))for(const o of Ps(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Yr(a)))return!0}}return!1},xE=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=lt(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=lt(a);c!==void 0&&s.push({column:c,strategy:Li(a),table:i})}}return s},yE=(e,t)=>{const s=new Map;for(const n of b(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of zi(i))for(const a of Ps(o))for(const c of xE(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},AE=["providerSubscriptionId","state"],bE=["providerEventId","processedAt"],ci=(e,t)=>t.every(s=>s in e.shape),NE=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&ci(t,AE)&&ci(s,bE)},wE=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],PE=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},IE=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},TE="@lunora/privacy",Qr="userId",li=new Set(["user","users"]),CE=e=>e.replaceAll("\\","/"),OE="privacy",kE=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),It=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,We=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Bs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),RE=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},Tt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},LE=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=RE(s,"tables"),i=It(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Bs(n).map(a=>We(a)))t.datasets.set(o,i)},Vs=8,Pe=(e,t=0)=>{if(t>Vs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Pe(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Pe(i,t+1)},FE=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:Pe(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?Bs(n):[],o=new Set(i.map(a=>We(a)));for(const a of wE)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?It(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),We(a)==="user"&&t.userTables.add(c))}},di=(e,t,s)=>{t.datasets.set(It(e.getArguments()[0])??s,s)},DE=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[We(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Xr=(e,t=0)=>{const s=Pe(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Vs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Xr(i.getExpression(),t+1):[DE(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},_E=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Xr(t)},ME=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Pe(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Bs(n):[])t.excluded.set(We(i),r.isPropertyAssignment(i)?It(i.getInitializer())??"":"")},KE=(e,t)=>{switch(Tt(e)){case"actionCacheDataset":{di(e,t,"actionCache");break}case"authDataset":{FE(e,t);break}case"defineDataset":{LE(e,t);break}case"documentHistoryDataset":{di(e,t,"documentHistory");break}}},Ws=e=>e!==void 0&&r.isCallExpression(e)&&Tt(e)==="defineDataset",Jr=e=>e!==void 0&&r.isCallExpression(e)&&kE.has(Tt(e)??""),$E=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(Ws(i)||Jr(i))?n:void 0},Zr=(e,t,s=0)=>{const n=Pe(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Vs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!Zr(i.getExpression(),t,s+1))return!1}else if(!Ws(i)&&!Jr(i)){const o=r.isIdentifier(i)?$E(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},zE=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||Zr(t,s)?s:void 0},BE=(e,t)=>{const s=[];for(const i of S(e,u.CallExpression))if(KE(i,t),Tt(i)==="definePrivacy"){const o=_E(i);ME(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:zE(o)})}return{declared:S(e,u.VariableDeclaration).filter(i=>Ws(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},VE=(e,t)=>{const s=E(t,"schema.ts"),n=[...b(t),...K(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>CE(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},WE=(e,t,s)=>{if(s?.has(TE)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:li};const n={datasets:new Map,excluded:new Map,userTables:new Set(li)},i=[],o=[];for(const f of VE(e,t)){const p=BE(f,n);i.push(...p.declared),o.push(...p.privacyCalls)}const a=new Set;for(const f of o){for(const p of f.passed??[])a.add(p);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:PE(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},eo=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&eo(n,t)),UE=(e,t)=>e.extensionKey!==OE&&(Qr in e.shape||Object.values(e.shape).some(s=>eo(s,t))),jE=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${Qr}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,qE=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>UE(o,t.userTables)).map(o=>o.name),[n]=IE(s,t.classifications);if(n!==void 0)throw new F("PRIVACY_COVERAGE",jE(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new F("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},HE=(e,t)=>{const s=mc(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},GE=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),YE="",QE=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},XE=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===xs.Const?t.getInitializer():void 0},at=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return at(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=XE(e);if(n!==void 0)return at(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},JE=(e,t)=>{if(GE.has(e))return{method:e,tables:at(t)??[YE]}},to=(e,t,s)=>e===void 0?void 0:{...e,fields:QE(t,e.method,s)},ui=e=>{const t=wt(e,Af);return t===void 0?void 0:to({method:t.method,tables:[t.table]},e,1)},ZE=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();return lr(n)!==void 0?ui(e):z(n)?to(JE(s,e.getArguments()[0]),e,2):ui(e)},eS=(e,t)=>R(e,t,(s,n)=>{const i=ZE(s);if(i===void 0)return;const o=N(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),tS=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),sS=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||V(s,"args")===void 0)return!1}return Cs(e,t).opaque},nS=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=le(a);c!==void 0&&sS(a,c.receiver)&&s.push(tS(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},iS=(e,t)=>{const s=[];for(const n of b(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...nS(i,C(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},rS=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),ht=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),so=e=>!e.isAny(),no=e=>{const t=e.getType();if(!so(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:rS.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},oS=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},io={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},aS=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),cS={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},lS=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),dS={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},uS=(e,t,s)=>{if(!t.some(i=>jo(i)))return cS;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return lS.has(s.typeName)&&!n&&!t.some(i=>Dc(i))?dS:io},ro=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,d=a!==void 0&&e!==a?a:void 0,f=d===void 0?i:aS(d),p=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${p}`:p,title:"Procedure exists at runtime but is missing from the generated API"}},fS=(e,t,s)=>{const n=[];for(const i of se(e)){const o=r.isIdentifier(i.getNameNode())?Jt(i):[i.getName()],c=o.some(d=>ht(s,t,d))||!oS(i)?void 0:no(i),[l=i.getName()]=o;c!==void 0&&n.push(ro(t,l,c,i.getStartLineNumber(),uS(i,o,c)))}return n},pS=(e,t,s)=>{if(ht(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=no(i.getExpression());o!==void 0&&n.push(ro(t,"default",o,i.getStartLineNumber(),io))}return n},gS=(e,t,s)=>[...fS(e,t,s),...pS(e,t,s)],mS=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Jt(n).some(i=>ht(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Jt(n).find(o=>ht(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),hS=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),vS=(e,t,s)=>{const n=[],i=[];for(const a of b(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=C(t,a);n.push(...gS(c,l,s)),i.push(...mS(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!so(a.getType()))&&n.push(hS(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},ES=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},SS=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},xS=(e,t)=>R(e,t,(s,n)=>ES(s)?{file:n,line:s.getStartLineNumber(),scope:N(s),workflow:SS(s)}:void 0),oo=e=>e==="@lunora/workflow",yS=e=>new Set(e.getImportDeclarations().filter(t=>oo(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),AS=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),bS=(e,t)=>{const s=Pi(e,"defineWorkflowEvent",oo),n=yS(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of S(e,u.CallExpression)){if(!AS(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?bs(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new F("WORKFLOW_EVENT_NOT_LITERAL",Ce(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:C(t,e.getFilePath()),type:l.getLiteralValue()})}return i},NS=(e,t)=>{const s=b(t).flatMap(i=>bS(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new F("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},wS=e=>{const t=Ya(e,"compatibility_date"),s=Qa(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:Xa(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
32
+ `},PS=e=>`// Generated by @lunora/codegen. Do not edit.
33
+ // Serves the advisor procedure list to the app's Worker, which forwards it to a hosted Studio after the admin check.
34
+ const PROCEDURES = ${JSON.stringify(e)};
35
+
36
+ const ADVISOR_PROCEDURES_PATH = "/__lunora/advisor-procedures";
37
+
38
+ export default {
39
+ fetch(request: Request): Response {
40
+ if (new URL(request.url).pathname !== ADVISOR_PROCEDURES_PATH) {
41
+ return Response.json({ error: "not found" }, { status: 404 });
42
+ }
43
+
44
+ if (request.method !== "GET") {
45
+ return Response.json({ error: "GET only" }, { status: 405 });
46
+ }
47
+
48
+ return new Response(PROCEDURES, { headers: { "Content-Type": "application/json" }, status: 200 });
49
+ },
50
+ };
51
+ `,IS=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":PS(t),"wrangler.jsonc":wS(e)}:{},TS=(e,t)=>{for(const s of new Set([pa(t),Ri(e)])){const n=s===void 0?[]:La(s);if(s!==void 0&&n.length>0)throw new F("PROJECT_CONFIG_INVALID",`${Ss(s)} is invalid:
52
+ ${n.map(i=>` - ${i}`).join(`
53
+ `)}`)}},CS=(e,t,s)=>{for(const n of s)t[n]===void 0&&Ee(E(e,n),{force:!0});for(const n of[...new Set(s.map(i=>Se(E(e,i))))].toSorted((i,o)=>o.length-i.length))K(n)&&vs(n).length===0&&Ee(n,{recursive:!0})},OS=(e,t)=>{for(const s of vs(e,{recursive:!0,withFileTypes:!0})){const n=E(s.parentPath,s.name);s.isFile()&&t[xe(e,n)]===void 0&&Ee(n)}},qe=(e,t)=>{K(e)&&Ie(e,"utf8")===t||Co(e,t,"utf8")},ao=(e,t)=>{if(t===""){Ee(e,{force:!0});return}qe(e,t)},kS=(e,t)=>{const s=E(e,"_lunora","studio");vt(s,{recursive:!0});for(const[n,i]of Object.entries(t))ao(E(s,`${n}.json`),i)},RS=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){Ee(s,{force:!0,recursive:!0});return}if(K(s))for(const n of vs(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[xe(e,i)]===void 0&&Ee(i)}for(const[n,i]of Object.entries(t))vt(Se(E(e,n)),{recursive:!0}),qe(E(e,n),i)},LS=(e,t,s,n)=>{const i=E(e,t);if(n!==void 0)CS(i,s,n);else if(Object.keys(s).length===0){Ee(i,{force:!0,recursive:!0});return}else K(i)&&OS(i,s);for(const[o,a]of Object.entries(s)){const c=E(i,o);vt(Se(c),{recursive:!0}),qe(c,a)}},FS=e=>{try{const t=Kc(E(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},ct=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},DS=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,_S=(e,t)=>{K(e)||vt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{qe(E(e,n.name),n.content),s.push(n.name);break}case"directory":{LS(e,n.name,n.files,n.owned),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{RS(e,n.files),s.push(...Object.keys(n.files));break}default:ao(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},MS=e=>{const t=FS(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Bc({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Wc({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
54
+ `,openApiModuleContent:Vc(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
55
+ `,openRpcModuleContent:Uc(i)}},KS=".lunora-schema.json",$S=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},zS=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new F("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new F("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},BS=8,VS=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:d,shapes:f,usesSandbox:p,useUmbrella:g,workflows:h}=e,x=()=>Tc(()=>{const A=da(l,a,{lazyFunctions:o}),j=Aa(l,a);return{functions:A,httpRoutes:Cc(l,a),mutators:j}});let{erased:D,value:{functions:w,httpRoutes:U,mutators:ne}}=x();la(b(a).map(A=>l.getSourceFileOrThrow(A)),A=>xe(a,A.getFilePath())),ei([...w,...ne].map(A=>A.filePath)),ei(U.filter(A=>A.stream).map(A=>A.filePath),"http-stream");for(let A=1;;A+=1){const j=d?w:w.filter(B=>B.channel?.kind!=="room"&&B.lifecycle!=="socket"),ge=Jc({agents:t,functions:j,httpRoutes:U,mutators:ne,useUmbrella:g,workflows:h}),ie={agents:t,functions:j,lazyFunctions:o,migrations:c,mutators:ne,shapes:f,useUmbrella:g,usesSandbox:p},te=cl(ie),_=ll(ie),L=Zc({functions:w,useUmbrella:g}),de=E(a,"_generated",Bi),re=[[s,ge],[i,L],[n,te],...Object.entries(_).map(([B,W])=>[E(de,B),W])];if(A>=BS||re.every(([B,W])=>DS(l,B,W)))return{apiContent:ge,erased:D,functions:w,functionModulesContent:_,functionsContent:te,httpRoutes:U,internalContent:L,mutators:ne};for(const[B,W]of re)ct(l,B,W);({erased:D,value:{functions:w,httpRoutes:U,mutators:ne}}=x())}},WS=e=>{const t=$S(),s=t?Vt.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora");TS(e.projectRoot,n);const i=Fa(n),o=e.lazyFunctions===!0||i,a=Da(n),c=E(n,"schema.ts");if(!K(c))throw new F("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??Ga(n);aa(sE);const d=Lc(l,c,e.projectRoot);qE(d.tables,WE(l,n,Ki(e.projectRoot)));const{agents:f,authClaims:p,capabilities:g,containers:h,crons:x,dataModelContent:D,dependencies:w,entryCronTriggers:U,workerEntryCrons:ne,env:A,featureUsage:j,hasFlags:ge,hasNotify:ie,identity:te,platformGate:_,queues:L,serverContent:de,services:re,storageRulesMetadata:B,topics:W,usesSandbox:He,useUmbrella:q,workflows:H}=Kv({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:d,target:e.target,workerEntry:e.workerEntry});oE(d,d.jurisdiction===void 0?void 0:iE(l,n));const G=E(n,"_generated"),I=E(G,"dataModel.ts"),co=E(G,"server.ts"),lo=E(G,"api.ts"),uo=E(G,"internal.ts"),fo=E(G,"functions.ts");ct(l,I,D),ct(l,co,de);const Us=Object.fromEntries(re.filter(m=>m.rpcEntrypoint!==void 0).flatMap(m=>Object.entries(yc(m,G))));for(const[m,Bt]of Object.entries(Us))ct(l,E(G,m),Bt);const Ge=kc(l,n),me=Fc(l,n),Ct=_.signals.typedWebSockets!==!1,{apiContent:js,erased:po,functions:Q,functionModulesContent:qs,functionsContent:Hs,httpRoutes:Ot,internalContent:Gs,mutators:kt}=VS({agents:f,apiPath:lo,generatedFunctionsPath:fo,internalPath:uo,lazyFunctions:o,roomsSupported:Ct,lunoraDirectory:n,migrations:Ge,project:l,shapes:me,useUmbrella:q,usesSandbox:He,workflows:H}),Ys=Ka(l,n),Rt=$a(Ys,d,[...Q,...Ot].map(m=>m.filePath)),Ye=Ys.length>0,Oe=e.lint===!1&&!Ye?void 0:{callEdges:Xv(l,n),inserts:Oc(l,n),queries:gn(l,n,Q),tableWrites:eS(l,n),workflowCalls:xS(l,n)},go=$c(Oe?.queries??gn(l,n,Q)),ke=e.lint===!1||Oe===void 0?void 0:Wh(l,n,{callSites:Oe,containers:h,crons:x,functions:Q,modules:Rt,mutators:kt,queues:L,schema:d,shapes:me,topics:W,workflows:H,wranglerVariables:e.wranglerVariables}),Qs=ke===void 0?[]:Qh(e.projectRoot,wg(l,e.projectRoot,n,[...Ro(ke,{source:"static"}),...vS(l,n,{byName:new Set([...H,...L,...f,...h].map(m=>m.exportName)),byPath:new Set([...Q,...kt,...me,...Ge].map(m=>`${m.filePath}:${m.exportName}`))}),...iS(l,n),...Ic(po,n),...jc(L,e.wranglerQueueProducers)])),mo=Rc(l,n),Xs=yE(l,n);zS(me,Xs,SE(l,n));const ho=ge?tE(l,n):[],Lt=_.signals.vectorStore!==!1,vo=hc(Fe(e.projectRoot,e.target),"deliveryAuthorization"),Ft=Fe(e.projectRoot,e.target)==="cloudflare"?e.studioAssets:void 0,Re=HE(j,{containerCount:h.length,cronCount:x.length,dependencies:w,hasPaymentTables:NE(d.tables),queueCount:L.length,storageColumnCount:Object.keys($i(d)).length,storageRuleCount:B.rules.length,vectorIndexCount:d.vectorIndexes.length,target:Fe(e.projectRoot,e.target),vectorStoreSupported:Lt,workflowCount:H.length}),Js=t?Vt.now():0,Dt=zc(d,Ge.map(m=>m.id)),_t=hE(l,n),Zs=Sc({advisories:Qs.filter(m=>m.name!=="procedure_type_check_unavailable"),agents:f,capabilities:g,containers:h,env:A,flagKeys:ho,hasFlags:ge,hasNotify:ie,hasIpReaders:Q.some(m=>m.readsIp===!0)||me.some(m=>m.readsIp===!0),hasRooms:Ct&&Q.some(m=>m.channel?.kind==="room"),hasSensitiveArgs:f.length>0||Q.some(m=>Ha(m)),hasSecretValues:_.signals.secretValues===!0,hasSockets:Ct&&Q.some(m=>m.lifecycle==="socket"),lazyFunctions:o,hasVectors:Lt,liveStreamDeclarations:_t,liveStreams:_.signals.liveStreams===!0,maskMetadata:Xs,mutators:kt,queues:L,rlsMetadata:mo,schema:d,schemaSnapshot:Dt,shapes:me,services:re,storageRules:B,studioFeatures:Re,topics:W,useUmbrella:q,workflowEvents:NS(l,n),workflows:H}),en=Qc(me,w.has("@lunora/db"),q),tn=qc(h,d.jurisdiction),sn=Hc(H,{lazy:o}),nn=Gc(f,{lazy:o}),rn=Yc(L,e.wranglerQueueProducers),on=dl(_t,q),an=el(x),Eo=tl(Re.scheduler),Qe=vc(Fe(e.projectRoot,e.target)),So=Qe.supported?sl(q):"",xo=nl(d.tables,q,d.jurisdiction),yo=_a(e.projectRoot)?il(q):"",cn=rl(d.vectorIndexes),Xe=al(d,q),ln=Xc(w.has("@lunora/seed")),Je=e.apiSpec??"openapi",Ze=Je==="openapi"||Je==="both",Ao=ke?.procedureProtections??[],bo=ke===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...Ao]},Mt=`${JSON.stringify(bo,void 0,2)}
56
+ `,et=Je==="openrpc"||Je==="both",dn=_c(w.has("@lunora/auth")),un=Mc({agentWorkflows:f.map(m=>m.className),authClaims:p.map(m=>m.name),capabilities:g,emailAgents:f.filter(m=>m.onEmail===!0).map(m=>({className:m.className,exportName:m.exportName})),hasAccess:w.has("@lunora/cloudflare-access"),hasAuth:w.has("@lunora/auth"),hasFramework:w.has("@lunora/astro")||w.has("@lunora/svelte")||w.has("@lunora/vue")||K(E(e.projectRoot,"src","worker.ts")),hasGlobal:d.tables.some(m=>_i(m)),hasHyperdriveGlobal:d.tables.some(m=>Mi(m)),hasKvIntrospector:Re.kv,hasNotify:ie,hasQueue:L.some(m=>m.mode==="push"),liveStreams:_.signals.liveStreams===!0,liveStreamsWithheld:_.liveStreamsWithheld,liveStreamDeclarations:_t,hasAdminRevocations:Qe.supported,hasScheduler:Re.scheduler,hasSourcedTables:d.tables.some(m=>m.externalSource!==void 0),hasStorage:Re.storage,hasDeliveryAuthorization:vo,hasVectors:Lt,hasWorkflow:H.length>0,identity:te,jurisdiction:d.jurisdiction,jurisdictionPinsAuth:d.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:d.tables.map(m=>({name:m.name,shardMode:m.shardMode})),securityHeaders:Ma(n),spaAssetsBindings:e.spaAssetsBindings,studioAssetsBinding:Ft?.binding,useUmbrella:q,vectorIndexCount:d.vectorIndexes.length,voiceAgents:f.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsArchitecture:Ye,wantsOpenApi:Ze,wantsOpenRpc:et}),{openApiContent:Kt,openApiModuleContent:fn,openRpcContent:$t,openRpcModuleContent:pn}=MS({functions:Q,httpRoutes:Ot,modules:Rt,projectRoot:e.projectRoot,wantsArchitecture:Ye}),he=Ye&&Oe!==void 0?uv({...Oe,crons:x,functions:Q,httpRoutes:Ot,modules:Rt,queues:L,schema:d,services:re,topics:W,workflows:H}):void 0,zt=E(n,KS),No=K(zt),wo=e.dryRun?[]:_S(G,[{content:un,kind:"always",name:"app.ts"},{content:D,kind:"always",name:"dataModel.ts"},{content:js,kind:"always",name:"api.ts"},{content:Gs,kind:"always",name:"internal.ts"},{content:de,kind:"always",name:"server.ts"},{content:Hs,kind:"always",name:"functions.ts"},{files:qs,kind:"directory",name:Bi},{content:Zs,kind:"always",name:"shard.ts"},{content:an,kind:"always",name:"crons.ts"},{content:cn,kind:"always",name:"vectors.ts"},{content:Xe.global,kind:"always",name:"drizzle.global.ts"},{content:Xe.shard,kind:"always",name:"drizzle.shard.ts"},{content:tn,kind:"optional",name:"containers.ts"},{content:sn,kind:"optional",name:"workflows.ts"},{content:nn,kind:"optional",name:"agents.ts"},{content:rn,kind:"optional",name:"queues.ts"},{content:on,kind:"optional",name:"live.ts"},{content:Eo,kind:"optional",name:"scheduler.ts"},{content:xo,kind:"optional",name:"shardRegistry.ts"},{content:So,kind:"optional",name:"adminRevocations.ts"},{content:yo,kind:"optional",name:"durableObjects.ts"},{content:ln,kind:"optional",name:"seed.ts"},{content:dn,kind:"optional",name:"authModule.ts"},{content:en,kind:"optional",name:"collections.ts"},{files:Us,kind:"services"},{files:IS(e.projectRoot,Mt,a),kind:"directory",name:"companion",owned:Ja},{content:Ze?Kt:"",kind:"optional",name:"openapi.json"},{content:Ze?fn:"",kind:"optional",name:"openapi.ts"},{content:et?$t:"",kind:"optional",name:"openrpc.json"},{content:et?pn:"",kind:"optional",name:"openrpc.ts"},{content:Mt,kind:"optional",name:"advisor-procedures.json"},{content:he===void 0?"":`${JSON.stringify(he,void 0,2)}
57
+ `,kind:"optional",name:"architecture.json"},{content:he===void 0?"":fv(he),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&Ft!==void 0&&kS(E(e.projectRoot,Ft.directory),{architecture:he===void 0?"":JSON.stringify(he),openapi:Ze?Kt:"",openrpc:et?$t:""}),!e.dryRun&&!No&&qe(zt,Lo(Dt)),t){const m=Vt.now(),Bt=Math.round(m-s),Po=Math.round(Js-s),Io=Math.round(m-Js);console.error(`@lunora/codegen: codegen took ${Bt.toString()}ms (discovery ${Po.toString()}ms, emit ${Io.toString()}ms)`)}return{advisories:Qs,advisorContext:ke,agents:f,architecture:he,containers:h,cronTriggers:[...new Set([...ol(x),...U])],workerEntryCrons:ne,generated:{advisorProceduresJson:Mt,agents:nn,api:js,app:un,authModule:dn,collections:en,containers:tn,crons:an,dataModel:D,drizzleGlobal:Xe.global,drizzleShard:Xe.shard,functionModules:qs,functions:Hs,internal:Gs,live:on,openApi:Kt,openApiModule:fn,openRpc:$t,openRpcModule:pn,queues:rn,seed:ln,server:de,shard:Zs,vectors:cn,workflows:sn},migrations:Ge,outputDirectory:G,platformDiagnostics:Qe.diagnostic===void 0?_.diagnostics:[..._.diagnostics,Qe.diagnostic],queues:L,indexReferences:go,schemaSnapshot:Dt,schemaSnapshotPath:zt,schemaTables:d.tables,workflows:H,writtenFiles:wo}},d0=e=>zo(()=>WS(e));export{KS as SCHEMA_SNAPSHOT_FILENAME,Ga as createCodegenProject,p0 as findTsconfig,g0 as refreshCodegenProject,d0 as runCodegen,m0 as tsconfigFingerprint};