@lunora/codegen 1.0.0-alpha.268 → 1.0.0-alpha.269

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 a,serializeSchemaSnapshot as s}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as d}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as l,errorAdvisoryNames as n,errorPlatformDiagnosticNames as c,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DFsutD7g.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-Z3MMfNoG.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-Djd59sWZ.mjs";import{default as h}from"./packem_shared/discoverAuthApiCalls-CJtGjrRa.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-IJ5ME0fR.mjs";import{default as P}from"./packem_shared/discoverCrons-7FZyY_8h.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as U,mayReadCapabilityContext as y,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-CodLXY4q.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-BaRnAlw6.mjs";import{default as W}from"./packem_shared/discoverFunctions-BiAdFs_o.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-BkfwRTKx.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-CWXYIz5_.mjs";import{default as w}from"./packem_shared/discoverInserts-C52minJD.mjs";import{d as Y}from"./packem_shared/index-ndyk9srq.mjs";import{default as Z}from"./packem_shared/discoverMigrations-BQbzkdoU.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-BpaUVHB6.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-DZkD5QFA.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as ie,discoverNotifyConfig as me}from"./packem_shared/NOTIFY_FILENAME-CX_Gz1si.mjs";import{default as de}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-HhyYb-hV.mjs";import{QUEUES_FILENAME as ce,discoverQueues as xe}from"./packem_shared/QUEUES_FILENAME-B8RkoxY5.mjs";import{default as Ee}from"./packem_shared/discoverR2sqlCalls-D-GN7Agb.mjs";import{default as Ae}from"./packem_shared/discoverRlsProcedures-qwXpyg2N.mjs";import{default as ge}from"./packem_shared/discoverRlsMetadata-CG8Rv9n8.mjs";import{discoverSandboxUsage as Ne}from"./packem_shared/discoverSandboxUsage-Z3ZV6dlv.mjs";import{default as Re}from"./packem_shared/discoverSchema-Dja7ta2_.mjs";import{readServiceBindings as _e,resolveServiceBindings as he}from"./packem_shared/readServiceBindings-BNe3IN3v.mjs";import{SHAPES_FILENAME as Le,discoverShapes as Me}from"./packem_shared/SHAPES_FILENAME-D9dnZ1x2.mjs";import{default as Pe}from"./packem_shared/discoverStorageRulesMetadata-Bgm8JPFh.mjs";import{WORKFLOWS_FILENAME as be,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-DryVyDtJ.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-CT3NRUF_.mjs";import{isD1GlobalTable as je,isHyperdriveGlobalTable as Be}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as We,emitOpenApi as Ke,emitOpenApiModule as Ve}from"./packem_shared/buildOpenApiDocument-CcjqWh8u.mjs";import{OPENRPC_VERSION as Qe,buildOpenRpcDocument as qe,emitOpenRpc as we,emitOpenRpcModule as Je}from"./packem_shared/OPENRPC_VERSION-B73FvmDP.mjs";import{DEFAULT_TARGET as Xe,platformMatrixIds as Ze,readProjectTarget as $e,resolveCodegenTarget as er}from"./packem_shared/DEFAULT_TARGET-CadzOvvN.mjs";import{l as or,r as tr}from"./packem_shared/project-config-file-CD247zmH.mjs";import{SCHEMA_SNAPSHOT_FILENAME as sr,createCodegenProject as ir,findTsconfig as mr,refreshCodegenProject as fr,runCodegen as dr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-QrTRRuEd.mjs";import{SchemaSnapshotParseError as lr,buildSchemaSnapshot as nr,evaluateSchemaDrift as cr,parseSchemaSnapshot as xr}from"./packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs";import{default as Er}from"./packem_shared/fingerprintSchemaSources-BDXTtGpN.mjs";import{schemaFromIr as Ar}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as gr,validatorIrToJsonSchema as Cr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Or,SDK_TARGETS as Rr,generateSdk as Tr}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as hr,secretKindOf as Ir}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Mr}from"./packem_shared/emitDrizzleSchema-DohtnI8c.mjs";import{default as Pr}from"./packem_shared/emitFunctions-evl8Mx1a.mjs";import{default as br}from"./packem_shared/emitServer-DymRagL2.mjs";import{e as yr}from"./packem_shared/shard-WXSIZRpD.mjs";import{G as Hr}from"./packem_shared/shared-BXUKWh7t.mjs";import{MESSAGE_SOLUTIONS as Br,findSolutionByMessage as kr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as Kr,findProjectConfigFile as Vr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{s as Qr,t as qr,u as wr}from"./packem_shared/shard-runtime-B1nU9CRa.mjs";import{emitApi as Yr,emitCollections as Xr}from"./packem_shared/emitApi-xDIHPRPH.mjs";import{emitCrons as $r,emitScheduler as eo,emitVectors as ro,emitWranglerCronTriggers as oo}from"./packem_shared/emitCrons-DKeoaeqU.mjs";import{emitDataModel as ao}from"./packem_shared/emitDataModel-DSk9AkJe.mjs";import{isTypedSchema as io}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Xe as DEFAULT_TARGET,j as FLAGS_FILENAME,Hr as GENERATED_HEADER,gr as LUNORA_ERROR_CODES,Br as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,se as NOTIFY_FILENAME,Qe as OPENRPC_VERSION,Kr as PROJECT_CONFIG_FILENAMES,ce as QUEUES_FILENAME,sr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Or as SDK_LANGUAGES,Rr as SDK_TARGETS,Le as SHAPES_FILENAME,lr as SchemaSnapshotParseError,e as VERSION,be as WORKFLOWS_FILENAME,We as buildOpenApiDocument,qe as buildOpenRpcDocument,nr as buildSchemaSnapshot,b as capabilitiesUsedBy,ir as createCodegenProject,l as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,h as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyConfig,le as discoverQueries,xe as discoverQueues,Ee as discoverR2sqlCalls,ge as discoverRlsMetadata,Ae as discoverRlsProcedures,Ne as discoverSandboxUsage,Re as discoverSchema,Me as discoverShapes,Pe as discoverStorageRulesMetadata,Ue as discoverWorkflows,Qr as emitAgents,Yr as emitApi,Ge as emitApp,Xr as emitCollections,qr as emitContainers,$r as emitCrons,ao as emitDataModel,Mr as emitDrizzleSchema,Pr as emitFunctions,Ke as emitOpenApi,Ve as emitOpenApiModule,we as emitOpenRpc,Je as emitOpenRpcModule,eo as emitScheduler,br as emitServer,yr as emitShard,ro as emitVectors,wr as emitWorkflows,oo as emitWranglerCronTriggers,n as errorAdvisoryNames,c as errorPlatformDiagnosticNames,cr as evaluateSchemaDrift,kr as findLunoraSolution,Vr as findProjectConfigFile,mr as findTsconfig,Er as fingerprintSchemaSources,U as foldCapabilitySignals,m as formatAdvisories,Tr as generateSdk,je as isD1GlobalTable,Be as isHyperdriveGlobalTable,R as isTestPath,io as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,or as loadProjectConfig,y as mayReadCapabilityContext,xr as parseSchemaSnapshot,Ze as platformMatrixIds,de as readPackageDependencies,tr as readProjectConfigLiterals,$e as readProjectTarget,_e as readServiceBindings,hr as redact,fr as refreshCodegenProject,er as resolveCodegenTarget,he as resolveServiceBindings,dr as runCodegen,Ar as schemaFromIr,Ir as secretKindOf,s as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,d as toAdvisorContext,Cr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as a,serializeSchemaSnapshot as s}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as d}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as l,errorAdvisoryNames as n,errorPlatformDiagnosticNames as c,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-DFsutD7g.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-Z3MMfNoG.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-Djd59sWZ.mjs";import{default as h}from"./packem_shared/discoverAuthApiCalls-CJtGjrRa.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-IJ5ME0fR.mjs";import{default as P}from"./packem_shared/discoverCrons-7FZyY_8h.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as U,mayReadCapabilityContext as y,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-CodLXY4q.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-BaRnAlw6.mjs";import{default as W}from"./packem_shared/discoverFunctions-BiAdFs_o.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-BkfwRTKx.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-CWXYIz5_.mjs";import{default as w}from"./packem_shared/discoverInserts-C52minJD.mjs";import{d as Y}from"./packem_shared/index-ndyk9srq.mjs";import{default as Z}from"./packem_shared/discoverMigrations-BQbzkdoU.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-BpaUVHB6.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-DZkD5QFA.mjs";import{NOTIFY_FILENAME as se,discoverNotifyCalls as ie,discoverNotifyConfig as me}from"./packem_shared/NOTIFY_FILENAME-CX_Gz1si.mjs";import{default as de}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-HhyYb-hV.mjs";import{QUEUES_FILENAME as ce,discoverQueues as xe}from"./packem_shared/QUEUES_FILENAME-B8RkoxY5.mjs";import{default as Ee}from"./packem_shared/discoverR2sqlCalls-D-GN7Agb.mjs";import{default as Ae}from"./packem_shared/discoverRlsProcedures-qwXpyg2N.mjs";import{default as ge}from"./packem_shared/discoverRlsMetadata-CG8Rv9n8.mjs";import{discoverSandboxUsage as Ne}from"./packem_shared/discoverSandboxUsage-Z3ZV6dlv.mjs";import{default as Re}from"./packem_shared/discoverSchema-Csitf1Q4.mjs";import{readServiceBindings as _e,resolveServiceBindings as he}from"./packem_shared/readServiceBindings-BNe3IN3v.mjs";import{SHAPES_FILENAME as Le,discoverShapes as Me}from"./packem_shared/SHAPES_FILENAME-D9dnZ1x2.mjs";import{default as Pe}from"./packem_shared/discoverStorageRulesMetadata-Bgm8JPFh.mjs";import{WORKFLOWS_FILENAME as be,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-DryVyDtJ.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-CT3NRUF_.mjs";import{isD1GlobalTable as je,isHyperdriveGlobalTable as Be}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as We,emitOpenApi as Ke,emitOpenApiModule as Ve}from"./packem_shared/buildOpenApiDocument-CcjqWh8u.mjs";import{OPENRPC_VERSION as Qe,buildOpenRpcDocument as qe,emitOpenRpc as we,emitOpenRpcModule as Je}from"./packem_shared/OPENRPC_VERSION-B73FvmDP.mjs";import{DEFAULT_TARGET as Xe,platformMatrixIds as Ze,readProjectTarget as $e,resolveCodegenTarget as er}from"./packem_shared/DEFAULT_TARGET-CadzOvvN.mjs";import{l as or,r as tr}from"./packem_shared/project-config-file-CD247zmH.mjs";import{SCHEMA_SNAPSHOT_FILENAME as sr,createCodegenProject as ir,findTsconfig as mr,refreshCodegenProject as fr,runCodegen as dr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bqac8aBQ.mjs";import{SchemaSnapshotParseError as lr,buildSchemaSnapshot as nr,evaluateSchemaDrift as cr,parseSchemaSnapshot as xr}from"./packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs";import{default as Er}from"./packem_shared/fingerprintSchemaSources-BDXTtGpN.mjs";import{schemaFromIr as Ar}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as gr,validatorIrToJsonSchema as Cr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Or,SDK_TARGETS as Rr,generateSdk as Tr}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as hr,secretKindOf as Ir}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Mr}from"./packem_shared/emitDrizzleSchema-DohtnI8c.mjs";import{default as Pr}from"./packem_shared/emitFunctions-evl8Mx1a.mjs";import{default as br}from"./packem_shared/emitServer-DymRagL2.mjs";import{e as yr}from"./packem_shared/shard-DTJX0sDf.mjs";import{G as Hr}from"./packem_shared/shared-BXUKWh7t.mjs";import{MESSAGE_SOLUTIONS as Br,findSolutionByMessage as kr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as Kr,findProjectConfigFile as Vr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{s as Qr,t as qr,u as wr}from"./packem_shared/shard-runtime-BXp-lUsd.mjs";import{emitApi as Yr,emitCollections as Xr}from"./packem_shared/emitApi-xDIHPRPH.mjs";import{emitCrons as $r,emitScheduler as eo,emitVectors as ro,emitWranglerCronTriggers as oo}from"./packem_shared/emitCrons-DKeoaeqU.mjs";import{emitDataModel as ao}from"./packem_shared/emitDataModel-DSk9AkJe.mjs";import{isTypedSchema as io}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Xe as DEFAULT_TARGET,j as FLAGS_FILENAME,Hr as GENERATED_HEADER,gr as LUNORA_ERROR_CODES,Br as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,se as NOTIFY_FILENAME,Qe as OPENRPC_VERSION,Kr as PROJECT_CONFIG_FILENAMES,ce as QUEUES_FILENAME,sr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Or as SDK_LANGUAGES,Rr as SDK_TARGETS,Le as SHAPES_FILENAME,lr as SchemaSnapshotParseError,e as VERSION,be as WORKFLOWS_FILENAME,We as buildOpenApiDocument,qe as buildOpenRpcDocument,nr as buildSchemaSnapshot,b as capabilitiesUsedBy,ir as createCodegenProject,l as describeErrorLevelFindings,v as diagnosticAt,a as diffSchemaSnapshots,N as discoverAgents,h as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyConfig,le as discoverQueries,xe as discoverQueues,Ee as discoverR2sqlCalls,ge as discoverRlsMetadata,Ae as discoverRlsProcedures,Ne as discoverSandboxUsage,Re as discoverSchema,Me as discoverShapes,Pe as discoverStorageRulesMetadata,Ue as discoverWorkflows,Qr as emitAgents,Yr as emitApi,Ge as emitApp,Xr as emitCollections,qr as emitContainers,$r as emitCrons,ao as emitDataModel,Mr as emitDrizzleSchema,Pr as emitFunctions,Ke as emitOpenApi,Ve as emitOpenApiModule,we as emitOpenRpc,Je as emitOpenRpcModule,eo as emitScheduler,br as emitServer,yr as emitShard,ro as emitVectors,wr as emitWorkflows,oo as emitWranglerCronTriggers,n as errorAdvisoryNames,c as errorPlatformDiagnosticNames,cr as evaluateSchemaDrift,kr as findLunoraSolution,Vr as findProjectConfigFile,mr as findTsconfig,Er as fingerprintSchemaSources,U as foldCapabilitySignals,m as formatAdvisories,Tr as generateSdk,je as isD1GlobalTable,Be as isHyperdriveGlobalTable,R as isTestPath,io as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,or as loadProjectConfig,y as mayReadCapabilityContext,xr as parseSchemaSnapshot,Ze as platformMatrixIds,de as readPackageDependencies,tr as readProjectConfigLiterals,$e as readProjectTarget,_e as readServiceBindings,hr as redact,fr as refreshCodegenProject,er as resolveCodegenTarget,he as resolveServiceBindings,dr as runCodegen,Ar as schemaFromIr,Ir as secretKindOf,s as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,d as toAdvisorContext,Cr as validatorIrToJsonSchema};
@@ -1,11 +1,11 @@
1
- import{existsSync as O,mkdirSync as Xn,readFileSync as Jn,writeFileSync as Zn,rmSync as er}from"node:fs";import{join as S,dirname as Ne}from"node:path";import{performance as Xe}from"node:perf_hooks";import{runAdvisor as tr}from"@lunora/advisor";import{LunoraError as W}from"@lunora/errors";import{readJsonSync as sr}from"@visulima/fs";import{SyntaxKind as d,Node as i,Project as Xt}from"ts-morph";import{serializeSchemaSnapshot as nr}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as rr}from"./formatAdvisories-DwmUKYuc.mjs";import{r as ir,a as y,b as or}from"./project-config-file-CD247zmH.mjs";import{a as Jt,d as ar,r as cr}from"./modules-CyqMHMWS.mjs";import{QUEUES_FILENAME as lr,discoverQueueDeclarations as dr}from"./QUEUES_FILENAME-B8RkoxY5.mjs";import{WORKFLOWS_FILENAME as ur,discoverWorkflows as fr}from"./WORKFLOWS_FILENAME-DryVyDtJ.mjs";import{r as gr}from"./json-data-Chfs2Cz5.mjs";import{s as Me}from"./paths-C-9fwEgQ.mjs";import{G as pr}from"./shared-BXUKWh7t.mjs";import{CAPABILITIES as mr,usedCapabilities as hr}from"./CAPABILITY_PROBES-DFsutD7g.mjs";import{isD1GlobalTable as Bs,isHyperdriveGlobalTable as $s}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as vr}from"./AGENTS_FILENAME-Z3MMfNoG.mjs";import{discoverContainers as Er}from"./CONTAINERS_FILENAME-IJ5ME0fR.mjs";import xr from"./discoverCrons-7FZyY_8h.mjs";import{diagnosticAt as pe}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as _e}from"./module-specifiers-WF8iAydP.mjs";import{a as Us,b as V,d as K,f as R,g as xt,c as h,w as St,k as Sr,l as yr,h as Ar,j as ot,i as br}from"./attribution-DmwAff2x.mjs";import{contextPropertiesRead as Nr,discoverFeatureUsage as Pr}from"./capabilitiesUsedBy-CodLXY4q.mjs";import wr from"./readPackageDependencies-RHhGiz0k.mjs";import{listLunoraSourceFiles as E,unwrapExpression as v,listSecurityScanFiles as Ke,objectLiteralFromCallbackBody as js,propertyInitializer as P,lunoraRelativePath as w,bindingKeyName as me,collectCallRows as I,findObjectProperty as D,collectSecurityCallRows as Ir,collectNodeRows as at,RUN_METHODS as Vs,functionReferenceSegments as qs,limitNameOf as Ws,optionsObjectLiteral as Hs,handlerOf as Cr,chainRootOf as yt,outermostValueWrapper as b,isWriteTarget as ze,isSameNode as ue,isConstDeclaration as Z,returningFunctionOf as ct,walkChain as Tr,memberAccessOf as Or,isTestPath as Rr}from"./isTestPath-Djd59sWZ.mjs";import{discoverSandboxUsage as kr}from"./discoverSandboxUsage-Z3ZV6dlv.mjs";import{resolveServiceBindings as Fr}from"./readServiceBindings-BNe3IN3v.mjs";import Dr from"./discoverStorageRulesMetadata-Bgm8JPFh.mjs";import{a as A,c as H,d as Gs,e as Lr}from"./classify-procedure-call-B8KernCD.mjs";import{i as Mr}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as _r,resolveCodegenTarget as Ys,readTargetDiagnostics as Kr,studioPlatformFor as zr}from"./DEFAULT_TARGET-CadzOvvN.mjs";import{b as Qs,e as Br}from"./shard-WXSIZRpD.mjs";import $r from"./emitServer-DymRagL2.mjs";import{emitDataModel as Ur}from"./emitDataModel-DSk9AkJe.mjs";import{a as Zt,r as Je,i as U,b as jr,m as Xs,c as Be,e as Js,E as Zs,C as en,d as Vr,f as qr,g as Wr}from"./context-root-Z4sUTfYv.mjs";import{r as $e,s as Hr}from"./parse-validator-DLAJeWE4.mjs";import Gr from"./discoverAuthApiCalls-CJtGjrRa.mjs";import{i as Yr,a as Qr,e as Xr,b as Jr,d as Zr,c as ei}from"./unwrap-handler-return-BlGA5K9G.mjs";import ti from"./discoverFunctions-BiAdFs_o.mjs";import si from"./discoverHttpRoutes-BkfwRTKx.mjs";import ni from"./discoverHyperdriveCalls-CWXYIz5_.mjs";import ri from"./discoverInserts-C52minJD.mjs";import{m as At,a as Te,s as tn,d as ii}from"./index-ndyk9srq.mjs";import{e as sn}from"./exported-procedure-chains-DOQLEINN.mjs";import oi from"./discoverMigrations-BQbzkdoU.mjs";import{i as _,r as nn}from"./database-calls-Bd3kT6B1.mjs";import{MUTATORS_FILENAME as ai,isDefineMutatorCallee as ci,mutatorServerImplOf as li,discoverMutators as di}from"./MUTATORS_FILENAME-BpaUVHB6.mjs";import ui from"./discoverNondeterministicCalls-DZkD5QFA.mjs";import{discoverNotifyConfig as fi,discoverNotifyCalls as gi}from"./NOTIFY_FILENAME-CX_Gz1si.mjs";import pi from"./discoverQueries-HhyYb-hV.mjs";import mi from"./discoverR2sqlCalls-D-GN7Agb.mjs";import hi from"./discoverRlsProcedures-qwXpyg2N.mjs";import vi from"./discoverRlsMetadata-CG8Rv9n8.mjs";import Ei from"./discoverSchema-Dja7ta2_.mjs";import{secretKindOf as xi,redact as Si,isHeuristicSecretKind as yi,isSecretishName as Ai}from"./redact-Cy14LEnc.mjs";import{discoverShapes as bi}from"./SHAPES_FILENAME-D9dnZ1x2.mjs";import{i as Ni}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as Pi}from"./emitApp-CT3NRUF_.mjs";import{buildOpenApiDocument as wi,emitOpenApiModule as Ii}from"./buildOpenApiDocument-CcjqWh8u.mjs";import{buildOpenRpcDocument as Ci,emitOpenRpcModule as Ti}from"./OPENRPC_VERSION-B73FvmDP.mjs";import{buildSchemaSnapshot as Oi}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Ri,emitSeed as ki,emitApi as Fi}from"./emitApi-xDIHPRPH.mjs";import{t as Di,u as Li,s as Mi,v as _i}from"./shard-runtime-B1nU9CRa.mjs";import{emitCrons as Ki,emitScheduler as zi,emitShardRegistry as Bi,emitDurableObjects as $i,emitVectors as Ui,emitWranglerCronTriggers as ji}from"./emitCrons-DKeoaeqU.mjs";import Vi from"./emitDrizzleSchema-DohtnI8c.mjs";import qi from"./emitFunctions-evl8Mx1a.mjs";const es={error:"ERROR",info:"INFO",warn:"WARN"},ts={ERROR:2,INFO:0,WARN:1},Wi=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"}),Hi=(e,t)=>{const{advisor:s}=ir(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,r=n!==void 0&&Object.hasOwn(es,n)?es[n]:void 0;return r===void 0?[...t,Wi(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=>ts[o.level]>=ts[r])},Gi={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},rn=lr.replace(/\.ts$/u,""),Yi="crons",Qi=ur.replace(/\.ts$/u,""),ie=(e,t)=>`${Me(e)}:${t}`,Ze=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Xi=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Gi[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,...Ze("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Ze("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Ze("workflow",t.workflow,"workflow name")}))],Ji=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Zi=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Ji(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},eo=e=>Xi(e).flatMap(t=>Zi(t)),to=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:rn,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}`,r=s??n;return{file:Yi,from:`cron:${t.name}`,kind:"trigger",line:0,...r===void 0?{reason:"the cron has no target"}:{to:r}}})],so=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),et=(e,t)=>t===void 0?e:{...e,module:t},no=e=>{const t=new Map,s=new Map,n=so(e.modules),r=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&r(l,c.id)},a=(c,l)=>{c!==void 0&&r(ie(c.file,c.exportName),l)};for(const c of e.functions){const l=ie(c.filePath,c.exportName),u=`${Me(c.filePath)}.${c.exportName}`;o(et({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Jt(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ie(c.filePath,c.exportName);o(et({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Jt(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(et({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({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},ie(rn,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName});for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ie(Qi,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}},ro=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,io=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ie(e.file,e.exportName))??{reason:ro(e.exportName)},oo=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=io(e,t);if("reason"in n)return n;const{to:r}=e;return s.has(r)?{drawn:n.map(o=>({from:o,kind:e.kind,to:r}))}:{reason:`${r} is not declared`}},tt=e=>`${e.from}|${e.kind}|${e.to}`,ao=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,co=e=>{const{nodes:t,sites:s}=no(e),n=new Map,r=new Map;for(const o of[...to(e),...eo(e)]){const a=oo(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(tt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};r.set(ao(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>tt(o).localeCompare(tt(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:[...r.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},lo=e=>`${pr}export const architecture = ${gr(e,"Record<string, unknown>")};
2
- `,uo=(e,t)=>{if(!(!t||e.jurisdiction!=="fedramp"))throw new W("CODEGEN_DIAGNOSTIC",'@lunora/codegen: the schema pins data to the "fedramp" jurisdiction, but this app uses Cloudflare Artifacts (`ctx.artifacts`), which supports only the "eu" and "us" jurisdictions. Repo data would be stored outside the declared residency. Remove the `ctx.artifacts` usage, or pin the schema to a jurisdiction Artifacts supports.')},ss=(e,t="api")=>{const s=new Map;for(const n of e){const r=Me(n),o=s.get(r);if(o===void 0){s.set(r,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${r}" twice and the dispatch key "${r}:<fn>" would be ambiguous`:`the generated api.ts would declare "${r}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new W("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${r}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},fo=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:r=!1,usage:o}=t,a=[];e.tables.some(c=>Bs(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=>$s(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`"}),r&&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?[]:mr)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},go=(e,t,s={})=>{if(t===void 0)return;const n=fo(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const r=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
1
+ import{existsSync as O,mkdirSync as Xn,readFileSync as Jn,writeFileSync as Zn,rmSync as er}from"node:fs";import{join as S,dirname as Ne}from"node:path";import{performance as Xe}from"node:perf_hooks";import{runAdvisor as tr}from"@lunora/advisor";import{LunoraError as W}from"@lunora/errors";import{readJsonSync as sr}from"@visulima/fs";import{SyntaxKind as d,Node as i,Project as Xt}from"ts-morph";import{serializeSchemaSnapshot as nr}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as rr}from"./formatAdvisories-DwmUKYuc.mjs";import{r as ir,a as y,b as or}from"./project-config-file-CD247zmH.mjs";import{a as Jt,d as ar,r as cr}from"./modules-CyqMHMWS.mjs";import{QUEUES_FILENAME as lr,discoverQueueDeclarations as dr}from"./QUEUES_FILENAME-B8RkoxY5.mjs";import{WORKFLOWS_FILENAME as ur,discoverWorkflows as fr}from"./WORKFLOWS_FILENAME-DryVyDtJ.mjs";import{r as pr}from"./json-data-Chfs2Cz5.mjs";import{s as Me}from"./paths-C-9fwEgQ.mjs";import{G as gr}from"./shared-BXUKWh7t.mjs";import{CAPABILITIES as mr,usedCapabilities as hr}from"./CAPABILITY_PROBES-DFsutD7g.mjs";import{isD1GlobalTable as Bs,isHyperdriveGlobalTable as $s}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as vr}from"./AGENTS_FILENAME-Z3MMfNoG.mjs";import{discoverContainers as Er}from"./CONTAINERS_FILENAME-IJ5ME0fR.mjs";import xr from"./discoverCrons-7FZyY_8h.mjs";import{diagnosticAt as ge}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as _e}from"./module-specifiers-WF8iAydP.mjs";import{a as Us,b as V,d as K,f as R,g as xt,c as h,w as St,k as Sr,l as yr,h as Ar,j as ot,i as br}from"./attribution-DmwAff2x.mjs";import{contextPropertiesRead as Nr,discoverFeatureUsage as Pr}from"./capabilitiesUsedBy-CodLXY4q.mjs";import wr from"./readPackageDependencies-RHhGiz0k.mjs";import{listLunoraSourceFiles as E,unwrapExpression as v,listSecurityScanFiles as Ke,objectLiteralFromCallbackBody as js,propertyInitializer as P,lunoraRelativePath as w,bindingKeyName as me,collectCallRows as I,findObjectProperty as D,collectSecurityCallRows as Ir,collectNodeRows as at,RUN_METHODS as Vs,functionReferenceSegments as qs,limitNameOf as Ws,optionsObjectLiteral as Hs,handlerOf as Cr,chainRootOf as yt,outermostValueWrapper as b,isWriteTarget as ze,isSameNode as ue,isConstDeclaration as Z,returningFunctionOf as ct,walkChain as Tr,memberAccessOf as Or,isTestPath as Rr}from"./isTestPath-Djd59sWZ.mjs";import{discoverSandboxUsage as kr}from"./discoverSandboxUsage-Z3ZV6dlv.mjs";import{resolveServiceBindings as Fr}from"./readServiceBindings-BNe3IN3v.mjs";import Dr from"./discoverStorageRulesMetadata-Bgm8JPFh.mjs";import{a as A,c as H,d as Gs,e as Lr}from"./classify-procedure-call-B8KernCD.mjs";import{i as Mr}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as _r,resolveCodegenTarget as Ys,readTargetDiagnostics as Kr,studioPlatformFor as zr}from"./DEFAULT_TARGET-CadzOvvN.mjs";import{b as Qs,e as Br}from"./shard-DTJX0sDf.mjs";import $r from"./emitServer-DymRagL2.mjs";import{emitDataModel as Ur}from"./emitDataModel-DSk9AkJe.mjs";import{a as Zt,r as Je,i as U,b as jr,m as Xs,c as Be,e as Js,E as Zs,C as en,d as Vr,f as qr,g as Wr}from"./context-root-Z4sUTfYv.mjs";import{r as $e,s as Hr}from"./parse-validator-DLAJeWE4.mjs";import Gr from"./discoverAuthApiCalls-CJtGjrRa.mjs";import{i as Yr,a as Qr,e as Xr,b as Jr,d as Zr,c as ei}from"./unwrap-handler-return-BlGA5K9G.mjs";import ti from"./discoverFunctions-BiAdFs_o.mjs";import si from"./discoverHttpRoutes-BkfwRTKx.mjs";import ni from"./discoverHyperdriveCalls-CWXYIz5_.mjs";import ri from"./discoverInserts-C52minJD.mjs";import{m as At,a as Te,s as tn,d as ii}from"./index-ndyk9srq.mjs";import{e as sn}from"./exported-procedure-chains-DOQLEINN.mjs";import oi from"./discoverMigrations-BQbzkdoU.mjs";import{i as _,r as nn}from"./database-calls-Bd3kT6B1.mjs";import{MUTATORS_FILENAME as ai,isDefineMutatorCallee as ci,mutatorServerImplOf as li,discoverMutators as di}from"./MUTATORS_FILENAME-BpaUVHB6.mjs";import ui from"./discoverNondeterministicCalls-DZkD5QFA.mjs";import{discoverNotifyConfig as fi,discoverNotifyCalls as pi}from"./NOTIFY_FILENAME-CX_Gz1si.mjs";import gi from"./discoverQueries-HhyYb-hV.mjs";import mi from"./discoverR2sqlCalls-D-GN7Agb.mjs";import hi from"./discoverRlsProcedures-qwXpyg2N.mjs";import vi from"./discoverRlsMetadata-CG8Rv9n8.mjs";import Ei from"./discoverSchema-Csitf1Q4.mjs";import{secretKindOf as xi,redact as Si,isHeuristicSecretKind as yi,isSecretishName as Ai}from"./redact-Cy14LEnc.mjs";import{discoverShapes as bi}from"./SHAPES_FILENAME-D9dnZ1x2.mjs";import{i as Ni}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as Pi}from"./emitApp-CT3NRUF_.mjs";import{buildOpenApiDocument as wi,emitOpenApiModule as Ii}from"./buildOpenApiDocument-CcjqWh8u.mjs";import{buildOpenRpcDocument as Ci,emitOpenRpcModule as Ti}from"./OPENRPC_VERSION-B73FvmDP.mjs";import{buildSchemaSnapshot as Oi}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Ri,emitSeed as ki,emitApi as Fi}from"./emitApi-xDIHPRPH.mjs";import{t as Di,u as Li,s as Mi,v as _i}from"./shard-runtime-BXp-lUsd.mjs";import{emitCrons as Ki,emitScheduler as zi,emitShardRegistry as Bi,emitDurableObjects as $i,emitVectors as Ui,emitWranglerCronTriggers as ji}from"./emitCrons-DKeoaeqU.mjs";import Vi from"./emitDrizzleSchema-DohtnI8c.mjs";import qi from"./emitFunctions-evl8Mx1a.mjs";const es={error:"ERROR",info:"INFO",warn:"WARN"},ts={ERROR:2,INFO:0,WARN:1},Wi=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"}),Hi=(e,t)=>{const{advisor:s}=ir(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,r=n!==void 0&&Object.hasOwn(es,n)?es[n]:void 0;return r===void 0?[...t,Wi(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=>ts[o.level]>=ts[r])},Gi={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},rn=lr.replace(/\.ts$/u,""),Yi="crons",Qi=ur.replace(/\.ts$/u,""),ie=(e,t)=>`${Me(e)}:${t}`,Ze=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Xi=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Gi[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,...Ze("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Ze("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Ze("workflow",t.workflow,"workflow name")}))],Ji=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Zi=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Ji(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},eo=e=>Xi(e).flatMap(t=>Zi(t)),to=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:rn,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}`,r=s??n;return{file:Yi,from:`cron:${t.name}`,kind:"trigger",line:0,...r===void 0?{reason:"the cron has no target"}:{to:r}}})],so=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),et=(e,t)=>t===void 0?e:{...e,module:t},no=e=>{const t=new Map,s=new Map,n=so(e.modules),r=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&r(l,c.id)},a=(c,l)=>{c!==void 0&&r(ie(c.file,c.exportName),l)};for(const c of e.functions){const l=ie(c.filePath,c.exportName),u=`${Me(c.filePath)}.${c.exportName}`;o(et({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Jt(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ie(c.filePath,c.exportName);o(et({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Jt(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(et({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({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},ie(rn,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName});for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ie(Qi,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}},ro=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,io=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ie(e.file,e.exportName))??{reason:ro(e.exportName)},oo=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=io(e,t);if("reason"in n)return n;const{to:r}=e;return s.has(r)?{drawn:n.map(o=>({from:o,kind:e.kind,to:r}))}:{reason:`${r} is not declared`}},tt=e=>`${e.from}|${e.kind}|${e.to}`,ao=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,co=e=>{const{nodes:t,sites:s}=no(e),n=new Map,r=new Map;for(const o of[...to(e),...eo(e)]){const a=oo(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(tt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};r.set(ao(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>tt(o).localeCompare(tt(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:[...r.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},lo=e=>`${gr}export const architecture = ${pr(e,"Record<string, unknown>")};
2
+ `,uo=(e,t)=>{if(!(!t||e.jurisdiction!=="fedramp"))throw new W("CODEGEN_DIAGNOSTIC",'@lunora/codegen: the schema pins data to the "fedramp" jurisdiction, but this app uses Cloudflare Artifacts (`ctx.artifacts`), which supports only the "eu" and "us" jurisdictions. Repo data would be stored outside the declared residency. Remove the `ctx.artifacts` usage, or pin the schema to a jurisdiction Artifacts supports.')},ss=(e,t="api")=>{const s=new Map;for(const n of e){const r=Me(n),o=s.get(r);if(o===void 0){s.set(r,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${r}" twice and the dispatch key "${r}:<fn>" would be ambiguous`:`the generated api.ts would declare "${r}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new W("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${r}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},fo=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:r=!1,usage:o}=t,a=[];e.tables.some(c=>Bs(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=>$s(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`"}),r&&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?[]:mr)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},po=(e,t,s={})=>{if(t===void 0)return;const n=fo(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const r=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
3
3
  `);throw new W("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
4
4
  ${r}
5
5
 
6
- Install them with your package manager, then re-run codegen.`)},po="env.ts",mo=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return _e(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},ho=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&_e(n.getModuleSpecifierValue())}return!1},vo=e=>{if(i.isIdentifier(e))return mo(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&ho(t)}return!1},Eo=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!vo(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw pe(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=Us(s,"member");a!==void 0&&t.push({exportName:a})}return t},xo=(e,t)=>{const s=S(t,po);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=Eo(n);if(r.length!==0){if(r.length>1)throw pe(n,`lunora/env.ts declares ${r.length.toString()} defineEnv() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},on="identity.ts",So=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return _e(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},yo=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&_e(n.getModuleSpecifierValue())}return!1},Ao=e=>{if(i.isIdentifier(e))return So(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&yo(t)}return!1},bo=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Ao(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw pe(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Us(s,"member");a!==void 0&&t.push({exportName:a})}return t},No=(e,t)=>{const s=S(t,on);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=bo(n);if(r.length!==0){if(r.length>1)throw pe(n,`lunora/identity.ts declares ${r.length.toString()} defineIdentity() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},Po=new Set(["allowedHosts","deniedHosts","interceptHttps"]),wo=(e,t)=>{const s=v(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return v(e.getDescendantsOfKind(d.VariableDeclaration).find(r=>r.getName()===n)?.getInitializer())},Io=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(y(s));if(!i.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=v(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Co=new Set(["durable"]),To=new Set(["rollback"]),Oo=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},Ro=new Map([["defineContainer",{keys:Po,signal:"containerEgressPolicy"}],["defineStep",{keys:To,signal:"workflowRollback"}],["stream",{keys:Co,signal:"durableStreams"}]]),ko=(e,t)=>{const s=Ro.get(Oo(t));if(s!==void 0)return t.getArguments().some(n=>Io(wo(e,n),s.keys))?s.signal:void 0},Fo=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Nr(r).has("secrets"));for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=ko(r,o);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},Do="createWorker",Lo="extend",ns=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,rs=e=>{const t=[],s=ns(P(e,"backupCron"));s!==void 0&&t.push(s);const n=P(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)&&!i.isMethodDeclaration(r))continue;const o=ns(r.getNameNode());o!==void 0&&t.push(o)}return t},Mo=e=>{const t=A(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Do)return i.isObjectLiteralExpression(s)?rs(s):[];if(t!==Lo||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=js(s.getBody());return n===void 0?[]:rs(n)},_o=(e,t)=>{const s=[];for(const{filePath:n}of Ke(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression))s.push(...Mo(o))}return[...new Set(s)]},an=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:an(e.inner)},Ko=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const r=an(n);return r!==void 0&&t.has(r)}))},zo=(e,t)=>{const s=new Map,n=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const o=s.get(r.name);if(o!==void 0)throw new W("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${o} and agent "${r.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(r.className);if(a!==void 0)throw new W("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${a} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Bo=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:r}=e,o=No(s,t),a=xo(s,t),c=fr(s,t),{queues:l,topics:u}=dr(s,t),p=Fr(n),f=vr(s,t);zo(c,f);const m=Er(s,t),x=Dr(s,t),z=xr(s,t,c,f),B=_o(s,t),N=Fo(s,t),k=kr(s,t),q=Pr(s,t);q.browser=q.browser||k.usesSandboxBrowser;const G=_r(q,Ys(n,e.target),{agents:f.length>0,commitOrderedTables:r.tables.some(T=>T.commitOrdered===!0),cronTriggers:z.length>0,crossShardFanout:r.tables.some(T=>Mr(T)),containerEgressPolicy:N.containerEgressPolicy,containerRuntimeScheduling:m.some(T=>T.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(T=>T.sandbox===!0),durableStreams:N.durableStreams,globalTables:r.tables.some(T=>T.shardMode==="global"),queues:l.length>0,relationGraph:Ko(r),secrets:N.secrets,services:p.length>0,topics:u.length>0,vectorStore:r.vectorIndexes.length>0,workerLoaders:k.usesSandboxLoader,workflowRollback:N.workflowRollback,workflowSchedules:c.some(T=>T.schedules!==void 0)}),F=G.usage,te=hr(F),oe=G.signals.vectorStore!==!1,ae=G.signals.services===!1?[]:p,se=wr(n),he=se??new Set,$=he.has("lunorash");go(r,se,{hasVectors:oe,scheduler:F.scheduler||z.length>0,storage:F.storage||x.rules.length>0||Object.keys(Qs(r)).length>0,usage:F});const L=O(S(t,"flags.ts")),M=O(S(t,"notify.ts"));return{agents:f,capabilities:te,containers:m,crons:z,dataModelContent:Ur(r),declaredDependencies:se,dependencies:he,entryCronTriggers:B,env:a,featureUsage:F,hasFlags:L,hasNotify:M,identity:o,platformGate:{...G,diagnostics:[...Kr(n,e.target),...G.diagnostics]},queues:l,serverContent:$r({agents:f,capabilities:te,containers:m,env:a,hasVectors:oe,hasFlags:L,hasNotify:M,identity:o,queues:l,schema:r,generatedDirectory:S(t,"_generated"),services:ae,storageRuleBuckets:x.rules.map(T=>T.bucket),topics:u,useUmbrella:$,workflows:c}),services:ae,storageRulesMetadata:x,topics:u,usesSandbox:k.usesSandboxBrowser||k.usesSandboxContainer||k.usesSandboxFs,useUmbrella:$,workflows:c}},cn=new Set(["delete","get","head","options","patch","post","put"]),$o=new Set(["handler","stream"]),Uo=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,is=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),jo=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!cn.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Vo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||cn.has(n.getName()))break;s=n.getExpression()}return jo(s)},qo=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(is.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&is.has(s.getText()))return!0}return!1},Wo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!$o.has(n.getName()))return;const r=Vo(s);if(!r||!Uo.test(r.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&qo(o);return{exportName:K(e)??e.getName(),file:t,method:r.method,path:r.path,usesGuard:a}},Ho=(e,t)=>{const s=[];for(const n of V(e)){const r=Wo(n,t);r&&s.push(r)}return s},Go=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ho(r,w(t,n)))}return s},Yo=e=>{const t=e.getText(),s=n=>{const r=n.getNameNode();return i.isIdentifier(r)&&r.getText()===t};for(const n of e.getAncestors())if(!(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)&&!i.isFunctionDeclaration(n)))for(const r of n.getParameters()){const o=r.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Qo=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isObjectBindingPattern(s))return;const n=s.getParent();if(i.isBindingElement(n)){t=n;continue}return i.isParameterDeclaration(n)?me(t):void 0}},Xo=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=i.isFunctionLikeDeclaration(o)||i.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(i.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Zt(a)}))return!1;const n=R(e),r=i.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return r!==void 0&&(i.isParameterDeclaration(n)||i.isBindingElement(n))&&Zt(r)},os=(e,t)=>{const s=e.getParent();if(i.isPropertyAccessExpression(s)&&s.getNameNode()===e||i.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Yo(e);return n!==void 0&&Qo(n)===t?!0:t==="args"&&Xo(e)},ln=(e,t)=>i.isIdentifier(e)?os(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>os(s,t)),Jo=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},as=e=>{const t=i.isIdentifier(e)?R(e):void 0;return i.isVariableDeclaration(t)&&i.isIdentifier(t.getNameNode())&&!xt(t)?t.getInitializer():void 0},lt=e=>ln(e,"args"),Q=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let r,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(r=c,o=l)}return r},j=e=>{if(lt(e))return!0;const t=Q(e);return t!==void 0&&lt(t)},Zo=e=>{if(i.isCallExpression(e)||i.isNewExpression(e))return!1;const t=Q(e);return t===void 0||!(i.isCallExpression(t)||i.isNewExpression(t))},ee=e=>{if(Je(e))return!0;const t=as(e);if(t!==void 0&&Je(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(r=>{const o=as(r);return o!==void 0&&Je(o)})},Pe=(e,t)=>ln(e,t),ea=(e,t)=>{if(Pe(e,t))return!0;const s=Q(e);if(s!==void 0&&Pe(s,t))return!0;const n=Jo(e);if(n!==void 0){const r=Q(n);return r!==void 0&&Pe(r,t)}return!1},ta=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:U(e.getExpression(),["ai"]),sa=(e,t)=>{if(!ta(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)||ee(s)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},na=(e,t)=>I(e,t,sa),ra=new Set(["generateText","streamText"]),ia=new Set(["messages","prompt","system"]),oa=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","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"]}],aa=(e,t)=>oa.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ca=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=[jr(t.getExpression()),t.getExpression().getText()].find(r=>r!==void 0&&aa(r,s));return n===void 0?void 0:`${n}.${s}`},la=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ca(t);if(s!==void 0)return s}},da=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],r=n?.getNameNode();if(r===void 0||!i.isObjectBindingPattern(r))return t;for(const o of r.getElements()){const a=me(o),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},ua=e=>{if(lt(e))return!0;const t=da(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},fa=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!ia.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&ua(s))return!0}return!1},ga=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=A(n.getExpression());if(r===void 0||!ra.has(r))continue;const[o]=n.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(A(c.getExpression())==="tool"&&(a=la(c),a!==void 0))break;a!==void 0&&s.push({scope:h(n),file:t,line:n.getStartLineNumber(),method:r,sideEffect:a,userInputDerived:fa(o)})}return s},pa=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ga(r,w(t,n)))}return s},ma=e=>U(e,["fetch"]),ha=(e,t)=>{if(!ma(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},va=(e,t)=>I(e,t,ha),bt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=$e(s.getExpression());return n===void 0||bt(n,t)})}finally{t.delete(e)}},Ea=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=D(t,"args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),r=n===void 0?void 0:$e(n);return r===void 0?{objects:[],opaque:!0}:{objects:[r],opaque:bt(r)}},xa=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const r=n.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&i.isExpression(o)?$e(o):void 0;a===void 0?s=!0:(t.push(a),s||=bt(a))}n=r.getExpression()}return{objects:t,opaque:s}},Nt=(e,t)=>t?xa(t):Ea(e),dn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=$e(s.getExpression());return n===void 0?[]:dn(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Sa=e=>e.flatMap(t=>dn(t,new Set)),ya=new Set(["check","length","max"]),dt=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Aa=e=>[e,...e.getDescendants()].filter(t=>dt(t)!==void 0),ba=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(ya.has(s.getName()))return!0;t=n}},Na=e=>{const t=[],s=[];for(const n of e)for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=Aa(o),c=y(r);a.some(l=>dt(l)==="any")?t.push(c):a.some(l=>dt(l)==="string"&&!ba(l))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Pa=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=H(s);if(n?.visibility!=="public")return;const{objects:r}=Nt(s,n.receiver),{anyArgs:o,unboundedStringArgs:a}=Na(r);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:K(e)??e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},wa=(e,t)=>{const s=[];for(const n of V(e)){const r=Pa(n,t);r&&s.push(r)}return s},Ia=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wa(r,w(t,n)))}return s},st=e=>e?.getKind()===d.TrueKeyword,Ca=e=>e?.getKind()===d.FalseKeyword,Ta=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Oa=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Ra=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&A(t.getExpression())==="scim"),ka=e=>e!==void 0&&i.isCallExpression(e)&&Oa.has(A(e.getExpression())??""),Fa=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Da=e=>{const t=P(e,"advanced"),s=P(e,"emailAndPassword"),n=P(e,"session");return{analyzable:!0,disableCsrfCheck:st(P(t,"disableCSRFCheck")),emailPasswordEnabled:st(P(s,"enabled")),requireEmailVerification:st(P(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Ra(P(e,"plugins"))&&ka(P(e,"database")),secureCookiesDisabled:Ca(P(t,"useSecureCookies")),sessionFreshAgeZero:Ta(P(n,"freshAge")),trustedOriginsWildcard:Fa(P(e,"trustedOrigins"))}},La=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Ma=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),r=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?Da(s):La();return{scope:h(e),file:t,line:e.getStartLineNumber(),...r}},_a=(e,t)=>Ir(e,t,Ma),Ka=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Xs(e.getExpression(),t.matchReceiver)?s:void 0},za=(e,t,s)=>{const n=Ka(e.getExpression(),s);if(n===void 0)return;const r=e.getArguments()[s.argIndex];if(!(!r||!j(r)||ee(r))&&!(s.requireUnmodifiedReach===!0&&!Zo(r)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:n}},Ue=(e,t,s)=>I(e,t,(n,r)=>za(n,r,s)),Ba=new Set(["content","pdf","scrape","screenshot"]),$a=(e,t)=>Ue(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ba}),un=e=>{const t=qs(e);return t===void 0?void 0:`${Me(t.slice(0,-1).join("/"))}:${String(t.at(-1))}`},fn=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Ua=e=>{if(!i.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||i.isIdentifier(t)&&t.getText()==="scheduler"},ja=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Va=(e,t)=>{const s=un(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"}:void 0},qa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),[n,r]=e.getArguments();if(Vs.has(s))return Va(s,n);if((s==="runAfter"||s==="runAt")&&Ua(t)){const c=un(r);return c===void 0?{kind:"schedule",reason:"the scheduled function is not a static api.* / internal.* chain"}:{kind:"schedule",target:c}}const o=ja.get(s),a=o===void 0?void 0:fn(t,o.surface);return o===void 0||a===void 0?void 0:{kind:o.kind,target:a}},cs=(e,t,s)=>s===void 0?void 0:{...s,file:t,line:e.getStartLineNumber(),scope:h(e)},Wa=(e,t)=>[...I(e,t,(s,n)=>cs(s,n,qa(s))),...at(e,t,d.PropertyAccessExpression,(s,n)=>{const r=fn(s,"services");return cs(s,n,r===void 0?void 0:{kind:"invoke",target:r})})],Ha=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Ga=new Set(["RateLimiter"]),Ya=new Set(["extend"]),ls="lunora",Qa=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],gn=e=>{const t=[],s=[];let n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=y(r);t.push(o),r.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,presentKeys:t,trueKeys:s}},ut=e=>e&&i.isObjectLiteralExpression(e)?gn(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Xa=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&js(t.getBody());return s?gn(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Ja=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=A(n.getExpression());r!==void 0&&(Ha.has(r)?s.push({callee:r,file:t,line:n.getStartLineNumber(),...ut(n.getArguments()[0])}):Ya.has(r)&&s.push({callee:r,file:t,line:n.getStartLineNumber(),...Xa(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const r=A(n.getExpression());r===void 0||!Ga.has(r)||s.push({callee:r,file:t,line:n.getStartLineNumber(),...ut(n.getArguments()[0])})}return s},Za=(e,t)=>{for(const s of Qa){const n=S(t,s);if(!O(n))continue;const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of r.getDescendantsOfKind(d.CallExpression))A(a.getExpression())===ls&&o.push({callee:ls,file:s,line:a.getStartLineNumber(),...ut(a.getArguments()[0])});return o}return[]},ec=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Ke(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ja(o,n))}return s.push(...Za(e,Ne(t))),s},ds="ctx.containers.",tc=e=>{if(!e.startsWith(ds))return!1;const t=e.slice(ds.length);return t.length>0&&!t.includes(".")},sc=(e,t)=>Ue(e,t,{argIndex:0,matchReceiver:tc,methods:new Set(["get"])}),nc=new Set(["allow","deny","setAllowed"]),rc=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=D(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},ic=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!rc(e)))return{detail:"enableInternet: true",scope:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},oc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!nc.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},ac=(e,t)=>ic(e,t)??oc(e,t),cc=(e,t)=>I(e,t,ac),lc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),dc=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return lc.has(s)?s:void 0},uc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const r=y(n);t.push(r);const o=n.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(r);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},fc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Ke(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=dc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&i.isObjectLiteralExpression(l)?uc(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},gc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),pc=new Set(["dbRateLimit","rateLimit"]),mc=e=>{const t=Hs(e);if(!t)return!1;const s=D(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},hc=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const n=gc.get(s);if(n!==void 0)return{callee:s,scope:h(e),failOpen:mc(e.getArguments()[n]),file:t,limitName:pc.has(s)?Ws(e):"",line:e.getStartLineNumber()}},vc=(e,t)=>I(e,t,hc),Ec=new Set(["boolean","number","object","string"]),xc=e=>{const t=e.getName();if(!Ec.has(t))return;const s=e.getExpression();return U(s,["flags"])||U(s,["flags","details"])?t:void 0},Sc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=xc(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const r=n.getLiteralValue();return r.length>0?{key:r,type:s}:void 0},yc=(e,t)=>{const s=new Map;for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=Sc(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,r])=>({key:n,type:r})).toSorted((n,r)=>n.key.localeCompare(r.key))},Ac=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=H(t);if(s?.kind!=="query")return;const n=Cr(t,s.receiver);return n?{exportName:K(e)??e.getName(),handler:n}:void 0},us=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},bc=e=>{const t=us(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=us(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Nc=(e,t)=>{const s=[];for(const n of Be(e.handler,"flags"))s.push({callee:bc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Pc=(e,t)=>{const s=[];for(const n of V(e)){const r=Ac(n);r&&s.push(...Nc(r,t))}return s},wc=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Pc(r,w(t,n)))}return s},Ic=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:U(e.getExpression(),["flags"]),Cc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Tc=(e,t)=>{if(!Ic(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const r=s.getLiteralValue(),o=Cc(n);if(!(r.length===0||o===void 0))return{defaultValue:o,scope:h(e),file:t,key:r,line:e.getStartLineNumber()}},Oc=(e,t)=>I(e,t,Tc),Rc=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 r=n.getTypeAtLocation(e),o=r.getText(e);if(!o||o==="any"||o==="never"||Yr(o))return;const a=e.getSourceFile().getFilePath();if(Qr(r,e,a)){const c=Xr(r,e,a,0,new Set);return c===void 0&&Jr(o),c}return o},kc=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Fc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Dc=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of r.getDescendantsOfKind(d.CallExpression))kc(a)&&s.push({file:o,indexName:Fc(a),line:a.getStartLineNumber()})}return s},fe=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,pn=e=>{const t=e.getArguments()[0],s=fe(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=D(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?fe(n.getInitializer()):void 0},Lc=new Set(["delete","get","head","options","patch","post","put"]),Mc=new Set(["handler","stream"]),_c=new Set(["runAction","runMutation"]),Kc=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),ge=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,mn=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(me(s)===t){const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0}}},fs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:mn(s,"ctx")},gs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:mn(s,"request")},ps=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const r of n){const o=r.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(_c.has(a)&&ge(c,t))return a;if(Kc.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&ge(c.getExpression(),t))return`db.${a}`}},ms=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&ge(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const r=n.getNameNode();if(!(!i.isObjectBindingPattern(r)||!ge(n.getInitializer(),t))){for(const o of r.getElements())if(me(o)==="auth")return!0}}return!1},zc=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Bc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&ge(n.getExpression(),t)},$c=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],hn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:$c(s)},Uc=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const r=n.getParent();if(!i.isCallExpression(r))return[];const o=r.getExpression();if(!i.isPropertyAccessExpression(o))return[];const a=o.getExpression();return i.isIdentifier(a)?hn(t,a.getText()):[]}return[]},jc=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=hn(s,t.getText());return n.length>0?n:Uc(t,s)},hs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(r=>Bc(r,t)&&jc(r).some(o=>zc.test(o)))},Vc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Mc.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const r=n.getName();if(Lc.has(r)){const o=n.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?r.toUpperCase():void 0}s=n.getExpression()}},qc=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=fe(e.getArguments()[0]),l=c&&fs(c,!0);if(!c||l===void 0||hs(c,gs(c,!0)))return;const u=ps(c,l);return u===void 0?void 0:{scope:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ms(c,l),sideEffect:u}}const n=Vc(e);if(n===void 0)return;const r=fe(e.getArguments()[0]),o=r&&fs(r,!1);if(!r||o===void 0||hs(r,gs(r,!1)))return;const a=ps(r,o);return a===void 0?void 0:{scope:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:ms(r,o),sideEffect:a}},Wc=(e,t)=>I(e,t,qc),Hc=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Gc=new Set(["append","set"]),vn=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",vs=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Hc.has(A(n.getExpression())??"")&&Pe(n,t)),Yc=(e,t)=>{if(vs(e,t))return!0;const s=Q(e);return s!==void 0&&vs(s,t)},ft=(e,t)=>ea(e,t)&&!Yc(e,t),Qc=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&i.isNewExpression(t)&&A(t.getExpression())==="Headers"},Oe=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Pt=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const r=n.getInitializer();r!==void 0&&ft(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:vn(n.getNameNode()),line:r.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const r=n.getNameNode();ft(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:r.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const r=Oe(n.getExpression());r!==void 0&&Pt(r,t,s)}},En=(e,t)=>{const s=Oe(e);if(s===void 0)return;const n=D(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const r=Oe(n.getInitializer());r!==void 0&&Pt(r,"response-init",t)},Xc=(e,t)=>{const s=A(e.getExpression());if(s==="Response")En(e.getArguments()[1],t);else if(s==="Headers"){const n=Oe(e.getArguments()[0]);n!==void 0&&Pt(n,"headers-ctor",t)}},Jc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),r=s.getExpression();if(n==="json"&&i.isIdentifier(r)&&r.getText()==="Response"){En(e.getArguments()[1],t);return}if(Gc.has(n)&&Qc(r)){const o=e.getArguments()[1];o!==void 0&&ft(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:vn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Zc=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Xc(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Jc(s,t)},el=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=fe(e.getArguments()[0]);if(n===void 0)return[];const r=n.getParameters()[1];if(r===void 0)return[];const o=r.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return Zc(n,{scope:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},tl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...el(n,t));return s},sl=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tl(r,w(t,n)))}return s},nl=new Set(["auth","context.auth"]),rl="userId",il=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(y(s))}return t},ol=(e,t)=>{const s=S(t,on);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){if(A(r.getExpression())!=="defineIdentity")continue;const[o]=r.getArguments();return o&&i.isObjectLiteralExpression(o)?il(o):void 0}},Es=e=>{if(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return nl.has(t.getText())||U(t,["auth"])?e:void 0},al=e=>{if(i.isPropertyAccessExpression(e)&&Es(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Es(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},xs=(e,t,s)=>{const n=al(e);return n===void 0?void 0:{declared:n===rl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:h(e)}},cl=(e,t)=>{const s=ol(e,t);return s===void 0?[]:[...at(e,t,d.PropertyAccessExpression,(n,r)=>xs(n,r,s)),...at(e,t,d.ElementAccessExpression,(n,r)=>xs(n,r,s))]},ll=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=P(s,"key");if(!(!n||!j(n)||ee(n)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},dl=(e,t)=>I(e,t,ll),ul=e=>{if(i.isComputedPropertyName(e)){const t=e.getExpression();return i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return i.isStringLiteral(e)?e.getLiteralValue():e.getText()},fl=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=ul(t.getNameNode());return s===void 0||s==="namespace"}),gl=(e,t)=>{for(const{filePath:s}of Ke(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){const o=r.getExpression(),[a]=r.getArguments();if(!(!i.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!i.isObjectLiteralExpression(a)||fl(a)))return r}}},pl="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",ml=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw pe(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 (${pl}). 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})},hl=new Set(["delete","get","getRaw","getWithMetadata","put"]),vl=(e,t,s=[])=>{const n=Ue(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:hl});return St(n,s)},El=new Set(["queue","send"]),Ss=new Set(["bcc","cc","to"]),xl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!El.has(t))return;const s=e.getExpression();return U(s,["mail"])||U(s,["email"])?t:void 0},Sl=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ss.has(y(t))&&j(n)&&!ee(n)}if(!i.isPropertyAssignment(t)||!Ss.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&j(s)&&!ee(s)}):!1,yl=(e,t)=>{const s=xl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Sl(n)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s}},Al=(e,t)=>I(e,t,yl),bl=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,Nl=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?bl(e):!0,xn=(e,t=!1)=>{for(const s of e.getProperties()){if(Nl(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||xn(n,!0))return!0}return!1},Pl=(e,t)=>{for(const s of E(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:r}of sn(n))for(const o of At(r)){const a=o.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||xn(a)))return!0}}return!1},wl=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const r=Te(n);if(r===void 0||!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!i.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Te(a);c!==void 0&&s.push({column:c,strategy:tn(a),table:r})}}return s},Il=(e,t)=>{const s=new Map;for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of sn(r))for(const a of At(o))for(const c of wl(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Cl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){const a=Te(o);if(a===void 0||!i.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Te(l);if(u===void 0)continue;const p=tn(l);p!=="custom"&&r.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:p,table:a})}}return r},Tl=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;return n?.receiver?At(n.receiver).flatMap(r=>Cl(r,K(e)??e.getName(),t)):[]},Ol=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Tl(a,o))}return s},Rl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},kl=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=D(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},Fl=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ci(s.getExpression())?s:void 0},Dl=e=>{const t=Fl(e),s=t===void 0?void 0:kl(t);if(s===void 0)return[];const n=e.getNameNode(),r=i.isIdentifier(n)?K(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Rl(o)).map(o=>({exportName:r,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Ll=e=>e.getVariableDeclarations().flatMap(t=>Dl(t)),Ml=(e,t)=>{const s=S(t,ai);if(!O(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Ll(n)},_l=new Set(["delete","get","patch"]),Kl=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),zl=new Set(["auth","identity","session","user"]),Bl=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),$l=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Ul=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},jl=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Vl=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,ql=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>jl(s.getExpression(),t)&&Vl(s.getThenStatement())),Wl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const r=n.getName();if(!_l.has(r))continue;const o=n.getExpression();if(!(_(o)||i.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return r}},Hl=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Js(yt(s))!==void 0)),Gl=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Bl.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Yl=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Kl.has(t.getText()))return!0;return[...zl].some(t=>Be(e,t).length>0)?!0:Hl(e)||Gl(e)},Ql=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=H(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const r=pn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&Gs(n.receiver,"use","rls"),a=Yl(r),c=new Set,l=[];for(const u of r.getDescendantsOfKind(d.CallExpression)){const p=$l(u);if(p===void 0)continue;const f=Ul(u);if(f===void 0||c.has(f)||!ql(r,f))continue;const m=Wl(r,f);m!==void 0&&(c.add(f),l.push({exportName:K(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:p,usesRls:o,visibility:n.visibility}))}return l},Xl=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Ql(a,o))}return s},Sn=(e,t)=>{const s=i.isIdentifier(e)&&t!==void 0?R(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?i.isIdentifier(t.getNameNode()):i.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Jl=e=>{const t=b(e),s=t.getParent();return(i.isPropertyAccessExpression(s)||i.isElementAccessExpression(s))&&s.getExpression()===t&&!ze(s)},Zl=e=>{const t=b(e).getParent();return i.isVariableDeclaration(t)&&i.isObjectBindingPattern(t.getNameNode())},ed=e=>{const s=b(e).getParent();if(i.isSpreadAssignment(s)||i.isSpreadElement(s)){const n=s.getParent();return(i.isObjectLiteralExpression(n)||i.isArrayLiteralExpression(n))&&!ze(n)}return i.isTemplateSpan(s)&&!i.isTaggedTemplateExpression(s.getParent().getParent())},Re=e=>{const t=R(e);return t===void 0||yr(t.getSourceFile())},gt=(e,t)=>{const s=b(e),n=s.getParent();if(!i.isCallExpression(n))return!1;const r=n.getArguments().indexOf(s),o=v(n.getExpression());if(r===-1||o===void 0)return!1;if(i.isIdentifier(o))return o.getText()==="structuredClone"&&Re(o);if(Sn(yt(o),t))return!(i.isPropertyAccessExpression(o)&&Zs.has(o.getName()))||i.isExpressionStatement(b(i.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!i.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!i.isIdentifier(a)||!Re(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"&&r>0;default:return!1}},we={kind:"opaque"},td={kind:"unreached"},sd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>i.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>i.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&i.isFunctionDeclaration(n)?n:void 0},pt=e=>{const t=v(e);if(i.isArrowFunction(t)||i.isFunctionExpression(t))return t;const s=i.isIdentifier(t)?R(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(i.isFunctionDeclaration(s)){const r=sd(s);return r===void 0||xt(r)?void 0:r}const n=Z(s)?v(s.getInitializer()):void 0;return i.isArrowFunction(n)||i.isFunctionExpression(n)?n:void 0},yn=(e,t,s)=>{const n=t.getArguments(),r=n.indexOf(s),o=r===-1||n.slice(0,r+1).some(l=>i.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[r];return o?we:c===void 0?a.some(l=>l.isRestParameter())?we:td:c.isRestParameter()?we:{kind:"parameter",parameter:c}},nd=e=>{const t=b(e),s=t.getParent();if(!i.isCallExpression(s)||s.getExpression()===t)return;const n=pt(s.getExpression());return n===void 0?we:yn(n,s,t)},rd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),id=e=>i.isForInStatement(e)?e.getExpression():i.isConditionalExpression(e)?e.getCondition():i.isElementAccessExpression(e)?e.getArgumentExpression():void 0,An=e=>{const t=b(e),s=t.getParent();if(i.isIfStatement(s)||i.isWhileStatement(s)||i.isDoStatement(s)||i.isSwitchStatement(s)||i.isCaseClause(s)||i.isTypeOfExpression(s)||i.isVoidExpression(s)||i.isComputedPropertyName(s))return!0;if(i.isTemplateSpan(s))return!i.isTaggedTemplateExpression(s.getParent().getParent());const n=id(s);if(n!==void 0)return ue(n,t);if(i.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!i.isBinaryExpression(s))return!1;const r=s.getOperatorToken().getKind(),o=r>=d.FirstAssignment&&r<=d.LastAssignment,a=r===d.QuestionQuestionToken||r===d.BarBarToken||r===d.AmpersandAmpersandToken;return!o&&!a},od=4,bn=(e,t,s=0)=>{if(Sr(e))return!0;if(Jl(e)){const r=b(e).getParent(),o=i.isElementAccessExpression(r)?r.getArgumentExpression():void 0,a=i.isStringLiteral(o)?o.getLiteralValue():void 0,c=i.isPropertyAccessExpression(r)?r.getName():a;return c===void 0||!rd.has(c)}if(Zl(e)||ed(e)||An(e)||gt(e,t))return!0;const n=nd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&ad(n.parameter,s+1)},ys=new WeakMap,ad=(e,t=0)=>{const s=e.getNameNode();if(!i.isIdentifier(s))return!0;const n=ys.get(e.compilerNode);if(n!==void 0)return n;if(t>od)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||R(a)?.compilerNode!==e.compilerNode||bn(a,void 0,t));return(o||t===0)&&ys.set(e.compilerNode,o),o},As=new WeakMap,cd=(e,t)=>{const s=i.isFunctionExpression(e)?e.getNameNode():void 0;if(!i.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(r=>{if(r===s||!n.has(r.getText()))return!1;const o=R(r)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},ld=(e,t,s)=>{const{context:n,impl:r}=e,o=As.get(r.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=i.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(f=>{const m=f.getNameNode();return i.isIdentifier(m)?[m]:[]}),l=new Map(c.map(f=>[f.getText(),f.getParentOrThrow().compilerNode])),u=f=>i.isIdentifier(a)?bn(f,n):!ze(f),p=!cd(r,s)&&c.every(f=>(f.getSymbol()?.getDeclarations().length??0)===1)&&r.getDescendantsOfKind(d.Identifier).every(f=>{const m=f.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(f)||R(f)?.compilerNode!==x?!0:u(f)});return As.set(r.compilerNode,p),p},bs=new WeakMap,dd=e=>{let t=bs.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=li(s);return n===void 0?[]:[[n.compilerNode,s]]})),bs.set(e.compilerNode,t)),t},ud=e=>{const t=dd(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[r,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:r,impl:s,mutatorName:K(n)??n.getName()};return a!==void 0&&ld(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},fd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),gd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),mt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Nn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>i.isIdentifier(t.getNameNode())),pd=e=>{const t=b(e),s=t.getParent();if(i.isVariableDeclaration(s))return ue(s.getInitializer(),t)?s:void 0;const n=i.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return i.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},md=e=>{const t=pd(e);return t===void 0?void 0:i.isIdentifier(t.getNameNode())?i.isForOfStatement(t.getParent().getParent())||Z(t)?[t]:void 0:Nn(t)},le=e=>e.isUnion()?e.getUnionTypes().every(t=>le(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>le(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),ke=(e,t,s)=>{const n=i.isCallExpression(e)?v(e.getExpression()):void 0;return i.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Ie=e=>{const t=v(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=t.getBody();return i.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(r=>i.isFunctionLikeDeclaration(r))===t).map(n=>n.getExpression()):[s]},hd=e=>{const t=i.isCallExpression(e)?v(e.getExpression()):void 0,s=i.isPropertyAccessExpression(t)?t.getExpression():void 0;return i.isPropertyAccessExpression(t)&&i.isIdentifier(s)&&gd.get(s.getText())?.has(t.getName())===!0&&Re(s)},vd=e=>{const t=ct(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=b(t),n=s.getParent();return i.isCallExpression(n)&&n.getArguments().includes(s)&&ke(n,en)?n:void 0},Ed=(e,t)=>{if(!(i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=b(e),n=s.getParent();return!i.isCallExpression(n)||n.getExpression()!==s?e:ke(n,fd,t)?n:void 0},xd=(e,t)=>{if(i.isAwaitExpression(e))return e;if(i.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=i.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Sd=(e,t)=>{if(i.isArrayLiteralExpression(e))return e;const n=i.isSpreadElement(e)||i.isSpreadAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isPropertyAssignment(e)&&ue(e.getInitializer(),t)?e.getParent():void 0;return i.isArrayLiteralExpression(n)||i.isObjectLiteralExpression(n)?n:void 0},Ns=e=>{const t=b(e),s=t.getParent();if(s===void 0)return;const n=i.isCallExpression(s)&&s.getArguments().includes(t)&&hd(s);return Ed(s,t)??xd(s,t)??Sd(s,t)??(n?s:vd(t))},yd=5e4,Pn=()=>({inProgress:new Set,verdicts:new Map});class Ad{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>yd&&this.cut()}memoized(t,s,n){const r=n.verdicts.get(t);if(r!==void 0)return r;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 bd=8,Nd=8;class Pd{budget;scope;taint;verdicts=Pn();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!le(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],r=new Set,o=(c,l)=>{r.has(c.compilerNode)||(r.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 r)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,r){const o=t.getNameNode();if(!i.isIdentifier(o)){for(const l of i.isParameterDeclaration(t)?Nn(t):[])r(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=bd?this.budget.cut():(r(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(b(l),!0,a,0))&&(t===n||!le(t.getType()))}valueCompromises(t,s,n,r){let o=t;for(let m=Ns(o);m!==void 0;m=Ns(o)){if(i.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=b(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&le(o.getType());if(ze(o))return!c&&(!i.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=md(o);if(u!==void 0)return u.some(m=>n(m,!0));const p=i.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(i.isCallExpression(p)&&p.getExpression()===a)return this.methodCallCompromises(p,n);const f=this.nestedReturningFunctionOf(o);return f!==void 0?this.resultCompromises(f,n,r)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const r=b(t).getParent();if(n>=Nd)return this.budget.cut();if(i.isCallExpression(r))return r.getExpression()===b(t)?this.valueCompromises(r,!1,s,n+1):!ke(r,mt);const o=i.isFunctionDeclaration(t)?t:r,a=i.isFunctionDeclaration(o)||Z(o)?o.getNameNode():void 0;return o===void 0||!i.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=b(c),u=l.getParent();return!i.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(r=>Ie(r)===void 0).some(r=>this.taint.isTaintedValue(r,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=ke(t,mt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const r=pt(n);return r!==void 0&&this.taint.isInImpl(r)?r.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(i.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const r=i.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&i.isCallExpression(r))return!gt(n,this.scope.context)&&this.isOpaqueCallTainted(r.getExpression(),r.getArguments(),n);if(i.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(i.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return i.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(gt(s,this.scope.context))return!1;const r=pt(t.getExpression()),o=r===void 0?void 0:yn(r,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&r!==void 0&&this.taint.isInImpl(r)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||i.isExpressionStatement(s)||i.isForStatement(s)||i.isElementAccessExpression(s)||An(t)||ue(ct(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const r=!i.isIdentifier(v(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||r)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=ct(t);return ue(s,this.scope.impl)?void 0:s}}const wd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Id=e=>{const t=v(e);if(!i.isIdentifier(t))return i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t);const s=R(t),n=i.isVariableDeclaration(s)?v(s.getInitializer()):void 0;return s===void 0||i.isFunctionDeclaration(s)||i.isParameterDeclaration(s)||i.isArrowFunction(n)||i.isFunctionExpression(n)},Cd=new Set(["all","allSettled","any","race"]),Ps=e=>i.isParameterDeclaration(e)?e:i.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,nt=8;class Td{budget=new Ad;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Pn();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Pd(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,nt)?!1:(i.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(r=>Ar(r)&&this.isIdentifierTainted(r))}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 r of this.referencesByName.get(s)??[]){const o=R(r)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],r])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(r=>r.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(f=>f.getInitializer())].some(f=>f!==void 0&&this.isTaintedValue(f,!1)))return!0;const n=t.getParentOrThrow(),r=i.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(f=>f.compilerNode===t.compilerNode):-1,o=b(n),a=o.getParent();if(r===-1)return!0;if(i.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,r,t.isRestParameter());const f=v(a.getExpression());if(!i.isPropertyAccessExpression(f)||!mt.has(f.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(f.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=i.isVariableDeclaration(a)&&Z(a)?a:void 0,l=i.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!i.isIdentifier(u))return!0;const p=this.referencesTo(l,u.getText());return p.length===0||p.some(f=>{const m=b(f),x=m.getParent();return!i.isCallExpression(x)||x.getExpression()!==m||this.isCallSiteTainted(x,r,t.isRestParameter())})}isCallSiteTainted(t,s,n){const r=t.getArguments(),o=r.findIndex(c=>i.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return r.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=v(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getExpression():void 0,a=i.isPropertyAccessExpression(n)&&i.isIdentifier(r)&&r.getText()==="Promise"&&Re(r)&&Cd.has(n.getName())?v(t.getArguments()[0]):void 0;if(i.isArrayLiteralExpression(a)){const p=a.getElements();return p.length>0&&p.every(f=>!i.isSpreadElement(f)&&this.isRootedInContext(f,s))}const c=i.isCallExpression(a)?v(a.getExpression()):void 0,l=i.isCallExpression(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="map"?v(a.getArguments()[0]):void 0,u=l===void 0?void 0:Ie(l);return u!==void 0&&u.length>0&&u.every(p=>p!==void 0&&this.isRootedInContext(p,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=R(t),r=Ps(n);if(r!==void 0)return this.isSource(r);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(i.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(i.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=i.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return i.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=v(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getName():void 0;return r!==void 0&&Zs.has(r)?!1:r!==void 0&&en.has(r)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Ie(a)!==void 0)&&(r===void 0||!wd.has(r))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(r,o=[])=>{const a=yt(r),c=i.isIdentifier(a)?Ps(R(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(r,s)||!this.isTaintedValue(r,!1)};return t.getArguments().every(r=>{const o=Ie(r);if(o===void 0)return!Id(r)&&n(r);const a=v(r),c=i.isArrowFunction(a)||i.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Tr(t,u=>this.callChainVerdict(u,s)),r=n.root;if(n.verdict!==void 0)return n.verdict;if(Sn(r,this.scope.context))return!0;const o=i.isIdentifier(r)?R(r):void 0,a=i.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=Z(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=i.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(i.isBindingElement(l)||i.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(i.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(i.isForOfStatement(s)||i.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),r=xt(t);if(n===void 0||r)return!0;if(this.isRootedInContext(n,nt))return!1;if(this.variableDepth>=nt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const ws=new WeakMap,Od=e=>{const t=ws.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Td(e);return ws.set(e.impl.compilerNode,s),s},Rd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),kd=new Set(["insert","insertManyUnsafe","patch","replace"]),Fd=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();return kd.has(t)&&Vr(e.getExpression())?t:void 0},Dd=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},Ld=(e,t)=>{const s=Or(e);return s?.member===t?v(s.object):void 0},Is=(e,t)=>i.isIdentifier(e)&&R(e)?.compilerNode===t.compilerNode,wn=(e,t,s,n=1)=>{const r=Ld(e,s);if(r!==void 0)return Is(r,t);const o=i.isIdentifier(e)?R(e):void 0;if(i.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&me(o)===s&&i.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||Z(l)&&Is(v(l.getInitializer()),t))}const a=Z(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&wn(a,t,s,n-1)},ht=e=>{const t=v(e)??e;return i.isConditionalExpression(t)?[...ht(t.getWhenTrue()),...ht(t.getWhenFalse())]:[t]},Md=(e,t,s)=>{const n=[],r=s===void 0?void 0:Od(s);for(const o of e.getProperties()){let a,c;if(i.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Rd.has(a))continue;if(ht(c).some(u=>r===void 0?j(u)&&!qr(u):r.isTaintedValue(u,!0))){const u=t.ownerField===a&&s?.pristine===!0&&wn(c,s.parameter,a);n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...u&&{ownerScoped:!0}})}}return n},_d=(e,t,s)=>{const n=Fd(e.getExpression()),r=n===void 0?void 0:e.getArguments()[1];if(n===void 0||r===void 0)return[];const o=Dd(r,n);if(o.length===0)return[];const a=h(e),c=ud(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Md(u,l,c))},Kd=(e,t,s=[],n=[])=>{const r=new Map(n.map(a=>[`${a.filePath}:${a.exportName}`,a.owner])),o=I(e,t,(a,c)=>_d(a,c,l=>r.get(`${c}:${l}`)));return St(o,s)},zd=["providerSubscriptionId","state"],Bd=["providerEventId","processedAt"],Cs=(e,t)=>t.every(s=>s in e.shape),$d=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Cs(t,zd)&&Cs(s,Bd)},Ud=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),jd=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Vd=e=>{const t=D(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?jd(t.getInitializer()):void 0},qd=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Ud.has(s))return;const[n]=e.getArguments(),r=n&&i.isObjectLiteralExpression(n)?Vd(n):void 0;return{callee:s,scope:h(e),file:t,line:e.getStartLineNumber(),...r===void 0?{}:{toleranceSeconds:r}}},Wd=(e,t)=>I(e,t,qd),Hd=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Gd=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Yd=(e,t)=>{const s=e.getArguments()[t];if(!s||!i.isObjectLiteralExpression(s))return;const n=D(s,"handler");if(n===void 0||!i.isPropertyAssignment(n))return;const r=n.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},In=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Cn=(e,t)=>e===t||e.startsWith(`${t}.`),Tn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Ts=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},On=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Ts(s));return i.isIdentifier(e)&&Ts(e)&&t.push(e),t},Qd=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Xd=e=>{const t=In(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const r=n.getInitializer(),o=i.isVariableDeclarationList(r)?r.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Jd=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Xd(e),r=new Set,o=a=>Tn(a).some(c=>n.some(l=>Cn(c.getText(),l)))?!0:On(a).some(c=>r.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Qd(a))r.add(l)}return{names:r,prefixes:n}},Zd=(e,t)=>Tn(e).some(s=>t.prefixes.some(n=>Cn(s.getText(),n)))?!0:On(e).some(s=>t.names.has(s.getText())),eu=e=>{const t=qs(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},tu=(e,t,s)=>{const n=In(e,0);if(n===void 0)return[];const r=Jd(e,t,n),o=new Set([n,...r.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!i.isPropertyAccessExpression(l)||!Vs.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Zd(u,r))continue;const p=eu(c.getArguments()[0]);p!==void 0&&a.push({dispatchKind:t,file:s,scope:h(c),line:c.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return a},su=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=Gd(n),o=r===void 0?void 0:Hd.get(r);if(o===void 0)continue;const a=Yd(n,o);a!==void 0&&s.push(...tu(a,r==="defineWorkflow"?"workflow":"queue",t))}return s},nu=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...su(r,w(t,n)))}return s},Os={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Rs=new Set(["account","credential","member","passkey","session","user"]),ru=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),iu=e=>{const s=ru(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Rs.has(s)||Rs.has(n)},ou=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},au=(e,t)=>{const{objects:s,opaque:n}=Nt(e,t);return Sa(s).some(r=>ou(r))?!0:n?void 0:!1},cu=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!D(t,"captcha"),usesRateLimit:!!D(t,"rateLimit")}},lu=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},Ce={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},du=e=>{const t=lu(e),s=t?A(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=cu(t);return{...Ce,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Os?{...Ce,[Os[s]]:!0}:Ce},uu=e=>{const t={...Ce};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const r=n.getName()==="use"?s.getArguments()[0]:void 0;if(r){const o=du(r);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},fu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),gu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!fu.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const r=e.getArguments()[0];return!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?!1:iu(r.getLiteralText())},pu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),ks=new Set(["queues","scheduler","topics","workflows"]),mu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!pu.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&ks.has(s.getName())&&Wr(s.getExpression()))return!0;s=s.getExpression()}const n=Js(s);return n?.length===1&&ks.has(n[0]??"")},hu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},Rn=new Set(["generateObject","generateText","streamObject","streamText"]),vu=e=>{const t=A(e.getExpression());return t!==void 0&&Rn.has(t)},Eu=e=>{const t=A(e.getExpression());if(t===void 0||!Rn.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!D(s,"maxOutputTokens")},xu=new Set(["log","span","trace"]),Su=new Set(["ai"]),yu=new Set(["email","mail"]),Au=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),rt=(e,t)=>[...t].some(s=>Be(e,s).length>0),bu=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Nu=new Set(["every","filter","flatMap","forEach","map","some"]),Pu=new Set(["all","allSettled","race"]),wu=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Nu.has(n))return t;const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="Promise"&&Pu.has(n))return t},Iu=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(bu.has(t.getKind())){const s=wu(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Cu=e=>{let t=e;for(;;){const s=t.getParent();if(!i.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(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Tu=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ou=e=>{let t=!1,s=!0;for(const n of[...Au].flatMap(r=>Be(e,r))){const r=Tu(n);r&&(t=!0,!Iu(r)&&!Cu(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ru=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Fs="lunora-advisor-exempt",ku=/^[\s*/]+/u,Fu=/[\w-]/u,Du=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
6
+ Install them with your package manager, then re-run codegen.`)},go="env.ts",mo=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return _e(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},ho=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&_e(n.getModuleSpecifierValue())}return!1},vo=e=>{if(i.isIdentifier(e))return mo(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&ho(t)}return!1},Eo=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!vo(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ge(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=Us(s,"member");a!==void 0&&t.push({exportName:a})}return t},xo=(e,t)=>{const s=S(t,go);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=Eo(n);if(r.length!==0){if(r.length>1)throw ge(n,`lunora/env.ts declares ${r.length.toString()} defineEnv() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},on="identity.ts",So=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return _e(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},yo=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&_e(n.getModuleSpecifierValue())}return!1},Ao=e=>{if(i.isIdentifier(e))return So(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&yo(t)}return!1},bo=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Ao(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ge(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Us(s,"member");a!==void 0&&t.push({exportName:a})}return t},No=(e,t)=>{const s=S(t,on);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=bo(n);if(r.length!==0){if(r.length>1)throw ge(n,`lunora/identity.ts declares ${r.length.toString()} defineIdentity() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},Po=new Set(["allowedHosts","deniedHosts","interceptHttps"]),wo=(e,t)=>{const s=v(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return v(e.getDescendantsOfKind(d.VariableDeclaration).find(r=>r.getName()===n)?.getInitializer())},Io=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(y(s));if(!i.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=v(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Co=new Set(["durable"]),To=new Set(["rollback"]),Oo=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},Ro=new Map([["defineContainer",{keys:Po,signal:"containerEgressPolicy"}],["defineStep",{keys:To,signal:"workflowRollback"}],["stream",{keys:Co,signal:"durableStreams"}]]),ko=(e,t)=>{const s=Ro.get(Oo(t));if(s!==void 0)return t.getArguments().some(n=>Io(wo(e,n),s.keys))?s.signal:void 0},Fo=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Nr(r).has("secrets"));for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=ko(r,o);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},Do="createWorker",Lo="extend",ns=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,rs=e=>{const t=[],s=ns(P(e,"backupCron"));s!==void 0&&t.push(s);const n=P(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)&&!i.isMethodDeclaration(r))continue;const o=ns(r.getNameNode());o!==void 0&&t.push(o)}return t},Mo=e=>{const t=A(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Do)return i.isObjectLiteralExpression(s)?rs(s):[];if(t!==Lo||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=js(s.getBody());return n===void 0?[]:rs(n)},_o=(e,t)=>{const s=[];for(const{filePath:n}of Ke(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression))s.push(...Mo(o))}return[...new Set(s)]},an=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:an(e.inner)},Ko=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const r=an(n);return r!==void 0&&t.has(r)}))},zo=(e,t)=>{const s=new Map,n=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const o=s.get(r.name);if(o!==void 0)throw new W("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${o} and agent "${r.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(r.className);if(a!==void 0)throw new W("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${a} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Bo=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:r}=e,o=No(s,t),a=xo(s,t),c=fr(s,t),{queues:l,topics:u}=dr(s,t),g=Fr(n),f=vr(s,t);zo(c,f);const m=Er(s,t),x=Dr(s,t),z=xr(s,t,c,f),B=_o(s,t),N=Fo(s,t),k=kr(s,t),q=Pr(s,t);q.browser=q.browser||k.usesSandboxBrowser;const G=_r(q,Ys(n,e.target),{agents:f.length>0,commitOrderedTables:r.tables.some(T=>T.commitOrdered===!0),cronTriggers:z.length>0,crossShardFanout:r.tables.some(T=>Mr(T)),containerEgressPolicy:N.containerEgressPolicy,containerRuntimeScheduling:m.some(T=>T.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(T=>T.sandbox===!0),durableStreams:N.durableStreams,globalTables:r.tables.some(T=>T.shardMode==="global"),queues:l.length>0,relationGraph:Ko(r),secrets:N.secrets,services:g.length>0,topics:u.length>0,vectorStore:r.vectorIndexes.length>0,workerLoaders:k.usesSandboxLoader,workflowRollback:N.workflowRollback,workflowSchedules:c.some(T=>T.schedules!==void 0)}),F=G.usage,te=hr(F),oe=G.signals.vectorStore!==!1,ae=G.signals.services===!1?[]:g,se=wr(n),he=se??new Set,$=he.has("lunorash");po(r,se,{hasVectors:oe,scheduler:F.scheduler||z.length>0,storage:F.storage||x.rules.length>0||Object.keys(Qs(r)).length>0,usage:F});const L=O(S(t,"flags.ts")),M=O(S(t,"notify.ts"));return{agents:f,capabilities:te,containers:m,crons:z,dataModelContent:Ur(r),declaredDependencies:se,dependencies:he,entryCronTriggers:B,env:a,featureUsage:F,hasFlags:L,hasNotify:M,identity:o,platformGate:{...G,diagnostics:[...Kr(n,e.target),...G.diagnostics]},queues:l,serverContent:$r({agents:f,capabilities:te,containers:m,env:a,hasVectors:oe,hasFlags:L,hasNotify:M,identity:o,queues:l,schema:r,generatedDirectory:S(t,"_generated"),services:ae,storageRuleBuckets:x.rules.map(T=>T.bucket),topics:u,useUmbrella:$,workflows:c}),services:ae,storageRulesMetadata:x,topics:u,usesSandbox:k.usesSandboxBrowser||k.usesSandboxContainer||k.usesSandboxFs,useUmbrella:$,workflows:c}},cn=new Set(["delete","get","head","options","patch","post","put"]),$o=new Set(["handler","stream"]),Uo=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,is=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),jo=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!cn.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Vo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||cn.has(n.getName()))break;s=n.getExpression()}return jo(s)},qo=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(is.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&is.has(s.getText()))return!0}return!1},Wo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!$o.has(n.getName()))return;const r=Vo(s);if(!r||!Uo.test(r.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&qo(o);return{exportName:K(e)??e.getName(),file:t,method:r.method,path:r.path,usesGuard:a}},Ho=(e,t)=>{const s=[];for(const n of V(e)){const r=Wo(n,t);r&&s.push(r)}return s},Go=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ho(r,w(t,n)))}return s},Yo=e=>{const t=e.getText(),s=n=>{const r=n.getNameNode();return i.isIdentifier(r)&&r.getText()===t};for(const n of e.getAncestors())if(!(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)&&!i.isFunctionDeclaration(n)))for(const r of n.getParameters()){const o=r.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Qo=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isObjectBindingPattern(s))return;const n=s.getParent();if(i.isBindingElement(n)){t=n;continue}return i.isParameterDeclaration(n)?me(t):void 0}},Xo=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=i.isFunctionLikeDeclaration(o)||i.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(i.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Zt(a)}))return!1;const n=R(e),r=i.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return r!==void 0&&(i.isParameterDeclaration(n)||i.isBindingElement(n))&&Zt(r)},os=(e,t)=>{const s=e.getParent();if(i.isPropertyAccessExpression(s)&&s.getNameNode()===e||i.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Yo(e);return n!==void 0&&Qo(n)===t?!0:t==="args"&&Xo(e)},ln=(e,t)=>i.isIdentifier(e)?os(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>os(s,t)),Jo=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},as=e=>{const t=i.isIdentifier(e)?R(e):void 0;return i.isVariableDeclaration(t)&&i.isIdentifier(t.getNameNode())&&!xt(t)?t.getInitializer():void 0},lt=e=>ln(e,"args"),Q=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let r,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(r=c,o=l)}return r},j=e=>{if(lt(e))return!0;const t=Q(e);return t!==void 0&&lt(t)},Zo=e=>{if(i.isCallExpression(e)||i.isNewExpression(e))return!1;const t=Q(e);return t===void 0||!(i.isCallExpression(t)||i.isNewExpression(t))},ee=e=>{if(Je(e))return!0;const t=as(e);if(t!==void 0&&Je(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(r=>{const o=as(r);return o!==void 0&&Je(o)})},Pe=(e,t)=>ln(e,t),ea=(e,t)=>{if(Pe(e,t))return!0;const s=Q(e);if(s!==void 0&&Pe(s,t))return!0;const n=Jo(e);if(n!==void 0){const r=Q(n);return r!==void 0&&Pe(r,t)}return!1},ta=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:U(e.getExpression(),["ai"]),sa=(e,t)=>{if(!ta(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)||ee(s)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},na=(e,t)=>I(e,t,sa),ra=new Set(["generateText","streamText"]),ia=new Set(["messages","prompt","system"]),oa=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","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"]}],aa=(e,t)=>oa.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ca=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=[jr(t.getExpression()),t.getExpression().getText()].find(r=>r!==void 0&&aa(r,s));return n===void 0?void 0:`${n}.${s}`},la=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ca(t);if(s!==void 0)return s}},da=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],r=n?.getNameNode();if(r===void 0||!i.isObjectBindingPattern(r))return t;for(const o of r.getElements()){const a=me(o),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},ua=e=>{if(lt(e))return!0;const t=da(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},fa=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!ia.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&ua(s))return!0}return!1},pa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=A(n.getExpression());if(r===void 0||!ra.has(r))continue;const[o]=n.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(A(c.getExpression())==="tool"&&(a=la(c),a!==void 0))break;a!==void 0&&s.push({scope:h(n),file:t,line:n.getStartLineNumber(),method:r,sideEffect:a,userInputDerived:fa(o)})}return s},ga=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pa(r,w(t,n)))}return s},ma=e=>U(e,["fetch"]),ha=(e,t)=>{if(!ma(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},va=(e,t)=>I(e,t,ha),bt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=$e(s.getExpression());return n===void 0||bt(n,t)})}finally{t.delete(e)}},Ea=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=D(t,"args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),r=n===void 0?void 0:$e(n);return r===void 0?{objects:[],opaque:!0}:{objects:[r],opaque:bt(r)}},xa=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const r=n.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&i.isExpression(o)?$e(o):void 0;a===void 0?s=!0:(t.push(a),s||=bt(a))}n=r.getExpression()}return{objects:t,opaque:s}},Nt=(e,t)=>t?xa(t):Ea(e),dn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=$e(s.getExpression());return n===void 0?[]:dn(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Sa=e=>e.flatMap(t=>dn(t,new Set)),ya=new Set(["check","length","max"]),dt=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Aa=e=>[e,...e.getDescendants()].filter(t=>dt(t)!==void 0),ba=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(ya.has(s.getName()))return!0;t=n}},Na=e=>{const t=[],s=[];for(const n of e)for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=Aa(o),c=y(r);a.some(l=>dt(l)==="any")?t.push(c):a.some(l=>dt(l)==="string"&&!ba(l))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Pa=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=H(s);if(n?.visibility!=="public")return;const{objects:r}=Nt(s,n.receiver),{anyArgs:o,unboundedStringArgs:a}=Na(r);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:K(e)??e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},wa=(e,t)=>{const s=[];for(const n of V(e)){const r=Pa(n,t);r&&s.push(r)}return s},Ia=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wa(r,w(t,n)))}return s},st=e=>e?.getKind()===d.TrueKeyword,Ca=e=>e?.getKind()===d.FalseKeyword,Ta=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Oa=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Ra=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&A(t.getExpression())==="scim"),ka=e=>e!==void 0&&i.isCallExpression(e)&&Oa.has(A(e.getExpression())??""),Fa=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Da=e=>{const t=P(e,"advanced"),s=P(e,"emailAndPassword"),n=P(e,"session");return{analyzable:!0,disableCsrfCheck:st(P(t,"disableCSRFCheck")),emailPasswordEnabled:st(P(s,"enabled")),requireEmailVerification:st(P(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Ra(P(e,"plugins"))&&ka(P(e,"database")),secureCookiesDisabled:Ca(P(t,"useSecureCookies")),sessionFreshAgeZero:Ta(P(n,"freshAge")),trustedOriginsWildcard:Fa(P(e,"trustedOrigins"))}},La=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Ma=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),r=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?Da(s):La();return{scope:h(e),file:t,line:e.getStartLineNumber(),...r}},_a=(e,t)=>Ir(e,t,Ma),Ka=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Xs(e.getExpression(),t.matchReceiver)?s:void 0},za=(e,t,s)=>{const n=Ka(e.getExpression(),s);if(n===void 0)return;const r=e.getArguments()[s.argIndex];if(!(!r||!j(r)||ee(r))&&!(s.requireUnmodifiedReach===!0&&!Zo(r)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:n}},Ue=(e,t,s)=>I(e,t,(n,r)=>za(n,r,s)),Ba=new Set(["content","pdf","scrape","screenshot"]),$a=(e,t)=>Ue(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ba}),un=e=>{const t=qs(e);return t===void 0?void 0:`${Me(t.slice(0,-1).join("/"))}:${String(t.at(-1))}`},fn=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Ua=e=>{if(!i.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||i.isIdentifier(t)&&t.getText()==="scheduler"},ja=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Va=(e,t)=>{const s=un(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"}:void 0},qa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),[n,r]=e.getArguments();if(Vs.has(s))return Va(s,n);if((s==="runAfter"||s==="runAt")&&Ua(t)){const c=un(r);return c===void 0?{kind:"schedule",reason:"the scheduled function is not a static api.* / internal.* chain"}:{kind:"schedule",target:c}}const o=ja.get(s),a=o===void 0?void 0:fn(t,o.surface);return o===void 0||a===void 0?void 0:{kind:o.kind,target:a}},cs=(e,t,s)=>s===void 0?void 0:{...s,file:t,line:e.getStartLineNumber(),scope:h(e)},Wa=(e,t)=>[...I(e,t,(s,n)=>cs(s,n,qa(s))),...at(e,t,d.PropertyAccessExpression,(s,n)=>{const r=fn(s,"services");return cs(s,n,r===void 0?void 0:{kind:"invoke",target:r})})],Ha=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Ga=new Set(["RateLimiter"]),Ya=new Set(["extend"]),ls="lunora",Qa=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],pn=e=>{const t=[],s=[];let n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=y(r);t.push(o),r.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,presentKeys:t,trueKeys:s}},ut=e=>e&&i.isObjectLiteralExpression(e)?pn(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Xa=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&js(t.getBody());return s?pn(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Ja=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=A(n.getExpression());r!==void 0&&(Ha.has(r)?s.push({callee:r,file:t,line:n.getStartLineNumber(),...ut(n.getArguments()[0])}):Ya.has(r)&&s.push({callee:r,file:t,line:n.getStartLineNumber(),...Xa(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const r=A(n.getExpression());r===void 0||!Ga.has(r)||s.push({callee:r,file:t,line:n.getStartLineNumber(),...ut(n.getArguments()[0])})}return s},Za=(e,t)=>{for(const s of Qa){const n=S(t,s);if(!O(n))continue;const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of r.getDescendantsOfKind(d.CallExpression))A(a.getExpression())===ls&&o.push({callee:ls,file:s,line:a.getStartLineNumber(),...ut(a.getArguments()[0])});return o}return[]},ec=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Ke(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ja(o,n))}return s.push(...Za(e,Ne(t))),s},ds="ctx.containers.",tc=e=>{if(!e.startsWith(ds))return!1;const t=e.slice(ds.length);return t.length>0&&!t.includes(".")},sc=(e,t)=>Ue(e,t,{argIndex:0,matchReceiver:tc,methods:new Set(["get"])}),nc=new Set(["allow","deny","setAllowed"]),rc=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=D(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},ic=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!rc(e)))return{detail:"enableInternet: true",scope:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},oc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!nc.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},ac=(e,t)=>ic(e,t)??oc(e,t),cc=(e,t)=>I(e,t,ac),lc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),dc=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return lc.has(s)?s:void 0},uc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const r=y(n);t.push(r);const o=n.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(r);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},fc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Ke(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=dc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&i.isObjectLiteralExpression(l)?uc(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},pc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),gc=new Set(["dbRateLimit","rateLimit"]),mc=e=>{const t=Hs(e);if(!t)return!1;const s=D(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},hc=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const n=pc.get(s);if(n!==void 0)return{callee:s,scope:h(e),failOpen:mc(e.getArguments()[n]),file:t,limitName:gc.has(s)?Ws(e):"",line:e.getStartLineNumber()}},vc=(e,t)=>I(e,t,hc),Ec=new Set(["boolean","number","object","string"]),xc=e=>{const t=e.getName();if(!Ec.has(t))return;const s=e.getExpression();return U(s,["flags"])||U(s,["flags","details"])?t:void 0},Sc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=xc(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const r=n.getLiteralValue();return r.length>0?{key:r,type:s}:void 0},yc=(e,t)=>{const s=new Map;for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=Sc(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,r])=>({key:n,type:r})).toSorted((n,r)=>n.key.localeCompare(r.key))},Ac=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=H(t);if(s?.kind!=="query")return;const n=Cr(t,s.receiver);return n?{exportName:K(e)??e.getName(),handler:n}:void 0},us=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},bc=e=>{const t=us(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=us(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Nc=(e,t)=>{const s=[];for(const n of Be(e.handler,"flags"))s.push({callee:bc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Pc=(e,t)=>{const s=[];for(const n of V(e)){const r=Ac(n);r&&s.push(...Nc(r,t))}return s},wc=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Pc(r,w(t,n)))}return s},Ic=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:U(e.getExpression(),["flags"]),Cc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Tc=(e,t)=>{if(!Ic(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const r=s.getLiteralValue(),o=Cc(n);if(!(r.length===0||o===void 0))return{defaultValue:o,scope:h(e),file:t,key:r,line:e.getStartLineNumber()}},Oc=(e,t)=>I(e,t,Tc),Rc=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 r=n.getTypeAtLocation(e),o=r.getText(e);if(!o||o==="any"||o==="never"||Yr(o))return;const a=e.getSourceFile().getFilePath();if(Qr(r,e,a)){const c=Xr(r,e,a,0,new Set);return c===void 0&&Jr(o),c}return o},kc=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Fc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Dc=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of r.getDescendantsOfKind(d.CallExpression))kc(a)&&s.push({file:o,indexName:Fc(a),line:a.getStartLineNumber()})}return s},fe=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,gn=e=>{const t=e.getArguments()[0],s=fe(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=D(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?fe(n.getInitializer()):void 0},Lc=new Set(["delete","get","head","options","patch","post","put"]),Mc=new Set(["handler","stream"]),_c=new Set(["runAction","runMutation"]),Kc=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),pe=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,mn=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(me(s)===t){const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0}}},fs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:mn(s,"ctx")},ps=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:mn(s,"request")},gs=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const r of n){const o=r.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(_c.has(a)&&pe(c,t))return a;if(Kc.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&pe(c.getExpression(),t))return`db.${a}`}},ms=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&pe(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const r=n.getNameNode();if(!(!i.isObjectBindingPattern(r)||!pe(n.getInitializer(),t))){for(const o of r.getElements())if(me(o)==="auth")return!0}}return!1},zc=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Bc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&pe(n.getExpression(),t)},$c=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],hn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:$c(s)},Uc=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const r=n.getParent();if(!i.isCallExpression(r))return[];const o=r.getExpression();if(!i.isPropertyAccessExpression(o))return[];const a=o.getExpression();return i.isIdentifier(a)?hn(t,a.getText()):[]}return[]},jc=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=hn(s,t.getText());return n.length>0?n:Uc(t,s)},hs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(r=>Bc(r,t)&&jc(r).some(o=>zc.test(o)))},Vc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Mc.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const r=n.getName();if(Lc.has(r)){const o=n.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?r.toUpperCase():void 0}s=n.getExpression()}},qc=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=fe(e.getArguments()[0]),l=c&&fs(c,!0);if(!c||l===void 0||hs(c,ps(c,!0)))return;const u=gs(c,l);return u===void 0?void 0:{scope:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ms(c,l),sideEffect:u}}const n=Vc(e);if(n===void 0)return;const r=fe(e.getArguments()[0]),o=r&&fs(r,!1);if(!r||o===void 0||hs(r,ps(r,!1)))return;const a=gs(r,o);return a===void 0?void 0:{scope:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:ms(r,o),sideEffect:a}},Wc=(e,t)=>I(e,t,qc),Hc=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Gc=new Set(["append","set"]),vn=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",vs=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Hc.has(A(n.getExpression())??"")&&Pe(n,t)),Yc=(e,t)=>{if(vs(e,t))return!0;const s=Q(e);return s!==void 0&&vs(s,t)},ft=(e,t)=>ea(e,t)&&!Yc(e,t),Qc=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&i.isNewExpression(t)&&A(t.getExpression())==="Headers"},Oe=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Pt=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const r=n.getInitializer();r!==void 0&&ft(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:vn(n.getNameNode()),line:r.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const r=n.getNameNode();ft(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:r.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const r=Oe(n.getExpression());r!==void 0&&Pt(r,t,s)}},En=(e,t)=>{const s=Oe(e);if(s===void 0)return;const n=D(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const r=Oe(n.getInitializer());r!==void 0&&Pt(r,"response-init",t)},Xc=(e,t)=>{const s=A(e.getExpression());if(s==="Response")En(e.getArguments()[1],t);else if(s==="Headers"){const n=Oe(e.getArguments()[0]);n!==void 0&&Pt(n,"headers-ctor",t)}},Jc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),r=s.getExpression();if(n==="json"&&i.isIdentifier(r)&&r.getText()==="Response"){En(e.getArguments()[1],t);return}if(Gc.has(n)&&Qc(r)){const o=e.getArguments()[1];o!==void 0&&ft(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:vn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Zc=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Xc(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Jc(s,t)},el=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=fe(e.getArguments()[0]);if(n===void 0)return[];const r=n.getParameters()[1];if(r===void 0)return[];const o=r.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return Zc(n,{scope:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},tl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...el(n,t));return s},sl=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tl(r,w(t,n)))}return s},nl=new Set(["auth","context.auth"]),rl="userId",il=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(y(s))}return t},ol=(e,t)=>{const s=S(t,on);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){if(A(r.getExpression())!=="defineIdentity")continue;const[o]=r.getArguments();return o&&i.isObjectLiteralExpression(o)?il(o):void 0}},Es=e=>{if(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return nl.has(t.getText())||U(t,["auth"])?e:void 0},al=e=>{if(i.isPropertyAccessExpression(e)&&Es(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Es(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},xs=(e,t,s)=>{const n=al(e);return n===void 0?void 0:{declared:n===rl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:h(e)}},cl=(e,t)=>{const s=ol(e,t);return s===void 0?[]:[...at(e,t,d.PropertyAccessExpression,(n,r)=>xs(n,r,s)),...at(e,t,d.ElementAccessExpression,(n,r)=>xs(n,r,s))]},ll=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=P(s,"key");if(!(!n||!j(n)||ee(n)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},dl=(e,t)=>I(e,t,ll),ul=e=>{if(i.isComputedPropertyName(e)){const t=e.getExpression();return i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return i.isStringLiteral(e)?e.getLiteralValue():e.getText()},fl=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=ul(t.getNameNode());return s===void 0||s==="namespace"}),pl=(e,t)=>{for(const{filePath:s}of Ke(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){const o=r.getExpression(),[a]=r.getArguments();if(!(!i.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!i.isObjectLiteralExpression(a)||fl(a)))return r}}},gl="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",ml=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ge(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 (${gl}). 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})},hl=new Set(["delete","get","getRaw","getWithMetadata","put"]),vl=(e,t,s=[])=>{const n=Ue(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:hl});return St(n,s)},El=new Set(["queue","send"]),Ss=new Set(["bcc","cc","to"]),xl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!El.has(t))return;const s=e.getExpression();return U(s,["mail"])||U(s,["email"])?t:void 0},Sl=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ss.has(y(t))&&j(n)&&!ee(n)}if(!i.isPropertyAssignment(t)||!Ss.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&j(s)&&!ee(s)}):!1,yl=(e,t)=>{const s=xl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Sl(n)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s}},Al=(e,t)=>I(e,t,yl),bl=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,Nl=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?bl(e):!0,xn=(e,t=!1)=>{for(const s of e.getProperties()){if(Nl(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||xn(n,!0))return!0}return!1},Pl=(e,t)=>{for(const s of E(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:r}of sn(n))for(const o of At(r)){const a=o.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||xn(a)))return!0}}return!1},wl=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const r=Te(n);if(r===void 0||!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!i.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Te(a);c!==void 0&&s.push({column:c,strategy:tn(a),table:r})}}return s},Il=(e,t)=>{const s=new Map;for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of sn(r))for(const a of At(o))for(const c of wl(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Cl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){const a=Te(o);if(a===void 0||!i.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Te(l);if(u===void 0)continue;const g=tn(l);g!=="custom"&&r.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:g,table:a})}}return r},Tl=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;return n?.receiver?At(n.receiver).flatMap(r=>Cl(r,K(e)??e.getName(),t)):[]},Ol=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Tl(a,o))}return s},Rl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},kl=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=D(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},Fl=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ci(s.getExpression())?s:void 0},Dl=e=>{const t=Fl(e),s=t===void 0?void 0:kl(t);if(s===void 0)return[];const n=e.getNameNode(),r=i.isIdentifier(n)?K(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Rl(o)).map(o=>({exportName:r,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Ll=e=>e.getVariableDeclarations().flatMap(t=>Dl(t)),Ml=(e,t)=>{const s=S(t,ai);if(!O(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Ll(n)},_l=new Set(["delete","get","patch"]),Kl=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),zl=new Set(["auth","identity","session","user"]),Bl=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),$l=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Ul=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},jl=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Vl=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,ql=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>jl(s.getExpression(),t)&&Vl(s.getThenStatement())),Wl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const r=n.getName();if(!_l.has(r))continue;const o=n.getExpression();if(!(_(o)||i.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return r}},Hl=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Js(yt(s))!==void 0)),Gl=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Bl.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Yl=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Kl.has(t.getText()))return!0;return[...zl].some(t=>Be(e,t).length>0)?!0:Hl(e)||Gl(e)},Ql=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=H(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const r=gn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&Gs(n.receiver,"use","rls"),a=Yl(r),c=new Set,l=[];for(const u of r.getDescendantsOfKind(d.CallExpression)){const g=$l(u);if(g===void 0)continue;const f=Ul(u);if(f===void 0||c.has(f)||!ql(r,f))continue;const m=Wl(r,f);m!==void 0&&(c.add(f),l.push({exportName:K(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:g,usesRls:o,visibility:n.visibility}))}return l},Xl=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Ql(a,o))}return s},Sn=(e,t)=>{const s=i.isIdentifier(e)&&t!==void 0?R(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?i.isIdentifier(t.getNameNode()):i.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Jl=e=>{const t=b(e),s=t.getParent();return(i.isPropertyAccessExpression(s)||i.isElementAccessExpression(s))&&s.getExpression()===t&&!ze(s)},Zl=e=>{const t=b(e).getParent();return i.isVariableDeclaration(t)&&i.isObjectBindingPattern(t.getNameNode())},ed=e=>{const s=b(e).getParent();if(i.isSpreadAssignment(s)||i.isSpreadElement(s)){const n=s.getParent();return(i.isObjectLiteralExpression(n)||i.isArrayLiteralExpression(n))&&!ze(n)}return i.isTemplateSpan(s)&&!i.isTaggedTemplateExpression(s.getParent().getParent())},Re=e=>{const t=R(e);return t===void 0||yr(t.getSourceFile())},pt=(e,t)=>{const s=b(e),n=s.getParent();if(!i.isCallExpression(n))return!1;const r=n.getArguments().indexOf(s),o=v(n.getExpression());if(r===-1||o===void 0)return!1;if(i.isIdentifier(o))return o.getText()==="structuredClone"&&Re(o);if(Sn(yt(o),t))return!(i.isPropertyAccessExpression(o)&&Zs.has(o.getName()))||i.isExpressionStatement(b(i.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!i.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!i.isIdentifier(a)||!Re(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"&&r>0;default:return!1}},we={kind:"opaque"},td={kind:"unreached"},sd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>i.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>i.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&i.isFunctionDeclaration(n)?n:void 0},gt=e=>{const t=v(e);if(i.isArrowFunction(t)||i.isFunctionExpression(t))return t;const s=i.isIdentifier(t)?R(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(i.isFunctionDeclaration(s)){const r=sd(s);return r===void 0||xt(r)?void 0:r}const n=Z(s)?v(s.getInitializer()):void 0;return i.isArrowFunction(n)||i.isFunctionExpression(n)?n:void 0},yn=(e,t,s)=>{const n=t.getArguments(),r=n.indexOf(s),o=r===-1||n.slice(0,r+1).some(l=>i.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[r];return o?we:c===void 0?a.some(l=>l.isRestParameter())?we:td:c.isRestParameter()?we:{kind:"parameter",parameter:c}},nd=e=>{const t=b(e),s=t.getParent();if(!i.isCallExpression(s)||s.getExpression()===t)return;const n=gt(s.getExpression());return n===void 0?we:yn(n,s,t)},rd=new Set(["__defineGetter__","__defineSetter__","__proto__"]),id=e=>i.isForInStatement(e)?e.getExpression():i.isConditionalExpression(e)?e.getCondition():i.isElementAccessExpression(e)?e.getArgumentExpression():void 0,An=e=>{const t=b(e),s=t.getParent();if(i.isIfStatement(s)||i.isWhileStatement(s)||i.isDoStatement(s)||i.isSwitchStatement(s)||i.isCaseClause(s)||i.isTypeOfExpression(s)||i.isVoidExpression(s)||i.isComputedPropertyName(s))return!0;if(i.isTemplateSpan(s))return!i.isTaggedTemplateExpression(s.getParent().getParent());const n=id(s);if(n!==void 0)return ue(n,t);if(i.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!i.isBinaryExpression(s))return!1;const r=s.getOperatorToken().getKind(),o=r>=d.FirstAssignment&&r<=d.LastAssignment,a=r===d.QuestionQuestionToken||r===d.BarBarToken||r===d.AmpersandAmpersandToken;return!o&&!a},od=4,bn=(e,t,s=0)=>{if(Sr(e))return!0;if(Jl(e)){const r=b(e).getParent(),o=i.isElementAccessExpression(r)?r.getArgumentExpression():void 0,a=i.isStringLiteral(o)?o.getLiteralValue():void 0,c=i.isPropertyAccessExpression(r)?r.getName():a;return c===void 0||!rd.has(c)}if(Zl(e)||ed(e)||An(e)||pt(e,t))return!0;const n=nd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&ad(n.parameter,s+1)},ys=new WeakMap,ad=(e,t=0)=>{const s=e.getNameNode();if(!i.isIdentifier(s))return!0;const n=ys.get(e.compilerNode);if(n!==void 0)return n;if(t>od)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||R(a)?.compilerNode!==e.compilerNode||bn(a,void 0,t));return(o||t===0)&&ys.set(e.compilerNode,o),o},As=new WeakMap,cd=(e,t)=>{const s=i.isFunctionExpression(e)?e.getNameNode():void 0;if(!i.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(r=>{if(r===s||!n.has(r.getText()))return!1;const o=R(r)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},ld=(e,t,s)=>{const{context:n,impl:r}=e,o=As.get(r.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=i.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(f=>{const m=f.getNameNode();return i.isIdentifier(m)?[m]:[]}),l=new Map(c.map(f=>[f.getText(),f.getParentOrThrow().compilerNode])),u=f=>i.isIdentifier(a)?bn(f,n):!ze(f),g=!cd(r,s)&&c.every(f=>(f.getSymbol()?.getDeclarations().length??0)===1)&&r.getDescendantsOfKind(d.Identifier).every(f=>{const m=f.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(f)||R(f)?.compilerNode!==x?!0:u(f)});return As.set(r.compilerNode,g),g},bs=new WeakMap,dd=e=>{let t=bs.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=li(s);return n===void 0?[]:[[n.compilerNode,s]]})),bs.set(e.compilerNode,t)),t},ud=e=>{const t=dd(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[r,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:r,impl:s,mutatorName:K(n)??n.getName()};return a!==void 0&&ld(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},fd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),pd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),mt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Nn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>i.isIdentifier(t.getNameNode())),gd=e=>{const t=b(e),s=t.getParent();if(i.isVariableDeclaration(s))return ue(s.getInitializer(),t)?s:void 0;const n=i.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return i.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},md=e=>{const t=gd(e);return t===void 0?void 0:i.isIdentifier(t.getNameNode())?i.isForOfStatement(t.getParent().getParent())||Z(t)?[t]:void 0:Nn(t)},le=e=>e.isUnion()?e.getUnionTypes().every(t=>le(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>le(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),ke=(e,t,s)=>{const n=i.isCallExpression(e)?v(e.getExpression()):void 0;return i.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Ie=e=>{const t=v(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=t.getBody();return i.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(r=>i.isFunctionLikeDeclaration(r))===t).map(n=>n.getExpression()):[s]},hd=e=>{const t=i.isCallExpression(e)?v(e.getExpression()):void 0,s=i.isPropertyAccessExpression(t)?t.getExpression():void 0;return i.isPropertyAccessExpression(t)&&i.isIdentifier(s)&&pd.get(s.getText())?.has(t.getName())===!0&&Re(s)},vd=e=>{const t=ct(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=b(t),n=s.getParent();return i.isCallExpression(n)&&n.getArguments().includes(s)&&ke(n,en)?n:void 0},Ed=(e,t)=>{if(!(i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=b(e),n=s.getParent();return!i.isCallExpression(n)||n.getExpression()!==s?e:ke(n,fd,t)?n:void 0},xd=(e,t)=>{if(i.isAwaitExpression(e))return e;if(i.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=i.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Sd=(e,t)=>{if(i.isArrayLiteralExpression(e))return e;const n=i.isSpreadElement(e)||i.isSpreadAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isPropertyAssignment(e)&&ue(e.getInitializer(),t)?e.getParent():void 0;return i.isArrayLiteralExpression(n)||i.isObjectLiteralExpression(n)?n:void 0},Ns=e=>{const t=b(e),s=t.getParent();if(s===void 0)return;const n=i.isCallExpression(s)&&s.getArguments().includes(t)&&hd(s);return Ed(s,t)??xd(s,t)??Sd(s,t)??(n?s:vd(t))},yd=5e4,Pn=()=>({inProgress:new Set,verdicts:new Map});class Ad{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>yd&&this.cut()}memoized(t,s,n){const r=n.verdicts.get(t);if(r!==void 0)return r;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 bd=8,Nd=8;class Pd{budget;scope;taint;verdicts=Pn();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!le(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],r=new Set,o=(c,l)=>{r.has(c.compilerNode)||(r.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 r)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,r){const o=t.getNameNode();if(!i.isIdentifier(o)){for(const l of i.isParameterDeclaration(t)?Nn(t):[])r(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=bd?this.budget.cut():(r(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(b(l),!0,a,0))&&(t===n||!le(t.getType()))}valueCompromises(t,s,n,r){let o=t;for(let m=Ns(o);m!==void 0;m=Ns(o)){if(i.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=b(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&le(o.getType());if(ze(o))return!c&&(!i.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=md(o);if(u!==void 0)return u.some(m=>n(m,!0));const g=i.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(i.isCallExpression(g)&&g.getExpression()===a)return this.methodCallCompromises(g,n);const f=this.nestedReturningFunctionOf(o);return f!==void 0?this.resultCompromises(f,n,r)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const r=b(t).getParent();if(n>=Nd)return this.budget.cut();if(i.isCallExpression(r))return r.getExpression()===b(t)?this.valueCompromises(r,!1,s,n+1):!ke(r,mt);const o=i.isFunctionDeclaration(t)?t:r,a=i.isFunctionDeclaration(o)||Z(o)?o.getNameNode():void 0;return o===void 0||!i.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=b(c),u=l.getParent();return!i.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(r=>Ie(r)===void 0).some(r=>this.taint.isTaintedValue(r,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=ke(t,mt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const r=gt(n);return r!==void 0&&this.taint.isInImpl(r)?r.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(i.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const r=i.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&i.isCallExpression(r))return!pt(n,this.scope.context)&&this.isOpaqueCallTainted(r.getExpression(),r.getArguments(),n);if(i.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(i.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return i.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(pt(s,this.scope.context))return!1;const r=gt(t.getExpression()),o=r===void 0?void 0:yn(r,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&r!==void 0&&this.taint.isInImpl(r)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||i.isExpressionStatement(s)||i.isForStatement(s)||i.isElementAccessExpression(s)||An(t)||ue(ct(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const r=!i.isIdentifier(v(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||r)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=ct(t);return ue(s,this.scope.impl)?void 0:s}}const wd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Id=e=>{const t=v(e);if(!i.isIdentifier(t))return i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t);const s=R(t),n=i.isVariableDeclaration(s)?v(s.getInitializer()):void 0;return s===void 0||i.isFunctionDeclaration(s)||i.isParameterDeclaration(s)||i.isArrowFunction(n)||i.isFunctionExpression(n)},Cd=new Set(["all","allSettled","any","race"]),Ps=e=>i.isParameterDeclaration(e)?e:i.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,nt=8;class Td{budget=new Ad;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Pn();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Pd(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,nt)?!1:(i.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(r=>Ar(r)&&this.isIdentifierTainted(r))}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 r of this.referencesByName.get(s)??[]){const o=R(r)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],r])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(r=>r.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(f=>f.getInitializer())].some(f=>f!==void 0&&this.isTaintedValue(f,!1)))return!0;const n=t.getParentOrThrow(),r=i.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(f=>f.compilerNode===t.compilerNode):-1,o=b(n),a=o.getParent();if(r===-1)return!0;if(i.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,r,t.isRestParameter());const f=v(a.getExpression());if(!i.isPropertyAccessExpression(f)||!mt.has(f.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(f.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=i.isVariableDeclaration(a)&&Z(a)?a:void 0,l=i.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!i.isIdentifier(u))return!0;const g=this.referencesTo(l,u.getText());return g.length===0||g.some(f=>{const m=b(f),x=m.getParent();return!i.isCallExpression(x)||x.getExpression()!==m||this.isCallSiteTainted(x,r,t.isRestParameter())})}isCallSiteTainted(t,s,n){const r=t.getArguments(),o=r.findIndex(c=>i.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return r.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=v(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getExpression():void 0,a=i.isPropertyAccessExpression(n)&&i.isIdentifier(r)&&r.getText()==="Promise"&&Re(r)&&Cd.has(n.getName())?v(t.getArguments()[0]):void 0;if(i.isArrayLiteralExpression(a)){const g=a.getElements();return g.length>0&&g.every(f=>!i.isSpreadElement(f)&&this.isRootedInContext(f,s))}const c=i.isCallExpression(a)?v(a.getExpression()):void 0,l=i.isCallExpression(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="map"?v(a.getArguments()[0]):void 0,u=l===void 0?void 0:Ie(l);return u!==void 0&&u.length>0&&u.every(g=>g!==void 0&&this.isRootedInContext(g,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=R(t),r=Ps(n);if(r!==void 0)return this.isSource(r);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(i.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(i.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=i.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return i.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=v(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getName():void 0;return r!==void 0&&Zs.has(r)?!1:r!==void 0&&en.has(r)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Ie(a)!==void 0)&&(r===void 0||!wd.has(r))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(r,o=[])=>{const a=yt(r),c=i.isIdentifier(a)?Ps(R(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(r,s)||!this.isTaintedValue(r,!1)};return t.getArguments().every(r=>{const o=Ie(r);if(o===void 0)return!Id(r)&&n(r);const a=v(r),c=i.isArrowFunction(a)||i.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Tr(t,u=>this.callChainVerdict(u,s)),r=n.root;if(n.verdict!==void 0)return n.verdict;if(Sn(r,this.scope.context))return!0;const o=i.isIdentifier(r)?R(r):void 0,a=i.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=Z(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=i.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(i.isBindingElement(l)||i.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(i.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(i.isForOfStatement(s)||i.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),r=xt(t);if(n===void 0||r)return!0;if(this.isRootedInContext(n,nt))return!1;if(this.variableDepth>=nt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const ws=new WeakMap,Od=e=>{const t=ws.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Td(e);return ws.set(e.impl.compilerNode,s),s},Rd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),kd=new Set(["insert","insertManyUnsafe","patch","replace"]),Fd=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();return kd.has(t)&&Vr(e.getExpression())?t:void 0},Dd=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},Ld=(e,t)=>{const s=Or(e);return s?.member===t?v(s.object):void 0},Is=(e,t)=>i.isIdentifier(e)&&R(e)?.compilerNode===t.compilerNode,wn=(e,t,s,n=1)=>{const r=Ld(e,s);if(r!==void 0)return Is(r,t);const o=i.isIdentifier(e)?R(e):void 0;if(i.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&me(o)===s&&i.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||Z(l)&&Is(v(l.getInitializer()),t))}const a=Z(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&wn(a,t,s,n-1)},ht=e=>{const t=v(e)??e;return i.isConditionalExpression(t)?[...ht(t.getWhenTrue()),...ht(t.getWhenFalse())]:[t]},Md=(e,t,s)=>{const n=[],r=s===void 0?void 0:Od(s);for(const o of e.getProperties()){let a,c;if(i.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Rd.has(a))continue;if(ht(c).some(u=>r===void 0?j(u)&&!qr(u):r.isTaintedValue(u,!0))){const u=t.ownerField===a&&s?.pristine===!0&&wn(c,s.parameter,a);n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...u&&{ownerScoped:!0}})}}return n},_d=(e,t,s)=>{const n=Fd(e.getExpression()),r=n===void 0?void 0:e.getArguments()[1];if(n===void 0||r===void 0)return[];const o=Dd(r,n);if(o.length===0)return[];const a=h(e),c=ud(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Md(u,l,c))},Kd=(e,t,s=[],n=[])=>{const r=new Map(n.map(a=>[`${a.filePath}:${a.exportName}`,a.owner])),o=I(e,t,(a,c)=>_d(a,c,l=>r.get(`${c}:${l}`)));return St(o,s)},zd=["providerSubscriptionId","state"],Bd=["providerEventId","processedAt"],Cs=(e,t)=>t.every(s=>s in e.shape),$d=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&&Cs(t,zd)&&Cs(s,Bd)},Ud=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),jd=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Vd=e=>{const t=D(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?jd(t.getInitializer()):void 0},qd=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Ud.has(s))return;const[n]=e.getArguments(),r=n&&i.isObjectLiteralExpression(n)?Vd(n):void 0;return{callee:s,scope:h(e),file:t,line:e.getStartLineNumber(),...r===void 0?{}:{toleranceSeconds:r}}},Wd=(e,t)=>I(e,t,qd),Hd=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Gd=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Yd=(e,t)=>{const s=e.getArguments()[t];if(!s||!i.isObjectLiteralExpression(s))return;const n=D(s,"handler");if(n===void 0||!i.isPropertyAssignment(n))return;const r=n.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},In=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Cn=(e,t)=>e===t||e.startsWith(`${t}.`),Tn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Ts=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},On=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Ts(s));return i.isIdentifier(e)&&Ts(e)&&t.push(e),t},Qd=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Xd=e=>{const t=In(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const r=n.getInitializer(),o=i.isVariableDeclarationList(r)?r.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Jd=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Xd(e),r=new Set,o=a=>Tn(a).some(c=>n.some(l=>Cn(c.getText(),l)))?!0:On(a).some(c=>r.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Qd(a))r.add(l)}return{names:r,prefixes:n}},Zd=(e,t)=>Tn(e).some(s=>t.prefixes.some(n=>Cn(s.getText(),n)))?!0:On(e).some(s=>t.names.has(s.getText())),eu=e=>{const t=qs(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},tu=(e,t,s)=>{const n=In(e,0);if(n===void 0)return[];const r=Jd(e,t,n),o=new Set([n,...r.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!i.isPropertyAccessExpression(l)||!Vs.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Zd(u,r))continue;const g=eu(c.getArguments()[0]);g!==void 0&&a.push({dispatchKind:t,file:s,scope:h(c),line:c.getStartLineNumber(),targetExport:g.exportName,targetFile:g.file})}return a},su=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=Gd(n),o=r===void 0?void 0:Hd.get(r);if(o===void 0)continue;const a=Yd(n,o);a!==void 0&&s.push(...tu(a,r==="defineWorkflow"?"workflow":"queue",t))}return s},nu=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...su(r,w(t,n)))}return s},Os={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Rs=new Set(["account","credential","member","passkey","session","user"]),ru=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),iu=e=>{const s=ru(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Rs.has(s)||Rs.has(n)},ou=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},au=(e,t)=>{const{objects:s,opaque:n}=Nt(e,t);return Sa(s).some(r=>ou(r))?!0:n?void 0:!1},cu=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!D(t,"captcha"),usesRateLimit:!!D(t,"rateLimit")}},lu=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},Ce={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},du=e=>{const t=lu(e),s=t?A(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=cu(t);return{...Ce,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Os?{...Ce,[Os[s]]:!0}:Ce},uu=e=>{const t={...Ce};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const r=n.getName()==="use"?s.getArguments()[0]:void 0;if(r){const o=du(r);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},fu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),pu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!fu.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const r=e.getArguments()[0];return!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?!1:iu(r.getLiteralText())},gu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),ks=new Set(["queues","scheduler","topics","workflows"]),mu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!gu.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&ks.has(s.getName())&&Wr(s.getExpression()))return!0;s=s.getExpression()}const n=Js(s);return n?.length===1&&ks.has(n[0]??"")},hu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},Rn=new Set(["generateObject","generateText","streamObject","streamText"]),vu=e=>{const t=A(e.getExpression());return t!==void 0&&Rn.has(t)},Eu=e=>{const t=A(e.getExpression());if(t===void 0||!Rn.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!D(s,"maxOutputTokens")},xu=new Set(["log","span","trace"]),Su=new Set(["ai"]),yu=new Set(["email","mail"]),Au=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),rt=(e,t)=>[...t].some(s=>Be(e,s).length>0),bu=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Nu=new Set(["every","filter","flatMap","forEach","map","some"]),Pu=new Set(["all","allSettled","race"]),wu=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Nu.has(n))return t;const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="Promise"&&Pu.has(n))return t},Iu=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(bu.has(t.getKind())){const s=wu(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Cu=e=>{let t=e;for(;;){const s=t.getParent();if(!i.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(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Tu=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ou=e=>{let t=!1,s=!0;for(const n of[...Au].flatMap(r=>Be(e,r))){const r=Tu(n);r&&(t=!0,!Iu(r)&&!Cu(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ru=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Fs="lunora-advisor-exempt",ku=/^[\s*/]+/u,Fu=/[\w-]/u,Du=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
7
7
  `);for(const n of s.split(`
8
- `)){const r=n.replace(ku,"");if(!r.startsWith(Fs))continue;const o=r.slice(Fs.length);if(Fu.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Lu=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=D(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Mu=(e,t)=>{const s=Lu(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),r=s.getText(),o=n.getVariableDeclaration(r)?.getInitializer();return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:n.getFunction(r)},_u=e=>{let t=!1,s=!1,n=!1,r=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(gu(l)&&(o=!0),mu(l)&&(t=!0),hu(l)&&(r=!0),vu(l)&&(s=!0),Eu(l)&&(n=!0),o&&t&&r&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ou(e);return{callsMail:rt(e,yu),emitsEvent:rt(e,xu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||rt(e,Su),throwsBareError:Ru(e),unboundedAiGeneration:n,usesInsertManyUnsafe:r,writesUserTable:o}},Ku=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=H(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const r=n.receiver?uu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Mu(e,s);return{...o?_u(o):{},...Du(e),...r,analyzableBody:o!==void 0,exportName:K(e)??e.getName(),file:t,hasEmailArg:au(s,n.receiver),kind:n.kind,visibility:n.visibility}},zu=(e,t)=>{const s=[];for(const n of V(e)){const r=Ku(n,t);r&&s.push(r)}return s},Bu=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...zu(r,w(t,n)))}return s},$u=new Set(["dbRateLimit","rateLimit"]),Uu=e=>i.isArrowFunction(e)?e.getBody():e,ju=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},kn=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Fn=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const r=n.getParent();return!(i.isPropertyAccessExpression(r)&&r.getNameNode()===n)})},Vu=(e,t)=>j(e)||t!==void 0&&Fn(e,t).some(s=>kn(s)),qu=(e,t)=>t===void 0?ee(e):Fn(e,t).some(s=>!kn(s)),Wu=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!$u.has(s))return;const n=P(Hs(e.getArguments()[2]),"key");if(!n)return;const r=Uu(n),o=ju(n);if(!(!Vu(r,o)||qu(r,o)))return{callee:s,scope:h(e),file:t,limitName:Ws(e),line:e.getStartLineNumber()}},Hu=(e,t)=>I(e,t,Wu),Gu=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Yu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Gu.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},Qu=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Xu=e=>{let t=v(e)??e;for(;i.isAwaitExpression(t);)t=v(t.getExpression())??t.getExpression();return t},Dn=(e,t=!1)=>{const s=Xu(e);if(i.isIdentifier(s)){if(t)return;const n=Q(s);return n===void 0?void 0:Dn(n,!0)}if(i.isCallExpression(s))return Yu(s)??Qu(s)},Ju=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const r=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=n.getExpression();r===e&&o!==void 0&&s.push(o)}return s},Zu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=H(s);if(n?.kind!=="query")return[];const r=pn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&Lr(n.receiver,"output"),a=n.receiver!==void 0&&Gs(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Ju(r)){const p=Dn(u);p===void 0||c.has(p)||(c.add(p),l.push({exportName:K(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:p,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},ef=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Zu(a,o))}return s},tf=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(y(s));return t},sf=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=nn(o);if(a===void 0)continue;const c=tf(P(a.options,"with"));c.length!==0&&r.push({exportName:K(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return r},nf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...sf(a,o))}return s},Fe=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Fe(e.getLeft()),s=Fe(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},rf=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Fe(t)!==void 0},of=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return y(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},af=(e,t,s)=>yi(e)?!Rr(s)&&Ai(of(t)):!0,cf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],r=new Set;for(const o of n){if(rf(o))continue;const a=Fe(o);if(a===void 0)continue;const c=xi(a);if(c===void 0||!af(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;r.has(u)||(r.add(u),s.push({file:t,kind:c,line:l,preview:Si(a)}))}return s},lf=(e,t)=>{const s=[];for(const n of E(t,{includeSkipped:!0})){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...cf(r,w(t,n)))}return s},df=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=nn(o);if(a===void 0)continue;const c=P(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),u=!l&&j(c);!l&&!u||r.push({exportName:K(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return r},uf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...df(a,o))}return s},ff=new Set(["query","unsafe"]),gf=e=>!i.isPropertyAccessExpression(e)||!ff.has(e.getName())?!1:U(e.getExpression(),["sql"]),pf=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),mf=(e,t)=>{if(!gf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!pf(s)))return{file:t,line:s.getStartLineNumber(),scope:h(e)}},hf=(e,t)=>I(e,t,mf),vf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Ef=e=>{for(const[t,s]of vf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},xf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Ef(a);c!==void 0&&s.push({file:w(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Sf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),yf=(e,t,s=[])=>{const n=Ue(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Sf,requireUnmodifiedReach:!0});return St(n,s)},Af=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),bf=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Nf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=y(r);t.push(o),o==="expiresInSeconds"&&(s=bf(r.getInitializer()));continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Pf=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Af.get(t);return s===void 0?void 0:Xs(e.getExpression(),r=>r==="ctx.storage"||r.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},wf=(e,t)=>{const s=Pf(e.getExpression());if(s!==void 0)return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...Nf(e.getArguments()[s.optionsIndex])}},If=(e,t)=>I(e,t,wf),Cf=(e,t)=>{const s=zr(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,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")}},Tf=new Set(["delete","hardDelete","patch","replace","restore"]),Of=new Set(["insertMany","insertManyUnsafe","patchWhere"]),Rf=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Ds=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],r=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return r.length===n.length?r:[]},kf=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const r=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return r===void 0?[]:Ds(r,e)}return Ds(s,e)},Ls="",Ff=(e,t)=>{if(Of.has(e))return{method:e,tables:[t!==void 0&&i.isStringLiteral(t)?t.getLiteralText():Ls]};if(Tf.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:kf(t,e);return{method:e,tables:s.length===0?[Ls]:s}}},Df=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(_(n))return Ff(s,e.getArguments()[0]);if(Rf.has(s)&&i.isPropertyAccessExpression(n)&&_(n.getExpression()))return{method:s,tables:[n.getName()]}},Lf=(e,t)=>I(e,t,(s,n)=>{const r=Df(s);if(r===void 0)return;const o=h(s),a=s.getStartLineNumber();return r.tables.map(c=>({file:n,line:a,method:r.method,scope:o,table:c}))}),Mf=(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"}),_f=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||D(s,"args")===void 0)return!1}return Nt(e,t).opaque},Kf=(e,t)=>{const s=[],n=(r,o)=>{const a=r.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=H(a);c!==void 0&&_f(a,c.receiver)&&s.push(Mf(t,o,a.getStartLineNumber()))};for(const r of e.getVariableStatements().filter(o=>o.isExported()))for(const o of r.getDeclarations())n(o,o.getName());return s},zf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n);r!==void 0&&s.push(...Kf(r,w(t,n)))}return s.toSorted((n,r)=>n.cacheKey.localeCompare(r.cacheKey))},Bf=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["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"}]]),De=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Ln=e=>!e.isAny(),Mn=e=>{const t=e.getType();if(!Ln(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Bf.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},$f=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},_n={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."},Uf=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.`}),jf={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)."},Vf=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),qf={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)."},Wf=(e,t,s)=>{if(!t.some(r=>br(r)))return jf;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Vf.has(s.typeName)&&!n&&!t.some(r=>Ni(r))?qf:_n},Kn=(e,t,s,n,r)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,p=u===void 0?r:Uf(u),f=c===void 0?p.remediation:`${c} ${p.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 — ${p.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${f}`:f,title:"Procedure exists at runtime but is missing from the generated API"}},Hf=(e,t,s)=>{const n=[];for(const r of V(e)){const o=i.isIdentifier(r.getNameNode())?ot(r):[r.getName()],c=o.some(u=>De(s,t,u))||!$f(r)?void 0:Mn(r),[l=r.getName()]=o;c!==void 0&&n.push(Kn(t,l,c,r.getStartLineNumber(),Wf(r,o,c)))}return n},Gf=(e,t,s)=>{if(De(s,t,"default"))return[];const n=[];for(const r of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!i.isIdentifier(o.getExpression()))){const o=Mn(r.getExpression());o!==void 0&&n.push(Kn(t,"default",o,r.getStartLineNumber(),_n))}return n},Yf=(e,t,s)=>[...Hf(e,t,s),...Gf(e,t,s)],Qf=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>i.isIdentifier(n.getNameNode())).filter(n=>ot(n).some(r=>De(s,t,r))).filter(n=>{const r=n.getInitializer();return r!==void 0&&i.isCallExpression(r)&&i.isPropertyAccessExpression(r.getExpression())}).map(n=>{const r=ot(n).find(o=>De(s,t,o))??n.getName();return{declaration:n,exportName:r,relativePath:t}}),Xf=({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"}),Jf=(e,t,s)=>{const n=[],r=[];for(const a of E(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...Yf(c,l,s)),r.push(...Qf(c,l,s))}const[o]=r;return o!==void 0&&r.every(({declaration:a})=>!Ln(a.getType()))&&n.push(Xf(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Zf=new Set(["when","where"]),it=new Set(["definePolicy","defineShape"]),eg=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return it.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const r=n.getNameNode().getText();return it.has(r)?r:void 0}const s=t.getText();return it.has(s)?s:void 0},tg=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,zn=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(tg(e))return"empty-object";if(i.isParenthesizedExpression(e))return zn(e.getExpression())}},wt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),sg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>wt(t)===e),Bn=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>wt(t)===e),ng=e=>{const t=sg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Bn(e).length>0},rg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>wt(t)===e),vt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",ig=(e,t)=>vt(e)||vt(t),og=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Ms=e=>!vt(e)&&(i.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),ag=(e,t,s)=>{const n=og.get(e);if(n!==void 0)return ig(t,s)?n==="positive"?"negative":"positive":Ms(t)||Ms(s)?void 0:n},de=e=>{if(i.isParenthesizedExpression(e))return de(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=ag(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=de(e.getLeft()),r=de(e.getRight());return n===r?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},_s=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},cg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},lg=e=>i.isReturnStatement(e)?e.getExpression()??e:e,dg=e=>{const t=[];for(const s of Bn(e)){const n=de(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of rg(e)){const n=de(s.getExpression());if(n==="indeterminate")continue;const r=n==="negative"?_s(s.getThenStatement()):_s(s.getElseStatement())??cg(s);r!==void 0&&t.push(lg(r))}return t},ug=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},fg=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)||!Zf.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&ng(a))for(const c of dg(a)){const l=zn(c);l!==void 0&&r.push({exportName:ug(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return r},gg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=eg(n);r!==void 0&&s.push(...fg(n,r,t))}return s},pg=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...gg(r,w(t,n)))}return s},mg=new Set(["query","upsert","upsertNow"]),hg=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(mg.has(t))return U(e.getExpression(),["vectors"])?t:void 0},vg=(e,t)=>{const s=hg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const r=P(n,"namespace");if(!(!r||!j(r)||ee(r)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s}},Eg=(e,t)=>I(e,t,vg),xg=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},Sg=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},yg=(e,t)=>I(e,t,(s,n)=>xg(s)?{file:n,line:s.getStartLineNumber(),scope:h(s),workflow:Sg(s)}:void 0),Ag=".lunora-schema.json",Et=(e,t)=>{O(e)&&Jn(e,"utf8")===t||Zn(e,t,"utf8")},bg=(e,t)=>{if(t===""){er(e,{force:!0});return}Et(e,t)},Ng=e=>{try{const t=sr(S(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Pg=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},wg=e=>{let t=O(e)?e:Ne(e);for(;t&&t!==Ne(t);){const s=S(t,"tsconfig.json");if(O(s))return s;t=Ne(t)}},Ks=e=>e.replaceAll("\\","/"),Ig=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new W("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 r=t.columns.length>0;for(const o of e){if(o.table===void 0){if(r)throw new W("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 W("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})}},Le=(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)},zs=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Cg=8,Tg=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:r,migrations:o,project:a,shapes:c,usesSandbox:l,useUmbrella:u,workflows:p}=e,f=()=>ei(()=>{const N=ti(a,r),k=di(a,r);return{functions:N,httpRoutes:si(a,r),mutators:k}});let{erased:m,value:{functions:x,httpRoutes:z,mutators:B}}=f();ss([...x,...B].map(N=>N.filePath)),ss(z.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const k=Fi({agents:t,functions:x,httpRoutes:z,mutators:B,useUmbrella:u,workflows:p}),q=qi({agents:t,functions:x,migrations:o,mutators:B,shapes:c,useUmbrella:u,usesSandbox:l});if(N>=Cg||zs(a,s,k)&&zs(a,n,q))return{apiContent:k,erased:m,functions:x,functionsContent:q,httpRoutes:z,mutators:B};Le(a,s,k),Le(a,n,q),{erased:m,value:{functions:x,httpRoutes:z,mutators:B}}=f()}},Og=e=>{const t=wg(e);return t?new Xt({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Xt({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},qp=(e,t)=>{const s=E(t),n=S(t,"schema.ts");O(n)&&s.push(n);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const r=new Set(s.map(c=>Ks(c))),o=Ks(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!r.has(l)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const l=c.getFilePath();if(!(l===o||l.startsWith(a)||l.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Wp=e=>{const t=Pg(),s=t?Xe.now():0,n=S(e.projectRoot,e.lunoraDirectory??"lunora"),r=S(n,"schema.ts");if(!O(r))throw new W("INTERNAL",`schema.ts not found at ${r}`);const o=e.project??Og(n);Hr(Rc);const a=Ei(o,r,e.projectRoot),{agents:c,capabilities:l,containers:u,crons:p,dataModelContent:f,dependencies:m,entryCronTriggers:x,env:z,featureUsage:B,hasFlags:N,hasNotify:k,identity:q,platformGate:G,queues:F,serverContent:te,services:oe,storageRulesMetadata:ae,topics:se,usesSandbox:he,useUmbrella:$,workflows:L}=Bo({lunoraDirectory:n,project:o,projectRoot:e.projectRoot,schema:a,target:e.target});ml(a,a.jurisdiction===void 0?void 0:gl(o,n)),uo(a,B.artifacts);const M=S(n,"_generated"),T=S(M,"dataModel.ts"),$n=S(M,"server.ts"),Un=S(M,"api.ts"),jn=S(M,"functions.ts");Le(o,T,f),Le(o,$n,te);const ve=oi(o,n),ne=bi(o,n),{apiContent:It,erased:Vn,functions:Y,functionsContent:Ct,httpRoutes:je,mutators:Ee}=Tg({agents:c,apiPath:Un,generatedFunctionsPath:jn,lunoraDirectory:n,migrations:ve,project:o,shapes:ne,useUmbrella:$,usesSandbox:he,workflows:L}),Tt=ar(o,n),Ve=cr(Tt,a,[...Y,...je].map(g=>g.filePath)),xe=Tt.length>0,X=e.lint===!1&&!xe?void 0:{inserts:ri(o,n),queries:pi(o,n),tableWrites:Lf(o,n),workflowCalls:yg(o,n)},Se=e.lint===!1||X===void 0?void 0:rr({adminRoutes:Go(o,n),aiRawRuns:na(o,n),aiToolSideEffects:pa(o,n),argumentDerivedFetches:va(o,n),argumentValidators:Ia(o,n),authApiCalls:Gr(o,n),authConfigs:_a(o,n),browserUrlAccesses:$a(o,n),configCalls:ec(o,n),containerKeyAccesses:sc(o,n),containerOverrides:cc(o,n),containers:u,exportSinks:fc(o,n),staleMigrationImports:xf(o,n),failOpenGuards:vc(o,n),flagReads:wc(o,n),flagSecurityDefaults:Oc(o,n),geoIndexUsages:Dc(o,n),httpActionGuards:Wc(o,n),httpHeaderWrites:sl(o,n),hyperdriveCalls:ni(o,n),identityClaimReads:cl(o,n),imageDeliveryUrlAccesses:dl(o,n),inserts:X.inserts,kvKeyAccesses:vl(o,n,Y),mailRecipientAccesses:Al(o,n),maskProcedures:ii(o,n),maskStrategies:Ol(o,n),mutatorWrites:Ml(o,n),nondeterministicCalls:ui(o,n),normalizeIdAuthorizations:Xl(o,n),notifyCalls:gi(o,n),notifyConfig:fi(o,n),mutators:Ee,ownerFieldWrites:Kd(o,n,Y,Ee),unrestrictedWhereBranches:pg(o,n),paymentWebhooks:Wd(o,n),privilegedDispatches:nu(o,n),procedureProtections:Bu(o,n),queries:X.queries,queues:F,r2sqlCalls:mi(o,n),ratelimitKeySelectors:Hu(o,n),rawRowReturns:ef(o,n),relationLoads:nf(o,n),rlsProcedures:hi(o,n),schema:a,secretLiterals:lf(o,n),modules:Ve,shapes:ne,softDeleteReads:uf(o,n),sqlInterpolations:hf(o,n),storageKeyAccesses:yf(o,n,Y),storageUploads:If(o,n),tableWrites:X.tableWrites,vectorNamespaceAccesses:Eg(o,n),workflowCalls:X.workflowCalls,workflows:L,wranglerVariables:e.wranglerVariables}),Ot=Se===void 0?[]:Hi(e.projectRoot,[...tr(Se,{source:"static"}),...Jf(o,n,{byName:new Set([...L,...F,...c,...u].map(g=>g.exportName)),byPath:new Set([...Y,...Ee,...ne,...ve].map(g=>`${g.filePath}:${g.exportName}`))}),...zf(o,n),...Zr(Vn,n)]),qn=vi(o,n),Rt=Il(o,n);Ig(ne,Rt,Pl(o,n));const Wn=N?yc(o,n):[],qe=G.signals.vectorStore!==!1,ce=Cf(B,{containerCount:u.length,cronCount:p.length,dependencies:m,hasPaymentTables:$d(a.tables),queueCount:F.length,storageColumnCount:Object.keys(Qs(a)).length,storageRuleCount:ae.rules.length,vectorIndexCount:a.vectorIndexes.length,target:Ys(e.projectRoot,e.target),vectorStoreSupported:qe,workflowCount:L.length}),kt=t?Xe.now():0,We=Oi(a,ve.map(g=>g.id)),Ft=Br({advisories:Ot.filter(g=>g.name!=="procedure_type_check_unavailable"),advisorProcedures:Se?.procedureProtections??[],agents:c,capabilities:l,containers:u,env:z,flagKeys:Wn,hasFlags:N,hasNotify:k,hasVectors:qe,maskMetadata:Rt,mutators:Ee,queues:F,rlsMetadata:qn,schema:a,schemaSnapshot:We,shapes:ne,services:oe,storageRules:ae,studioFeatures:ce,topics:se,useUmbrella:$,workflows:L}),Dt=Ri(ne,m.has("@lunora/db"),$),Lt=Di(u,a.jurisdiction),Mt=Li(L),_t=Mi(c),Kt=_i(F),zt=Ki(p),Hn=zi(ce.scheduler),Gn=Bi(a.tables,$),Yn=or(e.projectRoot)?$i($):"",Bt=Ui(a.vectorIndexes),ye=Vi(a,$),$t=ki(m.has("@lunora/seed")),Ae=e.apiSpec??"openapi",He=Ae==="openapi"||Ae==="both",Ge=Ae==="openrpc"||Ae==="both",Ut=Pi({capabilities:l,emailAgents:c.filter(g=>g.onEmail===!0).map(g=>({className:g.className,exportName:g.exportName})),hasAccess:m.has("@lunora/cloudflare-access"),hasAuth:m.has("@lunora/auth"),hasFramework:m.has("@lunora/astro")||m.has("@lunora/svelte")||m.has("@lunora/vue")||O(S(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(g=>Bs(g)),hasHyperdriveGlobal:a.tables.some(g=>$s(g)),hasKvIntrospector:ce.kv,hasNotify:k,hasQueue:F.some(g=>g.mode==="push"),hasScheduler:ce.scheduler,hasSourcedTables:a.tables.some(g=>g.externalSource!==void 0),hasStorage:ce.storage,hasVectors:qe,hasWorkflow:L.length>0,identity:q,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(g=>({name:g.name,shardMode:g.shardMode})),useUmbrella:$,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(g=>g.voice===!0&&g.voiceBindingName!==void 0).map(g=>({bindingName:g.voiceBindingName,exportName:g.exportName})),wantsArchitecture:xe,wantsOpenApi:He,wantsOpenRpc:Ge}),jt=Ng(e.projectRoot),Vt=xe?Ve:[],qt=wi({functions:Y,httpRoutes:je,modules:Vt,version:jt}),Wt=Ci({functions:Y,modules:Vt,version:jt}),Ht=`${JSON.stringify(qt,void 0,2)}
8
+ `)){const r=n.replace(ku,"");if(!r.startsWith(Fs))continue;const o=r.slice(Fs.length);if(Fu.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Lu=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=D(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Mu=(e,t)=>{const s=Lu(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),r=s.getText(),o=n.getVariableDeclaration(r)?.getInitializer();return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:n.getFunction(r)},_u=e=>{let t=!1,s=!1,n=!1,r=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(pu(l)&&(o=!0),mu(l)&&(t=!0),hu(l)&&(r=!0),vu(l)&&(s=!0),Eu(l)&&(n=!0),o&&t&&r&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ou(e);return{callsMail:rt(e,yu),emitsEvent:rt(e,xu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||rt(e,Su),throwsBareError:Ru(e),unboundedAiGeneration:n,usesInsertManyUnsafe:r,writesUserTable:o}},Ku=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=H(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const r=n.receiver?uu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Mu(e,s);return{...o?_u(o):{},...Du(e),...r,analyzableBody:o!==void 0,exportName:K(e)??e.getName(),file:t,hasEmailArg:au(s,n.receiver),kind:n.kind,visibility:n.visibility}},zu=(e,t)=>{const s=[];for(const n of V(e)){const r=Ku(n,t);r&&s.push(r)}return s},Bu=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...zu(r,w(t,n)))}return s},$u=new Set(["dbRateLimit","rateLimit"]),Uu=e=>i.isArrowFunction(e)?e.getBody():e,ju=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},kn=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Fn=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const r=n.getParent();return!(i.isPropertyAccessExpression(r)&&r.getNameNode()===n)})},Vu=(e,t)=>j(e)||t!==void 0&&Fn(e,t).some(s=>kn(s)),qu=(e,t)=>t===void 0?ee(e):Fn(e,t).some(s=>!kn(s)),Wu=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!$u.has(s))return;const n=P(Hs(e.getArguments()[2]),"key");if(!n)return;const r=Uu(n),o=ju(n);if(!(!Vu(r,o)||qu(r,o)))return{callee:s,scope:h(e),file:t,limitName:Ws(e),line:e.getStartLineNumber()}},Hu=(e,t)=>I(e,t,Wu),Gu=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Yu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Gu.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},Qu=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Xu=e=>{let t=v(e)??e;for(;i.isAwaitExpression(t);)t=v(t.getExpression())??t.getExpression();return t},Dn=(e,t=!1)=>{const s=Xu(e);if(i.isIdentifier(s)){if(t)return;const n=Q(s);return n===void 0?void 0:Dn(n,!0)}if(i.isCallExpression(s))return Yu(s)??Qu(s)},Ju=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const r=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=n.getExpression();r===e&&o!==void 0&&s.push(o)}return s},Zu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=H(s);if(n?.kind!=="query")return[];const r=gn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&Lr(n.receiver,"output"),a=n.receiver!==void 0&&Gs(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Ju(r)){const g=Dn(u);g===void 0||c.has(g)||(c.add(g),l.push({exportName:K(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:g,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},ef=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Zu(a,o))}return s},tf=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(y(s));return t},sf=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=nn(o);if(a===void 0)continue;const c=tf(P(a.options,"with"));c.length!==0&&r.push({exportName:K(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return r},nf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...sf(a,o))}return s},Fe=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Fe(e.getLeft()),s=Fe(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},rf=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Fe(t)!==void 0},of=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return y(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},af=(e,t,s)=>yi(e)?!Rr(s)&&Ai(of(t)):!0,cf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],r=new Set;for(const o of n){if(rf(o))continue;const a=Fe(o);if(a===void 0)continue;const c=xi(a);if(c===void 0||!af(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;r.has(u)||(r.add(u),s.push({file:t,kind:c,line:l,preview:Si(a)}))}return s},lf=(e,t)=>{const s=[];for(const n of E(t,{includeSkipped:!0})){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...cf(r,w(t,n)))}return s},df=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?H(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=nn(o);if(a===void 0)continue;const c=P(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),u=!l&&j(c);!l&&!u||r.push({exportName:K(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return r},uf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...df(a,o))}return s},ff=new Set(["query","unsafe"]),pf=e=>!i.isPropertyAccessExpression(e)||!ff.has(e.getName())?!1:U(e.getExpression(),["sql"]),gf=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),mf=(e,t)=>{if(!pf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!gf(s)))return{file:t,line:s.getStartLineNumber(),scope:h(e)}},hf=(e,t)=>I(e,t,mf),vf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Ef=e=>{for(const[t,s]of vf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},xf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Ef(a);c!==void 0&&s.push({file:w(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Sf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),yf=(e,t,s=[])=>{const n=Ue(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Sf,requireUnmodifiedReach:!0});return St(n,s)},Af=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),bf=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Nf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=y(r);t.push(o),o==="expiresInSeconds"&&(s=bf(r.getInitializer()));continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Pf=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Af.get(t);return s===void 0?void 0:Xs(e.getExpression(),r=>r==="ctx.storage"||r.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},wf=(e,t)=>{const s=Pf(e.getExpression());if(s!==void 0)return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...Nf(e.getArguments()[s.optionsIndex])}},If=(e,t)=>I(e,t,wf),Cf=(e,t)=>{const s=zr(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,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")}},Tf=new Set(["delete","hardDelete","patch","replace","restore"]),Of=new Set(["insertMany","insertManyUnsafe","patchWhere"]),Rf=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Ds=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],r=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return r.length===n.length?r:[]},kf=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const r=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return r===void 0?[]:Ds(r,e)}return Ds(s,e)},Ls="",Ff=(e,t)=>{if(Of.has(e))return{method:e,tables:[t!==void 0&&i.isStringLiteral(t)?t.getLiteralText():Ls]};if(Tf.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:kf(t,e);return{method:e,tables:s.length===0?[Ls]:s}}},Df=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(_(n))return Ff(s,e.getArguments()[0]);if(Rf.has(s)&&i.isPropertyAccessExpression(n)&&_(n.getExpression()))return{method:s,tables:[n.getName()]}},Lf=(e,t)=>I(e,t,(s,n)=>{const r=Df(s);if(r===void 0)return;const o=h(s),a=s.getStartLineNumber();return r.tables.map(c=>({file:n,line:a,method:r.method,scope:o,table:c}))}),Mf=(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"}),_f=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||D(s,"args")===void 0)return!1}return Nt(e,t).opaque},Kf=(e,t)=>{const s=[],n=(r,o)=>{const a=r.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=H(a);c!==void 0&&_f(a,c.receiver)&&s.push(Mf(t,o,a.getStartLineNumber()))};for(const r of e.getVariableStatements().filter(o=>o.isExported()))for(const o of r.getDeclarations())n(o,o.getName());return s},zf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n);r!==void 0&&s.push(...Kf(r,w(t,n)))}return s.toSorted((n,r)=>n.cacheKey.localeCompare(r.cacheKey))},Bf=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["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"}]]),De=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Ln=e=>!e.isAny(),Mn=e=>{const t=e.getType();if(!Ln(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Bf.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},$f=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},_n={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."},Uf=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.`}),jf={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)."},Vf=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),qf={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)."},Wf=(e,t,s)=>{if(!t.some(r=>br(r)))return jf;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Vf.has(s.typeName)&&!n&&!t.some(r=>Ni(r))?qf:_n},Kn=(e,t,s,n,r)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,g=u===void 0?r:Uf(u),f=c===void 0?g.remediation:`${c} ${g.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 — ${g.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${f}`:f,title:"Procedure exists at runtime but is missing from the generated API"}},Hf=(e,t,s)=>{const n=[];for(const r of V(e)){const o=i.isIdentifier(r.getNameNode())?ot(r):[r.getName()],c=o.some(u=>De(s,t,u))||!$f(r)?void 0:Mn(r),[l=r.getName()]=o;c!==void 0&&n.push(Kn(t,l,c,r.getStartLineNumber(),Wf(r,o,c)))}return n},Gf=(e,t,s)=>{if(De(s,t,"default"))return[];const n=[];for(const r of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!i.isIdentifier(o.getExpression()))){const o=Mn(r.getExpression());o!==void 0&&n.push(Kn(t,"default",o,r.getStartLineNumber(),_n))}return n},Yf=(e,t,s)=>[...Hf(e,t,s),...Gf(e,t,s)],Qf=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>i.isIdentifier(n.getNameNode())).filter(n=>ot(n).some(r=>De(s,t,r))).filter(n=>{const r=n.getInitializer();return r!==void 0&&i.isCallExpression(r)&&i.isPropertyAccessExpression(r.getExpression())}).map(n=>{const r=ot(n).find(o=>De(s,t,o))??n.getName();return{declaration:n,exportName:r,relativePath:t}}),Xf=({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"}),Jf=(e,t,s)=>{const n=[],r=[];for(const a of E(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...Yf(c,l,s)),r.push(...Qf(c,l,s))}const[o]=r;return o!==void 0&&r.every(({declaration:a})=>!Ln(a.getType()))&&n.push(Xf(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Zf=new Set(["when","where"]),it=new Set(["definePolicy","defineShape"]),ep=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return it.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const r=n.getNameNode().getText();return it.has(r)?r:void 0}const s=t.getText();return it.has(s)?s:void 0},tp=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,zn=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(tp(e))return"empty-object";if(i.isParenthesizedExpression(e))return zn(e.getExpression())}},wt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),sp=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>wt(t)===e),Bn=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>wt(t)===e),np=e=>{const t=sp(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Bn(e).length>0},rp=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>wt(t)===e),vt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",ip=(e,t)=>vt(e)||vt(t),op=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Ms=e=>!vt(e)&&(i.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),ap=(e,t,s)=>{const n=op.get(e);if(n!==void 0)return ip(t,s)?n==="positive"?"negative":"positive":Ms(t)||Ms(s)?void 0:n},de=e=>{if(i.isParenthesizedExpression(e))return de(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=ap(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=de(e.getLeft()),r=de(e.getRight());return n===r?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},_s=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},cp=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},lp=e=>i.isReturnStatement(e)?e.getExpression()??e:e,dp=e=>{const t=[];for(const s of Bn(e)){const n=de(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of rp(e)){const n=de(s.getExpression());if(n==="indeterminate")continue;const r=n==="negative"?_s(s.getThenStatement()):_s(s.getElseStatement())??cp(s);r!==void 0&&t.push(lp(r))}return t},up=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},fp=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)||!Zf.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&np(a))for(const c of dp(a)){const l=zn(c);l!==void 0&&r.push({exportName:up(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return r},pp=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=ep(n);r!==void 0&&s.push(...fp(n,r,t))}return s},gp=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pp(r,w(t,n)))}return s},mp=new Set(["query","upsert","upsertNow"]),hp=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(mp.has(t))return U(e.getExpression(),["vectors"])?t:void 0},vp=(e,t)=>{const s=hp(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const r=P(n,"namespace");if(!(!r||!j(r)||ee(r)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s}},Ep=(e,t)=>I(e,t,vp),xp=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},Sp=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},yp=(e,t)=>I(e,t,(s,n)=>xp(s)?{file:n,line:s.getStartLineNumber(),scope:h(s),workflow:Sp(s)}:void 0),Ap=".lunora-schema.json",Et=(e,t)=>{O(e)&&Jn(e,"utf8")===t||Zn(e,t,"utf8")},bp=(e,t)=>{if(t===""){er(e,{force:!0});return}Et(e,t)},Np=e=>{try{const t=sr(S(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Pp=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},wp=e=>{let t=O(e)?e:Ne(e);for(;t&&t!==Ne(t);){const s=S(t,"tsconfig.json");if(O(s))return s;t=Ne(t)}},Ks=e=>e.replaceAll("\\","/"),Ip=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new W("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 r=t.columns.length>0;for(const o of e){if(o.table===void 0){if(r)throw new W("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 W("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})}},Le=(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)},zs=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Cp=8,Tp=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:r,migrations:o,project:a,shapes:c,usesSandbox:l,useUmbrella:u,workflows:g}=e,f=()=>ei(()=>{const N=ti(a,r),k=di(a,r);return{functions:N,httpRoutes:si(a,r),mutators:k}});let{erased:m,value:{functions:x,httpRoutes:z,mutators:B}}=f();ss([...x,...B].map(N=>N.filePath)),ss(z.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const k=Fi({agents:t,functions:x,httpRoutes:z,mutators:B,useUmbrella:u,workflows:g}),q=qi({agents:t,functions:x,migrations:o,mutators:B,shapes:c,useUmbrella:u,usesSandbox:l});if(N>=Cp||zs(a,s,k)&&zs(a,n,q))return{apiContent:k,erased:m,functions:x,functionsContent:q,httpRoutes:z,mutators:B};Le(a,s,k),Le(a,n,q),{erased:m,value:{functions:x,httpRoutes:z,mutators:B}}=f()}},Op=e=>{const t=wp(e);return t?new Xt({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Xt({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},qg=(e,t)=>{const s=E(t),n=S(t,"schema.ts");O(n)&&s.push(n);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const r=new Set(s.map(c=>Ks(c))),o=Ks(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!r.has(l)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const l=c.getFilePath();if(!(l===o||l.startsWith(a)||l.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Wg=e=>{const t=Pp(),s=t?Xe.now():0,n=S(e.projectRoot,e.lunoraDirectory??"lunora"),r=S(n,"schema.ts");if(!O(r))throw new W("INTERNAL",`schema.ts not found at ${r}`);const o=e.project??Op(n);Hr(Rc);const a=Ei(o,r,e.projectRoot),{agents:c,capabilities:l,containers:u,crons:g,dataModelContent:f,dependencies:m,entryCronTriggers:x,env:z,featureUsage:B,hasFlags:N,hasNotify:k,identity:q,platformGate:G,queues:F,serverContent:te,services:oe,storageRulesMetadata:ae,topics:se,usesSandbox:he,useUmbrella:$,workflows:L}=Bo({lunoraDirectory:n,project:o,projectRoot:e.projectRoot,schema:a,target:e.target});ml(a,a.jurisdiction===void 0?void 0:pl(o,n)),uo(a,B.artifacts);const M=S(n,"_generated"),T=S(M,"dataModel.ts"),$n=S(M,"server.ts"),Un=S(M,"api.ts"),jn=S(M,"functions.ts");Le(o,T,f),Le(o,$n,te);const ve=oi(o,n),ne=bi(o,n),{apiContent:It,erased:Vn,functions:Y,functionsContent:Ct,httpRoutes:je,mutators:Ee}=Tp({agents:c,apiPath:Un,generatedFunctionsPath:jn,lunoraDirectory:n,migrations:ve,project:o,shapes:ne,useUmbrella:$,usesSandbox:he,workflows:L}),Tt=ar(o,n),Ve=cr(Tt,a,[...Y,...je].map(p=>p.filePath)),xe=Tt.length>0,X=e.lint===!1&&!xe?void 0:{inserts:ri(o,n),queries:gi(o,n),tableWrites:Lf(o,n),workflowCalls:yp(o,n)},Se=e.lint===!1||X===void 0?void 0:rr({adminRoutes:Go(o,n),aiRawRuns:na(o,n),aiToolSideEffects:ga(o,n),argumentDerivedFetches:va(o,n),argumentValidators:Ia(o,n),authApiCalls:Gr(o,n),authConfigs:_a(o,n),browserUrlAccesses:$a(o,n),configCalls:ec(o,n),containerKeyAccesses:sc(o,n),containerOverrides:cc(o,n),containers:u,exportSinks:fc(o,n),staleMigrationImports:xf(o,n),failOpenGuards:vc(o,n),flagReads:wc(o,n),flagSecurityDefaults:Oc(o,n),geoIndexUsages:Dc(o,n),httpActionGuards:Wc(o,n),httpHeaderWrites:sl(o,n),hyperdriveCalls:ni(o,n),identityClaimReads:cl(o,n),imageDeliveryUrlAccesses:dl(o,n),inserts:X.inserts,kvKeyAccesses:vl(o,n,Y),mailRecipientAccesses:Al(o,n),maskProcedures:ii(o,n),maskStrategies:Ol(o,n),mutatorWrites:Ml(o,n),nondeterministicCalls:ui(o,n),normalizeIdAuthorizations:Xl(o,n),notifyCalls:pi(o,n),notifyConfig:fi(o,n),mutators:Ee,ownerFieldWrites:Kd(o,n,Y,Ee),unrestrictedWhereBranches:gp(o,n),paymentWebhooks:Wd(o,n),privilegedDispatches:nu(o,n),procedureProtections:Bu(o,n),queries:X.queries,queues:F,r2sqlCalls:mi(o,n),ratelimitKeySelectors:Hu(o,n),rawRowReturns:ef(o,n),relationLoads:nf(o,n),rlsProcedures:hi(o,n),schema:a,secretLiterals:lf(o,n),modules:Ve,shapes:ne,softDeleteReads:uf(o,n),sqlInterpolations:hf(o,n),storageKeyAccesses:yf(o,n,Y),storageUploads:If(o,n),tableWrites:X.tableWrites,vectorNamespaceAccesses:Ep(o,n),workflowCalls:X.workflowCalls,workflows:L,wranglerVariables:e.wranglerVariables}),Ot=Se===void 0?[]:Hi(e.projectRoot,[...tr(Se,{source:"static"}),...Jf(o,n,{byName:new Set([...L,...F,...c,...u].map(p=>p.exportName)),byPath:new Set([...Y,...Ee,...ne,...ve].map(p=>`${p.filePath}:${p.exportName}`))}),...zf(o,n),...Zr(Vn,n)]),qn=vi(o,n),Rt=Il(o,n);Ip(ne,Rt,Pl(o,n));const Wn=N?yc(o,n):[],qe=G.signals.vectorStore!==!1,ce=Cf(B,{containerCount:u.length,cronCount:g.length,dependencies:m,hasPaymentTables:$d(a.tables),queueCount:F.length,storageColumnCount:Object.keys(Qs(a)).length,storageRuleCount:ae.rules.length,vectorIndexCount:a.vectorIndexes.length,target:Ys(e.projectRoot,e.target),vectorStoreSupported:qe,workflowCount:L.length}),kt=t?Xe.now():0,We=Oi(a,ve.map(p=>p.id)),Ft=Br({advisories:Ot.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Se?.procedureProtections??[],agents:c,capabilities:l,containers:u,env:z,flagKeys:Wn,hasFlags:N,hasNotify:k,hasVectors:qe,maskMetadata:Rt,mutators:Ee,queues:F,rlsMetadata:qn,schema:a,schemaSnapshot:We,shapes:ne,services:oe,storageRules:ae,studioFeatures:ce,topics:se,useUmbrella:$,workflows:L}),Dt=Ri(ne,m.has("@lunora/db"),$),Lt=Di(u,a.jurisdiction),Mt=Li(L),_t=Mi(c),Kt=_i(F),zt=Ki(g),Hn=zi(ce.scheduler),Gn=Bi(a.tables,$),Yn=or(e.projectRoot)?$i($):"",Bt=Ui(a.vectorIndexes),ye=Vi(a,$),$t=ki(m.has("@lunora/seed")),Ae=e.apiSpec??"openapi",He=Ae==="openapi"||Ae==="both",Ge=Ae==="openrpc"||Ae==="both",Ut=Pi({capabilities:l,emailAgents:c.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:m.has("@lunora/cloudflare-access"),hasAuth:m.has("@lunora/auth"),hasFramework:m.has("@lunora/astro")||m.has("@lunora/svelte")||m.has("@lunora/vue")||O(S(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(p=>Bs(p)),hasHyperdriveGlobal:a.tables.some(p=>$s(p)),hasKvIntrospector:ce.kv,hasNotify:k,hasQueue:F.some(p=>p.mode==="push"),hasScheduler:ce.scheduler,hasSourcedTables:a.tables.some(p=>p.externalSource!==void 0),hasStorage:ce.storage,hasVectors:qe,hasWorkflow:L.length>0,identity:q,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:$,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:xe,wantsOpenApi:He,wantsOpenRpc:Ge}),jt=Np(e.projectRoot),Vt=xe?Ve:[],qt=wi({functions:Y,httpRoutes:je,modules:Vt,version:jt}),Wt=Ci({functions:Y,modules:Vt,version:jt}),Ht=`${JSON.stringify(qt,void 0,2)}
9
9
  `,Gt=`${JSON.stringify(Wt,void 0,2)}
10
- `,be=xe&&X!==void 0?co({...X,callEdges:Wa(o,n),crons:p,functions:Y,httpRoutes:je,modules:Ve,queues:F,schema:a,services:oe,topics:se,workflows:L}):void 0,Yt=Ii(qt),Qt=Ti(Wt),Ye=S(n,Ag),Qn=O(Ye),Qe=[];if(!e.dryRun){O(M)||Xn(M,{recursive:!0});const g=(J,re)=>{Et(S(M,J),re),Qe.push(J)},C=(J,re)=>{bg(S(M,J),re),re!==""&&Qe.push(J)};g("app.ts",Ut),g("dataModel.ts",f),g("api.ts",It),g("server.ts",te),g("functions.ts",Ct),g("shard.ts",Ft),g("crons.ts",zt),g("vectors.ts",Bt),g("drizzle.global.ts",ye.global),g("drizzle.shard.ts",ye.shard),C("containers.ts",Lt),C("workflows.ts",Mt),C("agents.ts",_t),C("queues.ts",Kt),C("scheduler.ts",Hn),C("shardRegistry.ts",Gn),C("durableObjects.ts",Yn),C("seed.ts",$t),C("collections.ts",Dt),C("openapi.json",He?Ht:""),C("openapi.ts",He?Yt:""),C("openrpc.json",Ge?Gt:""),C("openrpc.ts",Ge?Qt:""),C("architecture.json",be===void 0?"":`${JSON.stringify(be,void 0,2)}
11
- `),C("architecture.ts",be===void 0?"":lo(be)),(!Qn||e.updateSchemaBaseline===!0)&&Et(Ye,nr(We))}if(t){const g=Xe.now(),C=Math.round(g-s),J=Math.round(kt-s),re=Math.round(g-kt);console.error(`@lunora/codegen: codegen took ${C.toString()}ms (discovery ${J.toString()}ms, emit ${re.toString()}ms)`)}return{advisories:Ot,advisorContext:Se,agents:c,containers:u,cronTriggers:[...new Set([...ji(p),...x])],generated:{agents:_t,api:It,app:Ut,collections:Dt,containers:Lt,crons:zt,dataModel:f,drizzleGlobal:ye.global,drizzleShard:ye.shard,functions:Ct,openApi:Ht,openApiModule:Yt,openRpc:Gt,openRpcModule:Qt,queues:Kt,seed:$t,server:te,shard:Ft,vectors:Bt,workflows:Mt},migrations:ve,outputDirectory:M,platformDiagnostics:G.diagnostics,queues:F,schemaSnapshot:We,schemaSnapshotPath:Ye,workflows:L,writtenFiles:Qe}};export{Ag as SCHEMA_SNAPSHOT_FILENAME,Og as createCodegenProject,wg as findTsconfig,qp as refreshCodegenProject,Wp as runCodegen};
10
+ `,be=xe&&X!==void 0?co({...X,callEdges:Wa(o,n),crons:g,functions:Y,httpRoutes:je,modules:Ve,queues:F,schema:a,services:oe,topics:se,workflows:L}):void 0,Yt=Ii(qt),Qt=Ti(Wt),Ye=S(n,Ap),Qn=O(Ye),Qe=[];if(!e.dryRun){O(M)||Xn(M,{recursive:!0});const p=(J,re)=>{Et(S(M,J),re),Qe.push(J)},C=(J,re)=>{bp(S(M,J),re),re!==""&&Qe.push(J)};p("app.ts",Ut),p("dataModel.ts",f),p("api.ts",It),p("server.ts",te),p("functions.ts",Ct),p("shard.ts",Ft),p("crons.ts",zt),p("vectors.ts",Bt),p("drizzle.global.ts",ye.global),p("drizzle.shard.ts",ye.shard),C("containers.ts",Lt),C("workflows.ts",Mt),C("agents.ts",_t),C("queues.ts",Kt),C("scheduler.ts",Hn),C("shardRegistry.ts",Gn),C("durableObjects.ts",Yn),C("seed.ts",$t),C("collections.ts",Dt),C("openapi.json",He?Ht:""),C("openapi.ts",He?Yt:""),C("openrpc.json",Ge?Gt:""),C("openrpc.ts",Ge?Qt:""),C("architecture.json",be===void 0?"":`${JSON.stringify(be,void 0,2)}
11
+ `),C("architecture.ts",be===void 0?"":lo(be)),(!Qn||e.updateSchemaBaseline===!0)&&Et(Ye,nr(We))}if(t){const p=Xe.now(),C=Math.round(p-s),J=Math.round(kt-s),re=Math.round(p-kt);console.error(`@lunora/codegen: codegen took ${C.toString()}ms (discovery ${J.toString()}ms, emit ${re.toString()}ms)`)}return{advisories:Ot,advisorContext:Se,agents:c,containers:u,cronTriggers:[...new Set([...ji(g),...x])],generated:{agents:_t,api:It,app:Ut,collections:Dt,containers:Lt,crons:zt,dataModel:f,drizzleGlobal:ye.global,drizzleShard:ye.shard,functions:Ct,openApi:Ht,openApiModule:Yt,openRpc:Gt,openRpcModule:Qt,queues:Kt,seed:$t,server:te,shard:Ft,vectors:Bt,workflows:Mt},migrations:ve,outputDirectory:M,platformDiagnostics:G.diagnostics,queues:F,schemaSnapshot:We,schemaSnapshotPath:Ye,workflows:L,writtenFiles:Qe}};export{Ap as SCHEMA_SNAPSHOT_FILENAME,Op as createCodegenProject,wp as findTsconfig,qg as refreshCodegenProject,Wg as runCodegen};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{Node as i,SyntaxKind as F}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as C}from"node:module";import{join as _}from"node:path";import{fileURLToPath as B}from"node:url";import{createJiti as V}from"jiti";import{findObjectProperty as u}from"./isTestPath-Djd59sWZ.mjs";import{r as q,p as J}from"./parse-validator-DLAJeWE4.mjs";import{R as U}from"./reserved-words-CW1QFbTd.mjs";import{a as I}from"./project-config-file-CD247zmH.mjs";const K=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,W=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},Z=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:Z(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=W(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},G=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",X=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},H=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return X(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:G(e.shardMode),vectorIndexes:[]}},Q=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>H(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},Y=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},ee=e=>{const t=Y(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},te=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ne=(e,t)=>{const n=ee(e);if(n)try{const s=V(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=C(_(t,"noop.cjs"))(s.startsWith("file:")?B(s):s),o=te(r,n);return typeof o!="object"||o===null?void 0:Q(o)}catch{return}},re=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},O=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},A=e=>e&&re.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",se=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},N=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ie=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,oe=/^(?:sqlite_|_cf_|__)/u,ae=/__(?:agg|rank|geo|fts)_/u,le=e=>oe.test(e)||ae.test(e),ce=new Set(["cascade","restrict","set null"]),de=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),P=/^[A-Za-z_$][\w$]*$/u,S=(e,t)=>{if(de.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(U.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!P.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(le(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},fe=e=>e&&ce.has(e)?e:void 0,ue=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},pe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?fe(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ge=e=>{const t=ue(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=pe(s);r&&n.push(r)}return n},me=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},be=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},xe=e=>{const[t,n,s]=e,r=be(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)me(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},he=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=O(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},ye=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},ve=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},Ee=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Ie=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Ee(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Se=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:A(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},ke=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Te=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:se(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},_e=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ye(n));break}case"global":{e.shardMode="global",e.globalBackend=ke(n);break}case"index":{e.indexes.push(xe(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Ie(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ge(r));break}case"searchIndex":{e.searchIndexes.push(he(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Te(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=ve(n);break}case"vectorize":{const r=Se(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Le=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Oe=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ie(t))},$=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))_e(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=J(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Le(e,t,n.searchIndexes),Oe(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=q(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(S(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push($(o,a))}}return t},Ae=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Ne=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:A(f(s,"metric")),name:o,table:Ae(s)}},D=e=>{const t=[];for(const n of e.getProperties()){const s=Ne(n);s&&t.push(s)}return t},k=(e,t)=>`${e}_${t}`,Pe=(e,t)=>{if(!P.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?k(t,e):e,$e=(e,t,n,s)=>{const r=k(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},je=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},De=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},ze=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Me=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Re=(e,t)=>{const n=je(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Me(n);return s?b(s,t.getName()):void 0}return n}},Fe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,De(t))return t;const s=ze(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Re(a,t)}},Ce=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Be=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);S(a,r.getNameNode()),s.push($(o,a))}return s},Ve=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:D(n)},z=(e,t,n,s,r)=>{Pe(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>$e(c,e,o,r)),l=n.map(c=>({...c,name:k(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},qe=(e,t,n)=>z(e,Be(n),Ve(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Je=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Fe(n);if(!s){if(t!==void 0){const o=ne(n,t);if(o){for(const a of o.bareTables)S(a.name,n);return z(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Ce(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return qe(r.key,r.keyNode,r.options)},Ue=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Ke=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ue(e)){const a=Je(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},We=new Set(["eu","fedramp","us"]),Ze=e=>N(e,"jurisdiction","jurisdiction",We,'"eu", "us", or "fedramp"'),Ge=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&O(r,"pinAuth")===!0}t=s}},Xe=new Set(["required"]),He=e=>N(e,"rls","rls mode",Xe,'"required"'),ct=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(F.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new R("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?D(l):[],g=Ke(r,a,n),w=[...a.flatMap(p=>p.vectorIndexes),...c,...g],M=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=w.find(p=>M.has(p.table));if(v)throw d(r,K(v.table,v.name));return{jurisdiction:Ze(r),...Ge(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:He(r),tables:a,vectorIndexes:w}};export{ct as default};
@@ -1 +1 @@
1
- import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{o as i,j as r,s as o,h as n,t as g,k as F,d as u,v as p,m as f,g as l,f as d,i as k,u as w,l as Q}from"./shard-runtime-B1nU9CRa.mjs";import"./shared-BXUKWh7t.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,o as emitAgents,n as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,f as emitQueuesMetadataFragments,l as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowFragments,w as emitWorkflows,Q as emitWorkflowsMetadataFragments};
1
+ import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{o as i,j as r,s as o,h as n,t as g,k as F,d as u,v as p,m as f,g as l,f as d,i as k,u as w,l as Q}from"./shard-runtime-BXp-lUsd.mjs";import"./shared-BXUKWh7t.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,o as emitAgents,n as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,f as emitQueuesMetadataFragments,l as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowFragments,w as emitWorkflows,Q as emitWorkflowsMetadataFragments};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as f}from"./shard-WXSIZRpD.mjs";import"./shard-runtime-B1nU9CRa.mjs";import"./shared-BXUKWh7t.mjs";export{f as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as f}from"./shard-DTJX0sDf.mjs";import"./shard-runtime-BXp-lUsd.mjs";import"./shared-BXUKWh7t.mjs";export{f as default};
@@ -1,4 +1,4 @@
1
- import{LunoraError as vt}from"@lunora/errors";import{serializeSchemaSnapshot as kt,hashSchemaSnapshot as St}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Rt,isD1GlobalTable as xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{p as At,i as Dt}from"./ir-DBSvhNa-.mjs";import{r as h}from"./json-data-Chfs2Cz5.mjs";import{r as C,e as Tt,a as Ot,b as Et,c as Ct,d as Lt,f as It,g as _t,h as Mt,i as Pt,j as qt,k as Nt,l as $t,m as Ft,n as Ut,o as Bt,p as Wt,q as jt}from"./shard-runtime-B1nU9CRa.mjs";import{u as K,i as Ht,G as Vt,d as Kt}from"./shared-BXUKWh7t.mjs";const Gt=` /**
1
+ import{LunoraError as vt}from"@lunora/errors";import{serializeSchemaSnapshot as kt,hashSchemaSnapshot as St}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Rt,isD1GlobalTable as xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{p as At,i as Dt}from"./ir-DBSvhNa-.mjs";import{r as h}from"./json-data-Chfs2Cz5.mjs";import{r as C,e as Tt,a as Ot,b as Et,c as Ct,d as Lt,f as It,g as _t,h as Mt,i as Pt,j as qt,k as Nt,l as $t,m as Ft,n as Ut,o as Bt,p as Wt,q as jt}from"./shard-runtime-BXp-lUsd.mjs";import{u as K,i as Ht,G as Vt,d as Kt}from"./shared-BXUKWh7t.mjs";const Gt=` /**
2
2
  * The bare writer every admin/maintenance entry point writes through.
3
3
  *
4
4
  * Admin and maintenance writes go through the SAME reactive-cache hooks as a
@@ -1,4 +1,4 @@
1
- import{s as b}from"./ir-DBSvhNa-.mjs";import{r as y}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as $}from"./CAPABILITY_PROBES-DFsutD7g.mjs";import{a as c,G as p}from"./shared-BXUKWh7t.mjs";const W=e=>e?{importFragment:"serveRelationFanout, ",override:`
1
+ import{s as b}from"./ir-DBSvhNa-.mjs";import{r as y}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as $}from"./CAPABILITY_PROBES-DFsutD7g.mjs";import{a as c,G as p}from"./shared-BXUKWh7t.mjs";const I=e=>e?{importFragment:"serveRelationFanout, ",override:`
2
2
  protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
3
3
  this.ensureMigrated();
4
4
 
@@ -6,14 +6,14 @@ import{s as b}from"./ir-DBSvhNa-.mjs";import{r as y}from"./json-data-Chfs2Cz5.mj
6
6
 
7
7
  return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
8
8
  }
9
- `}:{importFragment:"",override:""},g=(e,r,t,{cast:n="",sync:o=[]}={})=>{const i=`throw new Error(${JSON.stringify(r)});`,u=t.map(a=>` ${a}: ${o.includes(a)?"":"async "}() => {
9
+ `}:{importFragment:"",override:""},g=(e,r,t,{cast:n="",sync:o=[]}={})=>{const i=`throw new Error(${JSON.stringify(r)});`,u=t.map(a=>` ${a}: ${o===!0||o.includes(a)?"":"async "}() => {
10
10
  ${i}
11
11
  },`).join(`
12
12
  `);return`
13
13
  const ${e} = {
14
14
  ${u}
15
15
  }${n};
16
- `},f={build:"",configField:"",contextField:"",importLines:[],stub:""},I=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
16
+ `},f={build:"",configField:"",contextField:"",importLines:[],stub:""},W=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
17
17
  /** The \`.shardBy()\` tables this shard registers with the shard registry when it writes them. */
18
18
  const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(r=>JSON.stringify(r)).join(", ")}]);
19
19
  `,override:`
@@ -22,21 +22,21 @@ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(r=>JSON.string
22
22
 
23
23
  return namespace === undefined ? undefined : { namespace, shardedTables: SHARDED_TABLES };
24
24
  }
25
- `},T=(e,r)=>e?{build:`
25
+ `},q=(e,r)=>e?{build:`
26
26
  const flags: import("${r}").LunoraFlags = createFlags(flagsConfig, env, {
27
27
  provider: () => config.flags?.(env),
28
28
  targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
29
29
  });
30
30
  `,configField:`
31
31
  flags?: (env: Record<string, unknown>) => import("${r}").Provider;`,contextField:`
32
- flags,`,importLines:[`import { createFlags } from "${r}";`,'import flagsConfig from "../flags.js";'],stub:""}:f,q=e=>e?{build:`
32
+ flags,`,importLines:[`import { createFlags } from "${r}";`,'import flagsConfig from "../flags.js";'],stub:""}:f,B=e=>e?{build:`
33
33
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
34
34
  `,configField:"",contextField:`
35
35
  notify,
36
- push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:f,B=e=>e?{build:`
36
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:f,D=e=>e?{build:`
37
37
  const envConfig = lunoraEnvContract.${e.exportName}(env);
38
38
  `,configField:"",contextField:`
39
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:f,D=(e,r,t)=>{if(!r)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const n=a=>`
39
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:f,U=(e,r,t)=>{if(!r)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const n=a=>`
40
40
  const env = (this.env ?? {}) as Record<string, unknown>;
41
41
  const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
42
42
  provider: () => config.flags?.(env),
@@ -148,8 +148,8 @@ ${d}]);
148
148
  ${d}const ${e}: ${o} = config.${e} ? ${l} : ${e}Stub;
149
149
  `,configField:`
150
150
  ${e}?: (env: Record<string, unknown>) => ${o};`,importLines:[`import type { ${o} } from "${r}";`],stub:i}}const u=n.bindingType??o,a=[...new Set([u,o])].toSorted((l,s)=>l.localeCompare(s));return{build:C(e,o,n),configField:`
151
- ${e}?: (env: Record<string, unknown>) => ${u};`,importLines:[`import type { ${a.join(", ")} } from "${r}";`,...n.factory===void 0?[]:[`import { ${n.factory.name} } from "${r}";`]],stub:i}},U=e=>{const r=[],t=[];let n="",o="",i="",u="",a="";for(const l of $.filter(({key:s})=>e.has(s))){let s;if(w(l))s=S[l.key]();else if(L(l))s=F(l.contextProperty,l.moduleSpecifier,l.shardBinding);else continue;const m=l.contextProperty;t.push(...s.importLines),o+=s.configField,a+=s.stub,l.tier==="every"?(i+=s.build,u+=`
152
- ${m},`):(n+=s.build,r.push(m))}return{actionBuild:n,actionFields:r,configFields:o,everyBuild:i,everyFields:u,importLines:t,stubs:a}},j=(e,r)=>{if(e.length===0)return"";const t=r?`, ${JSON.stringify(r)}`:"",n=e.map(s=>{c(s.exportName,`container export "${s.exportName}"`),c(s.className,`container class "${s.className}"`);const m=s.sandbox===!0?"LunoraSandboxContainer":"LunoraContainer";return`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
151
+ ${e}?: (env: Record<string, unknown>) => ${u};`,importLines:[`import type { ${a.join(", ")} } from "${r}";`,...n.factory===void 0?[]:[`import { ${n.factory.name} } from "${r}";`]],stub:i}},j=e=>{const r=[],t=[];let n="",o="",i="",u="",a="";for(const l of $.filter(({key:s})=>e.has(s))){let s;if(w(l))s=S[l.key]();else if(L(l))s=F(l.contextProperty,l.moduleSpecifier,l.shardBinding);else continue;const m=l.contextProperty;t.push(...s.importLines),o+=s.configField,a+=s.stub,l.tier==="every"?(i+=s.build,u+=`
152
+ ${m},`):(n+=s.build,r.push(m))}return{actionBuild:n,actionFields:r,configFields:o,everyBuild:i,everyFields:u,importLines:t,stubs:a}},Q=(e,r)=>{if(e.length===0)return"";const t=r?`, ${JSON.stringify(r)}`:"",n=e.map(s=>{c(s.exportName,`container export "${s.exportName}"`),c(s.className,`container class "${s.className}"`);const m=s.sandbox===!0?"LunoraSandboxContainer":"LunoraContainer";return`/** Container DO for the \`${s.exportName}\` definition (binding \`${s.bindingName}\`). */
153
153
  export class ${s.className} extends ${m} {
154
154
  public constructor(ctx: ConstructorParameters<typeof ${m}>[0], env: Record<string, unknown>) {
155
155
  super(ctx, env, ${s.exportName}, "${s.exportName}"${t});
@@ -181,7 +181,7 @@ ${i?`
181
181
  */
182
182
  export { DirectoryBackupGateway, S3Gateway } from "@lunora/container/sandbox";
183
183
  `:""}
184
- ${n}`},Q=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)c(n.exportName,`container export "${n.exportName}"`),c(n.bindingName,`container binding "${n.bindingName}"`);const t=e.map(n=>{const o=n.schedulingPolicy!==void 0||n.maxInstances===void 0?"":`, maxInstances: ${String(n.maxInstances)}`;return` { binding: "${n.bindingName}", exportName: "${n.exportName}"${o} },`}).join(`
184
+ ${n}`},M=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)c(n.exportName,`container export "${n.exportName}"`),c(n.bindingName,`container binding "${n.bindingName}"`);const t=e.map(n=>{const o=n.schedulingPolicy!==void 0||n.maxInstances===void 0?"":`, maxInstances: ${String(n.maxInstances)}`;return` { binding: "${n.bindingName}", exportName: "${n.exportName}"${o} },`}).join(`
185
185
  `);return{build:`
186
186
  const containers = createContainerContext(env, LUNORA_CONTAINERS, ${r?JSON.stringify(r):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
187
187
  `,contextField:`
@@ -190,7 +190,7 @@ ${n}`},Q=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],
190
190
  const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
191
191
  ${t}
192
192
  ];
193
- `}},M=e=>{if(e.length===0)return"";const r=e.map(n=>(c(n.exportName,`workflow export "${n.exportName}"`),c(n.className,`workflow class "${n.className}"`),`/** WorkflowEntrypoint for the \`${n.exportName}\` definition, reached as \`ctx.exports.${n.className}\`. */
193
+ `}},K=e=>{if(e.length===0)return"";const r=e.map(n=>(c(n.exportName,`workflow export "${n.exportName}"`),c(n.className,`workflow class "${n.className}"`),`/** WorkflowEntrypoint for the \`${n.exportName}\` definition, reached as \`ctx.exports.${n.className}\`. */
194
194
  export class ${n.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${n.exportName}>, WorkflowOutputOf<typeof ${n.exportName}>> {
195
195
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
196
196
  super(ctx, env, ${n.exportName}, "${n.exportName}");
@@ -218,7 +218,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
218
218
  /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
219
219
  type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
220
220
 
221
- ${r}`},K=e=>{if(e.length===0)return"";const t=e.filter(a=>a.voice).length>0,n=e.map(a=>{c(a.exportName,`agent export "${a.exportName}"`),c(a.className,`agent class "${a.className}"`);const l=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent, reached as \`ctx.exports.${a.className}\`. */
221
+ ${r}`},G=e=>{if(e.length===0)return"";const t=e.filter(a=>a.voice).length>0,n=e.map(a=>{c(a.exportName,`agent export "${a.exportName}"`),c(a.className,`agent class "${a.className}"`);const l=`/** WorkflowEntrypoint for the \`${a.exportName}\` agent, reached as \`ctx.exports.${a.className}\`. */
222
222
  export class ${a.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
223
223
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
224
224
  super(ctx, env, compileAgentWorkflow(${a.exportName}, "${a.exportName}"), "${a.exportName}");
@@ -246,7 +246,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
246
246
 
247
247
  import { ${o} } from "../agents.js";
248
248
 
249
- ${n}`},G=e=>{const r=e.filter(o=>o.mode==="push");if(r.length===0)return"";for(const o of r)c(o.exportName,`queue export "${o.exportName}"`);const t=r.map(o=>o.exportName).join(", "),n=r.map(o=>` ${JSON.stringify(o.name)}: { binding: ${JSON.stringify(o.bindingName)}, definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
249
+ ${n}`},H=e=>{const r=e.filter(o=>o.mode==="push");if(r.length===0)return"";for(const o of r)c(o.exportName,`queue export "${o.exportName}"`);const t=r.map(o=>o.exportName).join(", "),n=r.map(o=>` ${JSON.stringify(o.name)}: { binding: ${JSON.stringify(o.bindingName)}, definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
250
250
  `);return`${p}/**
251
251
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
252
252
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
@@ -261,7 +261,7 @@ import { ${t} } from "../queues.js";
261
261
  export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
262
262
  ${n}
263
263
  };
264
- `},H=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)c(t.exportName,`workflow export "${t.exportName}"`),c(t.className,`workflow class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}" },`).join(`
264
+ `},J=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)c(t.exportName,`workflow export "${t.exportName}"`),c(t.className,`workflow class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}" },`).join(`
265
265
  `);return{build:`
266
266
  const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS, this.state.exports);
267
267
  `,contextField:`
@@ -270,7 +270,7 @@ ${n}
270
270
  const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
271
271
  ${r}
272
272
  ];
273
- `}},J=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)c(t.exportName,`queue export "${t.exportName}"`),c(t.bindingName,`queue binding "${t.bindingName}"`);const r=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}", name: ${JSON.stringify(t.name)} },`).join(`
273
+ `}},V=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)c(t.exportName,`queue export "${t.exportName}"`),c(t.bindingName,`queue binding "${t.bindingName}"`);const r=e.map(t=>` { binding: "${t.bindingName}", exportName: "${t.exportName}", name: ${JSON.stringify(t.name)} },`).join(`
274
274
  `);return{build:`
275
275
  const queues = createQueueContext(env, LUNORA_QUEUES);
276
276
  `,contextField:`
@@ -279,7 +279,7 @@ ${r}
279
279
  const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
280
280
  ${r}
281
281
  ];
282
- `}},V=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{c(n.exportName,`topic export "${n.exportName}"`);const o=b(r,n.exportName).map(i=>`{ binding: "${i.bindingName}", exportName: "${i.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${o}] },`}).join(`
282
+ `}},Y=(e,r)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const t=e.map(n=>{c(n.exportName,`topic export "${n.exportName}"`);const o=b(r,n.exportName).map(i=>`{ binding: "${i.bindingName}", exportName: "${i.exportName}" }`).join(", ");return` { exportName: "${n.exportName}", subscriptions: [${o}] },`}).join(`
283
283
  `);return{build:`
284
284
  const topics = createTopicContext(env, LUNORA_TOPICS);
285
285
  `,contextField:`
@@ -288,7 +288,7 @@ ${r}
288
288
  const LUNORA_TOPICS: ReadonlyArray<TopicBindingSpec> = [
289
289
  ${t}
290
290
  ];
291
- `}},Y=(e,r)=>{if(e.length===0)return{build:"",importLines:[],specs:""};const t=e.map(n=>(c(n.name,`service "${n.name}"`),c(n.binding,`service binding "${n.binding}"`),` { binding: "${n.binding}", name: "${n.name}"${n.rpcEntrypoint===void 0?"":", rpc: true"} },`)).join(`
291
+ `}},X=(e,r)=>{if(e.length===0)return{build:"",importLines:[],specs:""};const t=e.map(n=>(c(n.name,`service "${n.name}"`),c(n.binding,`service binding "${n.binding}"`),` { binding: "${n.binding}", name: "${n.name}"${n.rpcEntrypoint===void 0?"":", rpc: true"} },`)).join(`
292
292
  `);return{build:`
293
293
  const services = createServices(env, LUNORA_SERVICES);
294
294
  `,importLines:[`import type { ServiceBindingSpec } from "${r}";`,`import { createServices } from "${r}";`],specs:`
@@ -296,7 +296,7 @@ ${t}
296
296
  const LUNORA_SERVICES: ReadonlyArray<ServiceBindingSpec> = [
297
297
  ${t}
298
298
  ];
299
- `}},X=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)c(t.exportName,`agent export "${t.exportName}"`),c(t.className,`agent class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}"${t.publicRun===!0?", publicRun: true":""} },`).join(`
299
+ `}},z=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const t of e)c(t.exportName,`agent export "${t.exportName}"`),c(t.className,`agent class "${t.className}"`);const r=e.map(t=>` { className: "${t.className}", exportName: "${t.exportName}"${t.publicRun===!0?", publicRun: true":""} },`).join(`
300
300
  `);return{build:`
301
301
  const agents = createAgentContext(env, LUNORA_AGENTS, { exports: this.state.exports });
302
302
  `,contextField:`
@@ -312,10 +312,14 @@ const ${e} = ${y(n,r)};
312
312
  protected override ${t}(): ${r} {
313
313
  return ${e};
314
314
  }
315
- `}),z=e=>{if(e.length===0)return{constant:"",override:""};const r={workflows:e.map(t=>({className:t.className,exportName:t.exportName,name:t.name}))};return h("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",r,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Z=e=>{if(e.length===0)return{constant:"",override:""};const r={queues:e.map(t=>({binding:t.bindingName,...t.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:t.tuning.deadLetterQueue},exportName:t.exportName,mode:t.mode,name:t.name,...t.topic===void 0?{}:{topic:t.topic}}))};return h("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",r,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},ee=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
316
- const payments: LunoraPayment = config.payment
317
- ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
318
- : paymentStub;
315
+ `}),Z=e=>{if(e.length===0)return{constant:"",override:""};const r={workflows:e.map(t=>({className:t.className,exportName:t.exportName,name:t.name}))};return h("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",r,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},ee=e=>{if(e.length===0)return{constant:"",override:""};const r={queues:e.map(t=>({binding:t.bindingName,...t.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:t.tuning.deadLetterQueue},exportName:t.exportName,mode:t.mode,name:t.name,...t.topic===void 0?{}:{topic:t.topic}}))};return h("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",r,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},_=["attach","cancelPayment","cancelSubscription","capturePayment","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","refundPayment","track"],te=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
316
+ let payments: LunoraPayment | undefined;
319
317
  `,configField:`
320
318
  payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
321
- payments,`,stub:g("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},te=(e,r,t,n,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{T as a,D as b,B as c,J as d,U as e,V as f,Y as g,Q as h,H as i,X as j,ee as k,z as l,Z as m,I as n,te as o,W as p,q,g as r,K as s,j as t,M as u,G as v};
319
+ get payments(): LunoraPayment {
320
+ payments ??= config.payment
321
+ ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
322
+ : paymentStub;
323
+
324
+ return payments;
325
+ },`,stub:g("paymentStub: LunoraPayment","ctx.payments: no payment configured. Pass `payment` to createShardDO().",_,{cast:" as unknown as LunoraPayment",sync:!0})}:{build:"",configField:"",contextField:"",imports:[],stub:""},ne=(e,r,t,n,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...n?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...t?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...r?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{q as a,U as b,D as c,V as d,j as e,Y as f,X as g,M as h,J as i,z as j,te as k,Z as l,ee as m,W as n,ne as o,I as p,B as q,g as r,G as s,Q as t,K as u,H as v};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.268",
3
+ "version": "1.0.0-alpha.269",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,8 +46,8 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.192",
50
- "@lunora/agent": "1.0.0-alpha.181",
49
+ "@lunora/advisor": "1.0.0-alpha.193",
50
+ "@lunora/agent": "1.0.0-alpha.182",
51
51
  "@lunora/container": "1.0.0-alpha.69",
52
52
  "@lunora/errors": "1.0.0-alpha.50",
53
53
  "@lunora/platform": "1.0.0-alpha.56",
@@ -1 +0,0 @@
1
- import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as R}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as F}from"node:module";import{join as C}from"node:path";import{findObjectProperty as u}from"./isTestPath-Djd59sWZ.mjs";import{r as B,p as V}from"./parse-validator-DLAJeWE4.mjs";import{R as q}from"./reserved-words-CW1QFbTd.mjs";import{a as I}from"./project-config-file-CD247zmH.mjs";const J=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,U=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},K=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:K(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=U(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},Z=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",G=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},W=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return G(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:Z(e.shardMode),vectorIndexes:[]}},X=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>W(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},H=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},Q=e=>{const t=H(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},Y=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ee=(e,t)=>{const n=Q(e);if(n)try{const s=F(C(t,"noop.cjs")),r=s.resolve(n.moduleSpecifier),o=s(r),a=Y(o,n);return typeof a!="object"||a===null?void 0:X(a)}catch{return}},te=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},L=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},O=e=>e&&te.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ne=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},A=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},re=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,se=/^(?:sqlite_|_cf_|__)/u,ie=/__(?:agg|rank|geo|fts)_/u,oe=e=>se.test(e)||ie.test(e),ae=new Set(["cascade","restrict","set null"]),le=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),N=/^[A-Za-z_$][\w$]*$/u,S=(e,t)=>{if(le.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(q.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!N.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(oe(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ce=e=>e&&ae.has(e)?e:void 0,de=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},fe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?ce(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ue=e=>{const t=de(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=fe(s);r&&n.push(r)}return n},pe=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ge=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},me=e=>{const[t,n,s]=e,r=ge(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)pe(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},be=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=L(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},xe=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},he=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},ye=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},ve=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ye(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Ee=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:O(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Ie=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},Se=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},ke=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:ne(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},we=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(xe(n));break}case"global":{e.shardMode="global",e.globalBackend=Ie(n);break}case"index":{e.indexes.push(me(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ve(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ue(r));break}case"searchIndex":{e.searchIndexes.push(be(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:Se(n[0])};break}case"source":{e.externalSource=ke(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=he(n);break}case"vectorize":{const r=Ee(n,s);r&&e.vectorIndexes.push(r);break}}},_=["__vocab","_config","_content","_data","_docsize","_idx"],Te=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of _){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${_.join(", ")}.`)}},_e=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,re(t))},P=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))we(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Te(e,t,n.searchIndexes),_e(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=B(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(S(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(P(o,a))}}return t},Le=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Oe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:O(f(s,"metric")),name:o,table:Le(s)}},$=e=>{const t=[];for(const n of e.getProperties()){const s=Oe(n);s&&t.push(s)}return t},k=(e,t)=>`${e}_${t}`,Ae=(e,t)=>{if(!N.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?k(t,e):e,Ne=(e,t,n,s)=>{const r=k(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},Pe=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},je=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},$e=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ze=(e,t)=>{const n=Pe(e);if(n){if(i.isPropertyAccessExpression(t)){const s=De(n);return s?b(s,t.getName()):void 0}return n}},Me=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,je(t))return t;const s=$e(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ze(a,t)}},Re=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Fe=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);S(a,r.getNameNode()),s.push(P(o,a))}return s},Ce=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:$(n)},D=(e,t,n,s,r)=>{Ae(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>Ne(c,e,o,r)),l=n.map(c=>({...c,name:k(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},Be=(e,t,n)=>D(e,Fe(n),Ce(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ve=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Me(n);if(!s){if(t!==void 0){const o=ee(n,t);if(o){for(const a of o.bareTables)S(a.name,n);return D(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Re(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Be(r.key,r.keyNode,r.options)},qe=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Je=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of qe(e)){const a=Ve(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Ue=new Set(["eu","fedramp","us"]),Ke=e=>A(e,"jurisdiction","jurisdiction",Ue,'"eu", "us", or "fedramp"'),Ze=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&L(r,"pinAuth")===!0}t=s}},Ge=new Set(["required"]),We=e=>A(e,"rls","rls mode",Ge,'"required"'),it=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(R.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Je(r,a,n),w=[...a.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=w.find(p=>z.has(p.table));if(v)throw d(r,J(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:a,vectorIndexes:w}};export{it as default};