@lunora/codegen 1.0.0-alpha.401 → 1.0.0-alpha.402

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.
Files changed (65) hide show
  1. package/dist/index.d.mts +86 -1
  2. package/dist/index.d.ts +86 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{AGENTS_FILENAME-Cli3X44r.mjs → AGENTS_FILENAME-BiSJTXnu.mjs} +1 -1
  5. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-D1SaOfnm.mjs → ALL_NOTIFY_CHANNELS-_xAn-jI3.mjs} +1 -1
  6. package/dist/packem_shared/{CONTAINERS_FILENAME-BX1_ALLp.mjs → CONTAINERS_FILENAME-Bj3hFBa-.mjs} +1 -1
  7. package/dist/packem_shared/DEFAULT_TARGET-BfJ7upI0.mjs +1 -0
  8. package/dist/packem_shared/{FLAGS_FILENAME-DY3yo1u_.mjs → FLAGS_FILENAME-BW7MzS9C.mjs} +1 -1
  9. package/dist/packem_shared/{MUTATORS_FILENAME-Ck_l1lz7.mjs → MUTATORS_FILENAME-tPpN_a00.mjs} +1 -1
  10. package/dist/packem_shared/{OPENRPC_VERSION-CCp_wKFT.mjs → OPENRPC_VERSION-DI_G2H0Q.mjs} +1 -1
  11. package/dist/packem_shared/{QUEUES_FILENAME-C5xotY-M.mjs → QUEUES_FILENAME-Cpp-0QI9.mjs} +1 -1
  12. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-BIELlQsc.mjs → SCHEMA_SNAPSHOT_FILENAME-CoCuKo3b.mjs} +11 -11
  13. package/dist/packem_shared/{SHAPES_FILENAME-DCtGHMEm.mjs → SHAPES_FILENAME-cHL4n_Co.mjs} +1 -1
  14. package/dist/packem_shared/{WORKFLOWS_FILENAME-CyV1HQaP.mjs → WORKFLOWS_FILENAME-BXjKKAmj.mjs} +1 -1
  15. package/dist/packem_shared/{attribution-DjweYNgJ.mjs → attribution-C6VQNs-V.mjs} +1 -1
  16. package/dist/packem_shared/{buildOpenApiDocument-B1PEHSSc.mjs → buildOpenApiDocument-aAAsKnsY.mjs} +1 -1
  17. package/dist/packem_shared/{capabilitiesUsedBy-SSrieNZ1.mjs → capabilitiesUsedBy-t-UvdnZl.mjs} +1 -1
  18. package/dist/packem_shared/chain-BvRxehwv.mjs +1 -0
  19. package/dist/packem_shared/{classify-procedure-call-BuF5PNwV.mjs → classify-procedure-call-DwWrpCoX.mjs} +1 -1
  20. package/dist/packem_shared/companionServiceBinding-CnEUhH0Z.mjs +1 -0
  21. package/dist/packem_shared/{context-property-calls-BcUYQ6ph.mjs → context-property-calls-RsCkfFCU.mjs} +1 -1
  22. package/dist/packem_shared/{context-root-2wag3akK.mjs → context-root-CY5kkBER.mjs} +1 -1
  23. package/dist/packem_shared/{createCodegenProject-C8N4Zm8h.mjs → createCodegenProject-BC4GwdnG.mjs} +1 -1
  24. package/dist/packem_shared/{database-calls-B_85LJIk.mjs → database-calls-HP2mxQAR.mjs} +1 -1
  25. package/dist/packem_shared/{discoverAuthApiCalls-f8_WRQEA.mjs → discoverAuthApiCalls-CHytF_NH.mjs} +1 -1
  26. package/dist/packem_shared/{discoverCrons-DTqSuSDh.mjs → discoverCrons-C6Y1u_kI.mjs} +1 -1
  27. package/dist/packem_shared/discoverFunctions-B-051l15.mjs +1 -0
  28. package/dist/packem_shared/{discoverHttpRoutes-2gxHuLgt.mjs → discoverHttpRoutes-BccPlGZb.mjs} +1 -1
  29. package/dist/packem_shared/discoverHyperdriveCalls-DmUuhUoL.mjs +1 -0
  30. package/dist/packem_shared/{discoverInserts-CLh70kVu.mjs → discoverInserts-z7jg8LD3.mjs} +1 -1
  31. package/dist/packem_shared/discoverMaskProcedures-CrkT80jO.mjs +1 -0
  32. package/dist/packem_shared/{discoverMigrations-e5_NQdf-.mjs → discoverMigrations-B6u2Do9_.mjs} +1 -1
  33. package/dist/packem_shared/{discoverNondeterministicCalls-CrXAegUc.mjs → discoverNondeterministicCalls-Dei7EUFX.mjs} +1 -1
  34. package/dist/packem_shared/{discoverQueries-T8b_7ZZ-.mjs → discoverQueries-D4mihML_.mjs} +1 -1
  35. package/dist/packem_shared/discoverR2sqlCalls-Ej8oRuVk.mjs +1 -0
  36. package/dist/packem_shared/{discoverRlsMetadata-CnVvP2Ps.mjs → discoverRlsMetadata-CNn4cdfy.mjs} +1 -1
  37. package/dist/packem_shared/{discoverRlsProcedures-DttY0Jld.mjs → discoverRlsProcedures-CsczAow2.mjs} +1 -1
  38. package/dist/packem_shared/{discoverSandboxUsage-X0SECo-x.mjs → discoverSandboxUsage-EKZOCCPU.mjs} +1 -1
  39. package/dist/packem_shared/discoverSchema-BcyKCBIw.mjs +1 -0
  40. package/dist/packem_shared/{discoverStorageRulesMetadata-t_oMSn0L.mjs → discoverStorageRulesMetadata-yCB6MdrA.mjs} +1 -1
  41. package/dist/packem_shared/{emitApp-BrOgH7YU.mjs → emitApp-C3IUdkkt.mjs} +37 -28
  42. package/dist/packem_shared/{exported-procedure-chains-BaxQ8C-S.mjs → exported-procedure-chains-DiNvW1Wl.mjs} +1 -1
  43. package/dist/packem_shared/{fingerprintSchemaSources-PmhepCVj.mjs → fingerprintSchemaSources-Cpom_87X.mjs} +1 -1
  44. package/dist/packem_shared/{handler-reference-D2EE2q-4.mjs → handler-reference-BqSXtjJ6.mjs} +1 -1
  45. package/dist/packem_shared/index-BPg6e1oa.mjs +1 -0
  46. package/dist/packem_shared/{index-Dd6T5nSP.mjs → index-DgHhQfpm.mjs} +1 -1
  47. package/dist/packem_shared/{ip-reads-WFubgB1G.mjs → ip-reads-Bn9qvrMD.mjs} +1 -1
  48. package/dist/packem_shared/isTestPath-B357_sbh.mjs +1 -0
  49. package/dist/packem_shared/loadProjectConfig-D4_s2UFp.mjs +1 -0
  50. package/dist/packem_shared/{modules-DE0ksIeR.mjs → modules-BgublqiK.mjs} +1 -1
  51. package/dist/packem_shared/project-config-file-DBVmBpin.mjs +1 -0
  52. package/dist/packem_shared/{unwrap-handler-return-BpigsVD6.mjs → unwrap-handler-return-zNStZJ4K.mjs} +1 -1
  53. package/package.json +1 -1
  54. package/dist/packem_shared/DEFAULT_TARGET-C-gcdslJ.mjs +0 -1
  55. package/dist/packem_shared/chain-DWwd9wXd.mjs +0 -1
  56. package/dist/packem_shared/companionServiceBinding-ChINWo8k.mjs +0 -1
  57. package/dist/packem_shared/discoverFunctions-D4GIaVIP.mjs +0 -1
  58. package/dist/packem_shared/discoverHyperdriveCalls-DaJLewG0.mjs +0 -1
  59. package/dist/packem_shared/discoverMaskProcedures-C0VcUGpb.mjs +0 -1
  60. package/dist/packem_shared/discoverR2sqlCalls-CY0xmIWX.mjs +0 -1
  61. package/dist/packem_shared/discoverSchema-DDvMQheA.mjs +0 -1
  62. package/dist/packem_shared/index-fVYBrxkP.mjs +0 -1
  63. package/dist/packem_shared/isTestPath-ClgKgMYM.mjs +0 -1
  64. package/dist/packem_shared/loadProjectConfig-CtcJHHKS.mjs +0 -1
  65. package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{existsSync as M,readFileSync as Je,mkdirSync as Gt,writeFileSync as Cr,rmSync as pe,readdirSync as Yt}from"node:fs";import{dirname as Ze,join as v,relative as Qt}from"node:path";import{performance as At}from"node:perf_hooks";import{runAdvisor as Or}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{serializeSchemaSnapshot as kr}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Rr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Xt,ts as Fr,VariableDeclarationKind as Jt}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as I,descendantsOfKind as E,bindingKeyName as ge,collectCallRows as O,findObjectProperty as q,collectSecurityCallRows as Lr,propertyInitializer as F,listSecurityScanFiles as et,objectLiteralFromCallbackBody as _n,limitNameOf as zn,optionsObjectLiteral as $n,handlerOf as Dr,collectNodeRows as ae,chainRootOf as tt,outermostValueWrapper as C,isWriteTarget as st,isSameNode as N,unwrapExpression as h,isConstDeclaration as ce,memberAccessOf as Zt,returningFunctionOf as Ft,walkChain as Mr,RUN_METHODS as Kn,functionReferenceSegments as _r,isTestPath as zr,isFunctionLike as le,functionKeyOf as Bn,withSourceListMemo as $r}from"./isTestPath-ClgKgMYM.mjs";import{j as Z,h as Y,d as D,b as es,c as S,a as nt,w as ts,k as Kr,l as Br,f as Vr,m as Ur,g as Lt,i as Wr}from"./attribution-DjweYNgJ.mjs";import{b as Vs,r as bt,a as X,e as qr,m as Vn,c as it,f as ss,E as Un,C as Wn,d as jr,g as Hr,i as Gr}from"./context-root-2wag3akK.mjs";import{a as T,i as qn,c as ie,d as jn,e as Yr,f as Qr,g as Hn}from"./classify-procedure-call-BuF5PNwV.mjs";import{a as y,s as Xr}from"./property-name-7cBlgK_O.mjs";import{b as Jr,a as rt}from"./module-specifiers-BctA0m_p.mjs";import{r as ot,s as Zr}from"./parse-validator-BisfC8bR.mjs";import eo from"./discoverAuthApiCalls-f8_WRQEA.mjs";import{i as $,r as Gn}from"./database-calls-B_85LJIk.mjs";import{i as Dt,p as Yn,w as to,d as so}from"./index-fVYBrxkP.mjs";import no from"./discoverHyperdriveCalls-DaJLewG0.mjs";import{diagnosticAt as de}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ns,a as qe,s as Qn,d as io}from"./index-Dd6T5nSP.mjs";import{MUTATORS_FILENAME as ro,isDefineMutatorCallee as oo,mutatorServerImplOf as ao,discoverMutators as co}from"./MUTATORS_FILENAME-Ck_l1lz7.mjs";import lo from"./discoverNondeterministicCalls-CrXAegUc.mjs";import{discoverNotifyConfig as uo,discoverNotifyCalls as fo}from"./ALL_NOTIFY_CHANNELS-D1SaOfnm.mjs";import po from"./discoverR2sqlCalls-CY0xmIWX.mjs";import go from"./discoverRlsProcedures-DttY0Jld.mjs";import{s as is,n as mo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as ho,redact as vo,isHeuristicSecretKind as Eo,isSecretishName as xo}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Xn,readProjectLazyFunctions as So,readProjectStudioCompanion as yo,readMergeDurableObjects as Ao}from"./loadProjectConfig-CtcJHHKS.mjs";import{a as Me,d as bo,r as No}from"./modules-DE0ksIeR.mjs";import{WORKFLOWS_FILENAME as Po,discoverWorkflows as wo}from"./WORKFLOWS_FILENAME-CyV1HQaP.mjs";import{r as Io}from"./json-data-Chfs2Cz5.mjs";import{a as To,I as Co,g as Oo,G as Jn,d as ko,i as Ro}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as Fo}from"./createCodegenProject-C8N4Zm8h.mjs";import{findTsconfig as cx,refreshCodegenProject as lx,tsconfigFingerprint as dx}from"./createCodegenProject-C8N4Zm8h.mjs";import{wranglerString as Lo,wranglerValue as Do,companionName as Mo,COMPANION_FILES as _o}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as zo,usedCapabilities as $o}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Zn,isHyperdriveGlobalTable as ei}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Ko}from"./AGENTS_FILENAME-Cli3X44r.mjs";import{discoverContainers as Bo}from"./CONTAINERS_FILENAME-BX1_ALLp.mjs";import Vo from"./discoverCrons-DTqSuSDh.mjs";import{contextPropertiesRead as Uo,createTargetScope as Wo,fileWiresRequestSecretTool as qo,discoverFeatureUsage as jo}from"./capabilitiesUsedBy-SSrieNZ1.mjs";import ti from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Ho,findProjectConfigFile as Go}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Yo}from"./QUEUES_FILENAME-C5xotY-M.mjs";import{discoverSandboxUsage as Qo}from"./discoverSandboxUsage-X0SECo-x.mjs";import{resolveServiceBindings as Xo}from"./companionServiceBinding-ChINWo8k.mjs";import Jo from"./discoverStorageRulesMetadata-t_oMSn0L.mjs";import{resolveCodegenTarget as _e,gatePlatformFeatures as Zo,readTargetDiagnostics as ea,vectorizeDimensionDiagnostics as ta,liveStreamsDeliveryAuthorizationDiagnostic as sa,socketRoutesDeliveryAuthorizationDiagnostic as na,studioPlatformFor as ia,platformFeatureAvailable as ra,gateAdminTokenRevocation as oa}from"./DEFAULT_TARGET-C-gcdslJ.mjs";import{i as aa}from"./schema-BgM8A3XV.mjs";import{b as si,e as ca}from"./shard-Csztu3jG.mjs";import{e as la,a as da}from"./server-CRFaUMKQ.mjs";import{emitDataModel as ua}from"./emitDataModel-BvCZS4Yq.mjs";import{i as fa,b as pa,e as ga,d as ma,f as ha,c as va}from"./unwrap-handler-return-BpigsVD6.mjs";import Ea from"./discoverHttpRoutes-2gxHuLgt.mjs";import xa from"./discoverInserts-CLh70kVu.mjs";import{e as ni}from"./exported-procedure-chains-BaxQ8C-S.mjs";import Sa from"./discoverMigrations-e5_NQdf-.mjs";import Us from"./discoverQueries-T8b_7ZZ-.mjs";import ya from"./discoverRlsMetadata-CnVvP2Ps.mjs";import Aa from"./discoverSchema-DDvMQheA.mjs";import{discoverShapes as ba}from"./SHAPES_FILENAME-DCtGHMEm.mjs";import{i as Na}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as Pa,emitApp as wa}from"./emitApp-BrOgH7YU.mjs";import{readJsonSync as Ia}from"@visulima/fs";import{indexReferencesOf as Ta,buildSchemaSnapshot as Ca}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as Oa,emitOpenApiModule as ka}from"./buildOpenApiDocument-B1PEHSSc.mjs";import{buildOpenRpcDocument as Ra,emitOpenRpcModule as Fa}from"./OPENRPC_VERSION-CCp_wKFT.mjs";import{w as La,u as Da,v as Ma,t as _a,x as za}from"./shard-runtime-D0xuE0pX.mjs";import{emitCollections as $a,emitSeed as Ka,emitApi as Ba,emitInternalApi as Va}from"./emitApi-lwadq5G7.mjs";import{emitCrons as Ua,emitScheduler as Wa,emitAdminRevocations as qa,emitShardRegistry as ja,emitDurableObjects as Ha,emitVectors as Ga,emitWranglerCronTriggers as Ya}from"./emitCrons-CCRKs482.mjs";import Qa from"./emitDrizzleSchema-BzOChEYW.mjs";import{LAZY_FUNCTION_DIRECTORY as ii,emitFunctions as Xa,emitLazyFunctionModules as Ja}from"./emitFunctions-ppMX7E3X.mjs";const Za=(e,t=!1)=>{if(e.length===0)return"";const s=ko(t),n=e.map(c=>{if(To(c.exportName,"live stream export name"),!Co.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{Oo(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,p=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${p} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const x=u.fields.map(_=>`\${encodeURIComponent(key.${_})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${p} => ({
1
+ import{existsSync as M,readFileSync as Je,mkdirSync as Gt,writeFileSync as Cr,rmSync as pe,readdirSync as Yt}from"node:fs";import{dirname as Ze,join as v,relative as Qt}from"node:path";import{performance as At}from"node:perf_hooks";import{runAdvisor as Or}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{serializeSchemaSnapshot as kr}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Rr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Xt,ts as Fr,VariableDeclarationKind as Jt}from"ts-morph";import{listLunoraSourceFiles as A,lunoraRelativePath as I,descendantsOfKind as E,bindingKeyName as ge,collectCallRows as O,findObjectProperty as q,collectSecurityCallRows as Lr,propertyInitializer as F,listSecurityScanFiles as et,objectLiteralFromCallbackBody as _n,limitNameOf as zn,optionsObjectLiteral as $n,handlerOf as Dr,collectNodeRows as ae,chainRootOf as tt,outermostValueWrapper as C,isWriteTarget as st,isSameNode as N,unwrapExpression as h,isConstDeclaration as ce,memberAccessOf as Zt,returningFunctionOf as Ft,walkChain as Mr,RUN_METHODS as Kn,functionReferenceSegments as _r,isTestPath as zr,isFunctionLike as le,functionKeyOf as Bn,withSourceListMemo as $r}from"./isTestPath-B357_sbh.mjs";import{j as Z,h as Y,d as D,b as es,c as S,a as nt,w as ts,k as Kr,l as Br,f as Vr,m as Ur,g as Lt,i as Wr}from"./attribution-C6VQNs-V.mjs";import{b as Vs,r as bt,a as X,e as qr,m as Vn,c as it,f as ss,E as Un,C as Wn,d as jr,g as Hr,i as Gr}from"./context-root-CY5kkBER.mjs";import{a as T,i as qn,c as ie,d as jn,e as Yr,f as Qr,g as Hn}from"./classify-procedure-call-DwWrpCoX.mjs";import{a as y,s as Xr}from"./property-name-7cBlgK_O.mjs";import{b as Jr,a as rt}from"./module-specifiers-BctA0m_p.mjs";import{r as ot,s as Zr}from"./parse-validator-BisfC8bR.mjs";import eo from"./discoverAuthApiCalls-CHytF_NH.mjs";import{i as $,r as Gn}from"./database-calls-HP2mxQAR.mjs";import{i as Dt,p as Yn,w as to,d as so}from"./index-BPg6e1oa.mjs";import no from"./discoverHyperdriveCalls-DmUuhUoL.mjs";import{diagnosticAt as de}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ns,a as qe,s as Qn,d as io}from"./index-DgHhQfpm.mjs";import{MUTATORS_FILENAME as ro,isDefineMutatorCallee as oo,mutatorServerImplOf as ao,discoverMutators as co}from"./MUTATORS_FILENAME-tPpN_a00.mjs";import lo from"./discoverNondeterministicCalls-Dei7EUFX.mjs";import{discoverNotifyConfig as uo,discoverNotifyCalls as fo}from"./ALL_NOTIFY_CHANNELS-_xAn-jI3.mjs";import po from"./discoverR2sqlCalls-Ej8oRuVk.mjs";import go from"./discoverRlsProcedures-CsczAow2.mjs";import{s as is,n as mo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as ho,redact as vo,isHeuristicSecretKind as Eo,isSecretishName as xo}from"./redact-Cy14LEnc.mjs";import{r as Xn,c as So,a as yo,e as Ao,d as bo}from"./project-config-file-DBVmBpin.mjs";import{a as Me,d as No,r as Po}from"./modules-BgublqiK.mjs";import{WORKFLOWS_FILENAME as wo,discoverWorkflows as Io}from"./WORKFLOWS_FILENAME-BXjKKAmj.mjs";import{r as To}from"./json-data-Chfs2Cz5.mjs";import{a as Co,I as Oo,g as ko,G as Jn,d as Ro,i as Fo}from"./shared-Cn7dMQ_u.mjs";import{createCodegenProject as Lo}from"./createCodegenProject-BC4GwdnG.mjs";import{findTsconfig as lx,refreshCodegenProject as dx,tsconfigFingerprint as ux}from"./createCodegenProject-BC4GwdnG.mjs";import{wranglerString as Do,wranglerValue as Mo,companionName as _o,COMPANION_FILES as zo}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{CAPABILITIES as $o,usedCapabilities as Ko}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Zn,isHyperdriveGlobalTable as ei}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Bo}from"./AGENTS_FILENAME-BiSJTXnu.mjs";import{discoverContainers as Vo}from"./CONTAINERS_FILENAME-Bj3hFBa-.mjs";import Uo from"./discoverCrons-C6Y1u_kI.mjs";import{contextPropertiesRead as Wo,createTargetScope as qo,fileWiresRequestSecretTool as jo,discoverFeatureUsage as Ho}from"./capabilitiesUsedBy-t-UvdnZl.mjs";import ti from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as Go,findProjectConfigFile as Yo}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Qo}from"./QUEUES_FILENAME-Cpp-0QI9.mjs";import{discoverSandboxUsage as Xo}from"./discoverSandboxUsage-EKZOCCPU.mjs";import{resolveServiceBindings as Jo}from"./companionServiceBinding-CnEUhH0Z.mjs";import Zo from"./discoverStorageRulesMetadata-yCB6MdrA.mjs";import{resolveCodegenTarget as _e,gatePlatformFeatures as ea,readTargetDiagnostics as ta,vectorizeDimensionDiagnostics as sa,liveStreamsDeliveryAuthorizationDiagnostic as na,socketRoutesDeliveryAuthorizationDiagnostic as ia,studioPlatformFor as ra,platformFeatureAvailable as oa,gateAdminTokenRevocation as aa}from"./DEFAULT_TARGET-BfJ7upI0.mjs";import{i as ca}from"./schema-BgM8A3XV.mjs";import{b as si,e as la}from"./shard-Csztu3jG.mjs";import{e as da,a as ua}from"./server-CRFaUMKQ.mjs";import{emitDataModel as fa}from"./emitDataModel-BvCZS4Yq.mjs";import{i as pa,b as ga,e as ma,d as ha,f as va,c as Ea}from"./unwrap-handler-return-zNStZJ4K.mjs";import xa from"./discoverHttpRoutes-BccPlGZb.mjs";import Sa from"./discoverInserts-z7jg8LD3.mjs";import{e as ni}from"./exported-procedure-chains-DiNvW1Wl.mjs";import ya from"./discoverMigrations-B6u2Do9_.mjs";import Us from"./discoverQueries-D4mihML_.mjs";import Aa from"./discoverRlsMetadata-CNn4cdfy.mjs";import ba from"./discoverSchema-BcyKCBIw.mjs";import{discoverShapes as Na}from"./SHAPES_FILENAME-cHL4n_Co.mjs";import{i as Pa}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as wa,emitApp as Ia}from"./emitApp-C3IUdkkt.mjs";import{readJsonSync as Ta}from"@visulima/fs";import{indexReferencesOf as Ca,buildSchemaSnapshot as Oa}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as ka,emitOpenApiModule as Ra}from"./buildOpenApiDocument-aAAsKnsY.mjs";import{buildOpenRpcDocument as Fa,emitOpenRpcModule as La}from"./OPENRPC_VERSION-DI_G2H0Q.mjs";import{w as Da,u as Ma,v as _a,t as za,x as $a}from"./shard-runtime-D0xuE0pX.mjs";import{emitCollections as Ka,emitSeed as Ba,emitApi as Va,emitInternalApi as Ua}from"./emitApi-lwadq5G7.mjs";import{emitCrons as Wa,emitScheduler as qa,emitAdminRevocations as ja,emitShardRegistry as Ha,emitDurableObjects as Ga,emitVectors as Ya,emitWranglerCronTriggers as Qa}from"./emitCrons-CCRKs482.mjs";import Xa from"./emitDrizzleSchema-BzOChEYW.mjs";import{LAZY_FUNCTION_DIRECTORY as ii,emitFunctions as Ja,emitLazyFunctionModules as Za}from"./emitFunctions-ppMX7E3X.mjs";const ec=(e,t=!1)=>{if(e.length===0)return"";const s=Ro(t),n=e.map(c=>{if(Co(c.exportName,"live stream export name"),!Oo.test(c.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(c.filePath)}`);return`import type { ${c.exportName} as ${c.exportName}Stream } from "../${c.filePath}.js";`}),i=e.map(c=>{const l=c.topics.map(u=>{ko(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,p=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${p} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const x=u.fields.map(_=>`\${encodeURIComponent(key.${_})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${p} => ({
2
2
  __lunoraLive: ${m},
3
3
  topic: \`${u.name}:${x}\`,
4
4
  }),`});return` ${c.exportName}: {
@@ -18,15 +18,15 @@ export const live = {
18
18
  ${i.join(`
19
19
  `)}
20
20
  };
21
- `},ri=new Set(["delete","get","head","options","patch","post","put"]),ec=new Set(["handler","stream"]),tc=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ws=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),sc=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ri.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},nc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||ri.has(n.getName()))break;s=n.getExpression()}return sc(s)},ic=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Ws.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Ws.has(s.getText()))return!0}return!1},rc=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!ec.has(n.getName()))return;const i=nc(s);if(!i||!tc.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&ic(o);return{exportName:Y(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},oc=(e,t)=>{const s=[];for(const n of Z(e)){const i=rc(n,t);i&&s.push(i)}return s},ac=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...oc(i,I(t,n)))}return s},cc=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},lc=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?ge(t):void 0}},dc=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Vs(a)}))return!1;const n=D(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Vs(i)},qs=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=cc(e);return n!==void 0&&lc(n)===t?!0:t==="args"&&dc(e)},oi=(e,t)=>r.isIdentifier(e)?qs(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>qs(s,t)),uc=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},js=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!es(t)?t.getInitializer():void 0},Mt=e=>oi(e,"args"),J=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of E(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},G=e=>{if(Mt(e))return!0;const t=J(e);return t!==void 0&&Mt(t)},fc=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=J(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},me=e=>{if(bt(e))return!0;const t=js(e);if(t!==void 0&&bt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=js(i);return o!==void 0&&bt(o)})},ze=(e,t)=>oi(e,t),pc=(e,t)=>{if(ze(e,t))return!0;const s=J(e);if(s!==void 0&&ze(s,t))return!0;const n=uc(e);if(n!==void 0){const i=J(n);return i!==void 0&&ze(i,t)}return!1},gc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:X(e.getExpression(),["ai"]),mc=(e,t)=>{if(!gc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)||me(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},hc=(e,t)=>O(e,t,mc),vc=new Set(["generateText","streamText"]),Ec=new Set(["messages","prompt","system"]),xc=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Sc=(e,t)=>xc.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),yc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[qr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&Sc(i,s));return n===void 0?void 0:`${n}.${s}`},Ac=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=yc(t);if(s!==void 0)return s}},bc=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=ge(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Nc=e=>{if(Mt(e))return!0;const t=bc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},Pc=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!Ec.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&Nc(s))return!0}return!1},wc=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=T(n.getExpression());if(i===void 0||!vc.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(T(c.getExpression())==="tool"&&(a=Ac(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Pc(o)})}return s},Ic=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wc(i,I(t,n)))}return s},Tc=e=>X(e,["fetch"]),Cc=(e,t)=>{if(!Tc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Oc=(e,t)=>O(e,t,Cc),rs=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=ot(s.getExpression());return n===void 0||rs(n,t)})}finally{t.delete(e)}},kc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=q(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:ot(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:rs(i)}},Rc=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?ot(o):void 0;a===void 0?s=!0:(t.push(a),s||=rs(a))}n=i.getExpression()}return{objects:t,opaque:s}},os=(e,t)=>t?Rc(t):kc(e),ai=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=ot(s.getExpression());return n===void 0?[]:ai(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Fc=e=>e.flatMap(t=>ai(t,new Set)),Lc=new Set(["check","length","max"]),_t=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(Lc.has(s.getName()))return!0;t=n}},zt=e=>Jr(e)||e==="@lunora/values",Dc=e=>{const t=new Set(["v"]);for(const s of qn(e,"v",zt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&zt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Mc=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},_c=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),zc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&zt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),as=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return _c(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&zc(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},$c=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},Kc=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Bc=e=>r.isReturnStatement(e)?e.getExpression():void 0,Vc=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Kc(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Bc(t);return s?[s]:[]}),ci=(e,t)=>{if(as(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return ci(e.getExpression(),t)},Uc=(e,t)=>{const s=$c(e.getExpression(),e.getSourceFile());if(!s)return[];const n=_t(e),i=new Set(Vc(s).map(o=>ci(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=as(o,t);return a===void 0?[]:[{bounded:_t(o)||n&&i.has(o),factory:a}]})},Wc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=as(s,t),i=n===void 0?[]:[{bounded:_t(s),factory:n}];return r.isCallExpression(s)?[...i,...Uc(s,t)]:i}),qc=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=Wc(a,t),l=y(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},jc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ie(n);if(i?.visibility!=="public")return;const{objects:o}=os(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=qc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:Y(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Hc=(e,t)=>{const s=[],n=Dc(e),i={destructured:Mc(e,n),namespaces:n};for(const o of Z(e)){const a=jc(o,t,i);a&&s.push(a)}return s},Gc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hc(i,I(t,n)))}return s},Nt=e=>e?.getKind()===d.TrueKeyword,Yc=e=>e?.getKind()===d.FalseKeyword,Qc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Xc=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Jc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&T(t.getExpression())==="scim"),Zc=e=>e!==void 0&&r.isCallExpression(e)&&Xc.has(T(e.getExpression())??""),el=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),tl=e=>{const t=F(e,"advanced"),s=F(e,"emailAndPassword"),n=F(e,"session");return{analyzable:!0,disableCsrfCheck:Nt(F(t,"disableCSRFCheck")),emailPasswordEnabled:Nt(F(s,"enabled")),requireEmailVerification:Nt(F(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Jc(F(e,"plugins"))&&Zc(F(e,"database")),secureCookiesDisabled:Yc(F(t,"useSecureCookies")),sessionFreshAgeZero:Qc(F(n,"freshAge")),trustedOriginsWildcard:el(F(e,"trustedOrigins"))}},sl=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),nl=(e,t)=>{if(T(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?tl(s):sl();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},il=(e,t)=>Lr(e,t,nl),rl=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Vn(e.getExpression(),t.matchReceiver)?s:void 0},ol=(e,t,s)=>{const n=rl(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!G(i)||me(i))&&!(s.requireUnmodifiedReach===!0&&!fc(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},at=(e,t,s)=>O(e,t,(n,i)=>ol(n,i,s)),al=new Set(["content","pdf","scrape","screenshot"]),cl=(e,t)=>at(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:al}),ll=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),dl=new Set(["RateLimiter"]),ul=new Set(["extend"]),Hs="lunora",fl=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],li=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},$t=e=>e&&r.isObjectLiteralExpression(e)?li(e):{analyzable:!1,presentKeys:[],trueKeys:[]},pl=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&_n(t.getBody());return s?li(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},gl=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=T(n.getExpression());i!==void 0&&(ll.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...$t(n.getArguments()[0])}):ul.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...pl(n.getArguments()[0])}))}for(const n of E(e,d.NewExpression)){const i=T(n.getExpression());i===void 0||!dl.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...$t(n.getArguments()[0])})}return s},ml=e=>{for(const t of fl){const s=v(e,t);if(!M(s))continue;const n=new Xt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Je(s,"utf8")),i=[];for(const o of E(n,d.CallExpression))T(o.getExpression())===Hs&&i.push({callee:Hs,file:t,line:o.getStartLineNumber(),...$t(o.getArguments()[0])});return i}return[]},hl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of et(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...gl(o,n))}return s.push(...ml(Ze(t))),s},Gs="ctx.containers.",vl=e=>{if(!e.startsWith(Gs))return!1;const t=e.slice(Gs.length);return t.length>0&&!t.includes(".")},El=(e,t)=>at(e,t,{argIndex:0,matchReceiver:vl,methods:new Set(["get"])}),xl=new Set(["allow","deny","setAllowed"]),Sl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=q(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},yl=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!Sl(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Al=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!xl.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},bl=(e,t)=>yl(e,t)??Al(e,t),Nl=(e,t)=>O(e,t,bl),Pl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&$(s.getExpression())?s.getName():void 0},wl=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&$(s)?1:0]},Il=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Tl=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>Il.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Cl=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return O(e,t,(i,o)=>{const a=Pl(i);if(a===void 0)return;const c=Tl(wl(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},Ol=new Set(["defineExportSink","r2Sink","webhookExportSink"]),kl=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Ol.has(s)?s:void 0},Rl=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=y(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Fl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of et(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of E(o,d.CallExpression)){const c=kl(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Rl(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},Ll=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Dl=new Set(["dbRateLimit","rateLimit"]),Ml=e=>{const t=$n(e);if(!t)return!1;const s=q(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},_l=(e,t)=>{const s=T(e.getExpression());if(s===void 0)return;const n=Ll.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:Ml(e.getArguments()[n]),file:t,limitName:Dl.has(s)?zn(e):"",line:e.getStartLineNumber()}},zl=(e,t)=>O(e,t,_l),$l=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ie(t);if(s?.kind!=="query")return;const n=Dr(t,s.receiver);return n?{exportName:Y(e)??e.getName(),handler:n}:void 0},Ys=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Kl=e=>{const t=Ys(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Ys(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Bl=(e,t)=>{const s=[];for(const n of it(e.handler,"flags"))s.push({callee:Kl(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Vl=(e,t)=>{const s=[];for(const n of Z(e)){const i=$l(n);i&&s.push(...Bl(i,t))}return s},Ul=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Vl(i,I(t,n)))}return s},Wl=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:X(e.getExpression(),["flags"]),ql=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},jl=(e,t)=>{if(!Wl(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=ql(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},Hl=(e,t)=>O(e,t,jl),Gl=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Yl=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Ql=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of E(i,d.CallExpression))Gl(a)&&s.push({file:o,indexName:Yl(a),line:a.getStartLineNumber()})}return s},Xl=new Set(["delete","get","head","options","patch","post","put"]),Jl=new Set(["handler","stream"]),Zl=new Set(["runAction","runMutation"]),ed=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Te=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,di=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(ge(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Qs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:di(s,"ctx")},Xs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:di(s,"request")},Js=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Zl.has(a)&&Te(c,t))return a;if(ed.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Te(c.getExpression(),t))return`db.${a}`}},Zs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Te(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Te(n.getInitializer(),t))){for(const o of i.getElements())if(ge(o)==="auth")return!0}}return!1},td=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,sd=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Te(n.getExpression(),t)},nd=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],ui=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:nd(s)},id=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?ui(t,a.getText()):[]}return[]},rd=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=ui(s,t.getText());return n.length>0?n:id(t,s)},en=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>sd(i,t)&&rd(i).some(o=>td.test(o)))},od=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Jl.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Xl.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},ad=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Dt(e.getArguments()[0]),l=c&&Qs(c,!0);if(!c||l===void 0||en(c,Xs(c,!0)))return;const u=Js(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Zs(c,l),sideEffect:u}}const n=od(e);if(n===void 0)return;const i=Dt(e.getArguments()[0]),o=i&&Qs(i,!1);if(!i||o===void 0||en(i,Xs(i,!1)))return;const a=Js(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Zs(i,o),sideEffect:a}},cd=(e,t)=>O(e,t,ad),ld=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),dd=new Set(["append","set"]),fi=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",tn=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>ld.has(T(n.getExpression())??"")&&ze(n,t)),ud=(e,t)=>{if(tn(e,t))return!0;const s=J(e);return s!==void 0&&tn(s,t)},Kt=(e,t)=>pc(e,t)&&!ud(e,t),fd=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=J(e);return t!==void 0&&r.isNewExpression(t)&&T(t.getExpression())==="Headers"},je=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=J(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},cs=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Kt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:fi(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Kt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=je(n.getExpression());i!==void 0&&cs(i,t,s)}},pi=(e,t)=>{const s=je(e);if(s===void 0)return;const n=q(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=je(n.getInitializer());i!==void 0&&cs(i,"response-init",t)},pd=(e,t)=>{const s=T(e.getExpression());if(s==="Response")pi(e.getArguments()[1],t);else if(s==="Headers"){const n=je(e.getArguments()[0]);n!==void 0&&cs(n,"headers-ctor",t)}},gd=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){pi(e.getArguments()[1],t);return}if(dd.has(n)&&fd(i)){const o=e.getArguments()[1];o!==void 0&&Kt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:fi(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},md=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))pd(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))gd(s,t)},hd=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Dt(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return md(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},vd=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression))s.push(...hd(n,t));return s},Ed=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vd(i,I(t,n)))}return s},gi="identity.ts",xd=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return rt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Sd=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&rt(n.getModuleSpecifierValue())}return!1},yd=e=>{if(r.isIdentifier(e))return xd(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Sd(t)}return!1},Ad=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!yd(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw de(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=nt(s,"member");a!==void 0&&t.push({exportName:a})}return t},bd=(e,t)=>{const s=v(t,gi);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Ad(n);if(i.length!==0){if(i.length>1)throw de(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Nd=new Set(["auth","context.auth"]),Pd="userId",wd=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(y(s))}return t},Id=(e,t)=>{const s=v(t,gi);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(T(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?wd(o):void 0}},sn=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Nd.has(t.getText())||X(t,["auth"])?e:void 0},Td=e=>{if(r.isPropertyAccessExpression(e)&&sn(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&sn(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},nn=(e,t,s)=>{const n=Td(e);return n===void 0?void 0:{declared:n===Pd||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},Cd=(e,t)=>{const s=Id(e,t);return s===void 0?[]:[...ae(e,t,d.PropertyAccessExpression,(n,i)=>nn(n,i,s)),...ae(e,t,d.ElementAccessExpression,(n,i)=>nn(n,i,s))]},Od=(e,t)=>{if(T(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=F(s,"key");if(!(!n||!G(n)||me(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},kd=(e,t)=>O(e,t,Od),Rd=new Set(["delete","get","getRaw","getWithMetadata","put"]),Fd=(e,t,s=[])=>{const n=at(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Rd});return ts(n,s)},Ld=new Set(["queue","send"]),rn=new Set(["bcc","cc","to"]),Dd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ld.has(t))return;const s=e.getExpression();return X(s,["mail"])||X(s,["email"])?t:void 0},Md=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return rn.has(y(t))&&G(n)&&!me(n)}if(!r.isPropertyAssignment(t)||!rn.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&G(s)&&!me(s)}):!1,_d=(e,t)=>{const s=Dd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Md(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},zd=(e,t)=>O(e,t,_d),$d=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=qe(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=qe(l);if(u===void 0)continue;const f=Qn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Kd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;return n?.receiver?ns(n.receiver).flatMap(i=>$d(i,Y(e)??e.getName(),t)):[]},Bd=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Kd(a,o))}return s},Vd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},Ud=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=q(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Wd=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return oo(s.getExpression())?s:void 0},qd=e=>{const t=Wd(e),s=t===void 0?void 0:Ud(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?Y(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Vd(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},jd=e=>e.getVariableDeclarations().flatMap(t=>qd(t)),Hd=(e,t)=>{const s=v(t,ro);if(!M(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return jd(n)},Gd=new Set(["delete","get","patch"]),Yd=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Qd=new Set(["auth","identity","session","user"]),Xd=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Jd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!$(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Zd=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},eu=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),tu=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,su=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>eu(s.getExpression(),t)&&tu(s.getThenStatement())),nu=(e,t)=>{for(const s of E(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Gd.has(i))continue;const o=n.getExpression(),a=$(o);if(!(a||r.isPropertyAccessExpression(o)&&$(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},iu=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>ss(tt(s))!==void 0)),ru=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Xd.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),ou=e=>{for(const t of E(e,d.Identifier))if(Yd.has(t.getText()))return!0;return[...Qd].some(t=>it(e,t).length>0)?!0:iu(e)||ru(e)},au=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ie(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Yn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&jn(n.receiver,"use","rls"),a=ou(i),c=new Set,l=[];for(const u of E(i,d.CallExpression)){const f=Jd(u);if(f===void 0)continue;const p=Zd(u);if(p===void 0||c.has(p)||!su(i,p))continue;const m=nu(i,p);m!==void 0&&(c.add(p),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},cu=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...au(a,o))}return s},mi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?D(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},lu=e=>{const t=C(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!st(s)},du=e=>{const t=C(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},uu=e=>{const s=C(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!st(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},He=e=>{const t=D(e);return t===void 0||Br(t.getSourceFile())},Bt=(e,t)=>{const s=C(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&He(o);if(mi(tt(o),t))return!(r.isPropertyAccessExpression(o)&&Un.has(o.getName()))||r.isExpressionStatement(C(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!He(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},$e={kind:"opaque"},fu={kind:"unreached"},pu=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Vt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?D(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=pu(s);return i===void 0||es(i)?void 0:i}const n=ce(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},hi=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?$e:c===void 0?a.some(l=>l.isRestParameter())?$e:fu:c.isRestParameter()?$e:{kind:"parameter",parameter:c}},gu=e=>{const t=C(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Vt(s.getExpression());return n===void 0?$e:hi(n,s,t)},mu=new Set(["__defineGetter__","__defineSetter__","__proto__"]),hu=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,vi=e=>{const t=C(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=hu(s);if(n!==void 0)return N(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},vu=4,Ei=(e,t,s=0)=>{if(Kr(e))return!0;if(lu(e)){const i=C(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!mu.has(c)}if(du(e)||uu(e)||vi(e)||Bt(e,t))return!0;const n=gu(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Eu(n.parameter,s+1)},on=new WeakMap,Eu=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=on.get(e.compilerNode);if(n!==void 0)return n;if(t>vu)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||D(a)?.compilerNode!==e.compilerNode||Ei(a,void 0,t));return(o||t===0)&&on.set(e.compilerNode,o),o},an=new WeakMap,xu=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=D(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Su=(e,t,s)=>{const{context:n,impl:i}=e,o=an.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(p=>{const m=p.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(p=>[p.getText(),p.getParentOrThrow().compilerNode])),u=p=>r.isIdentifier(a)?Ei(p,n):!st(p),f=!xu(i,s)&&c.every(p=>(p.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(p=>{const m=p.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(p)||D(p)?.compilerNode!==x?!0:u(p)});return an.set(i.compilerNode,f),f},cn=new WeakMap,yu=e=>{let t=cn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=ao(s);return n===void 0?[]:[[n.compilerNode,s]]})),cn.set(e.compilerNode,t)),t},Au=e=>{const t=yu(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:Y(n)??n.getName()};return a!==void 0&&Su(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},Pt="args",Ne=e=>{const t=Zt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===Pt?t.member:void 0}if(!r.isIdentifier(e))return;const s=D(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=ce(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&ge(i)===Pt||r.isIdentifier(o)&&o.getText()===Pt?ge(s):void 0},bu=new Set(["auth","identity","user"]),Ut=e=>{const t=i=>{const o=ss(i);return o!==void 0&&o.length>0&&bu.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=J(s);return n!==void 0&&t(n)},xi=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Ne(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?J(n):void 0;if(o!==void 0)for(const a of xi(o,t-1))s.add(a)}return s},Ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Ke(n),...Ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const p=Ne(h(u)??u);return p===void 0?[]:Ke(f).filter(m=>m===p)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Ne(h(n)??n),c=Ne(h(i)??i);return a!==void 0&&Ut(i)&&o.push(a),c!==void 0&&Ut(n)&&o.push(c),o},Nu=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&Yr(i.getExpression(),"defineIdentityGuard")},Pu=e=>{if(!Nu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Ne(h(s)??s),o=t.some((a,c)=>c!==n&&Ut(a));return i!==void 0&&o?[i]:[]})},wu=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},Iu=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),ln=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},Tu=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Cu=(e,t)=>{const s=new Set;for(const n of E(e,d.IfStatement))if(n.getEnd()<=t&&ln(n,e)&&wu(n.getThenStatement()))for(const i of Ke(n.getExpression()))s.add(i);for(const n of E(e,d.CallExpression))if(n.getEnd()<=t&&Tu(n)&&ln(n,e))for(const i of Pu(n))s.add(i);return s},Ou=(e,t)=>{const s=xi(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Iu);if(n===void 0)return!1;const i=Cu(n,e.getStart());return[...s].every(o=>i.has(o))},ku=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Ru=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Wt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Si=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Fu=e=>{const t=C(e),s=t.getParent();if(r.isVariableDeclaration(s))return N(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Lu=e=>{const t=Fu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ce(t)?[t]:void 0:Si(t)},Pe=e=>e.isUnion()?e.getUnionTypes().every(t=>Pe(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Pe(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ge=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Be=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Du=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&Ru.get(s.getText())?.has(t.getName())===!0&&He(s)},Mu=e=>{const t=Ft(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=C(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ge(n,Wn)?n:void 0},_u=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=C(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ge(n,ku,t)?n:void 0},zu=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},$u=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&N(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},dn=e=>{const t=C(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Du(s);return _u(s,t)??zu(s,t)??$u(s,t)??(n?s:Mu(t))},Ku=5e4,yi=()=>({inProgress:new Set,verdicts:new Map});class Bu{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Ku&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Vu=8,Uu=8;class Wu{budget;scope;taint;verdicts=yi();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Pe(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Si(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Vu?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(C(l),!0,a,0))&&(t===n||!Pe(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=dn(o);m!==void 0;m=dn(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=C(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Pe(o.getType());if(st(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Lu(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const p=this.nestedReturningFunctionOf(o);return p!==void 0?this.resultCompromises(p,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=C(t).getParent();if(n>=Uu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===C(t)?this.valueCompromises(i,!1,s,n+1):!Ge(i,Wt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ce(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=C(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Be(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ge(t,Wt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Vt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!Bt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(Bt(s,this.scope.context))return!1;const i=Vt(t.getExpression()),o=i===void 0?void 0:hi(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||vi(t)||N(Ft(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Ft(t);return N(s,this.scope.impl)?void 0:s}}const qu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),ju=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=D(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Hu=new Set(["all","allSettled","any","race"]),un=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,wt=8;class Gu{budget=new Bu;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=yi();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Wu(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,wt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>Vr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=D(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(p=>p.getInitializer())].some(p=>p!==void 0&&this.isTaintedValue(p,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(p=>p.compilerNode===t.compilerNode):-1,o=C(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const p=h(a.getExpression());if(!r.isPropertyAccessExpression(p)||!Wt.has(p.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(p.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&ce(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(p=>{const m=C(p),x=m.getParent();return!r.isCallExpression(x)||x.getExpression()!==m||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&He(i)&&Hu.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(p=>!r.isSpreadElement(p)&&this.isRootedInContext(p,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Be(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=D(t),i=un(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&Un.has(i)?!1:i!==void 0&&Wn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Be(a)!==void 0)&&(i===void 0||!qu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=tt(i),c=r.isIdentifier(a)?un(D(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Be(i);if(o===void 0)return!ju(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Mr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(mi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?D(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=ce(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=es(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,wt))return!1;if(this.variableDepth>=wt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const fn=new WeakMap,Yu=e=>{const t=fn.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Gu(e);return fn.set(e.impl.compilerNode,s),s},Qu=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Xu=new Set(["insert","insertManyUnsafe","patch","replace"]),Ju=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Xu.has(t)&&jr(e.getExpression())?t:void 0},Zu=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},ef=(e,t)=>{const s=Zt(e);return s?.member===t?h(s.object):void 0},pn=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,Ai=(e,t,s,n=1)=>{const i=ef(e,s);if(i!==void 0)return pn(i,t);const o=r.isIdentifier(e)?D(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&ge(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ce(l)&&pn(h(l.getInitializer()),t))}const a=ce(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Ai(a,t,s,n-1)},qt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...qt(t.getWhenTrue()),...qt(t.getWhenFalse())]:[t]},tf=(e,t,s)=>{const n=[],i=s===void 0?void 0:Yu(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Qu.has(a))continue;const l=qt(c).filter(f=>i===void 0?G(f)&&!Hr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&Ai(c,s.parameter,a),p=l.every(m=>Ou(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...p&&{guarded:!0}})}}return n},sf=(e,t,s)=>{const n=Ju(e.getExpression()),i=n==="patch"||n==="replace"?2:1,o=n===void 0?void 0:e.getArguments()[i];if(n===void 0||o===void 0)return[];const a=Zu(o,n);if(a.length===0)return[];const c=S(e),l=Au(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>tf(f,u,l))},nf=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=O(e,t,(c,l)=>sf(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return ts(o,s).map(c=>Ur(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},rf=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),of=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,af=e=>{const t=q(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?of(t.getInitializer()):void 0},cf=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!rf.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?af(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},lf=(e,t)=>O(e,t,cf),df=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),uf=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},ff=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=q(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},bi=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Ni=(e,t)=>e===t||e.startsWith(`${t}.`),Pi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},gn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},wi=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>gn(s));return r.isIdentifier(e)&&gn(e)&&t.push(e),t},pf=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},gf=e=>{const t=bi(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},mf=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:gf(e),i=new Set,o=a=>Pi(a).some(c=>n.some(l=>Ni(c.getText(),l)))?!0:wi(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of pf(a))i.add(l)}return{names:i,prefixes:n}},hf=(e,t)=>Pi(e).some(s=>t.prefixes.some(n=>Ni(s.getText(),n)))?!0:wi(e).some(s=>t.names.has(s.getText())),vf=e=>{const t=_r(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Ef=(e,t,s)=>{const n=bi(e,0);if(n===void 0)return[];const i=mf(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!Kn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!hf(u,i))continue;const f=vf(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:S(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},xf=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=uf(n),o=i===void 0?void 0:df.get(i);if(o===void 0)continue;const a=ff(n,o);a!==void 0&&s.push(...Ef(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Sf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...xf(i,I(t,n)))}return s},mn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},hn=new Set(["account","credential","member","passkey","session","user"]),yf=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Af=e=>{const s=yf(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return hn.has(s)||hn.has(n)},bf=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Nf=(e,t)=>{const{objects:s,opaque:n}=os(e,t);return Fc(s).some(i=>bf(i))?!0:n?void 0:!1},Pf=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!q(t,"captcha"),usesRateLimit:!!q(t,"rateLimit")}},wf=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Ve={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},If=e=>{const t=wf(e),s=t?T(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Pf(t);return{...Ve,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in mn?{...Ve,[mn[s]]:!0}:Ve},Tf=e=>{const t={...Ve};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=If(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Cf=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Of=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Cf.has(t.getName()))return!1;const s=t.getExpression();if(!$(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:Af(i.getLiteralText())},kf=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),vn=new Set(["queues","scheduler","topics","workflows"]),Rf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!kf.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&vn.has(s.getName())&&Gr(s.getExpression()))return!0;s=s.getExpression()}const n=ss(s);return n?.length===1&&vn.has(n[0]??"")},Ff=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},Ii=new Set(["generateObject","generateText","streamObject","streamText"]),Lf=e=>{const t=T(e.getExpression());return t!==void 0&&Ii.has(t)},Df=e=>{const t=T(e.getExpression());if(t===void 0||!Ii.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!q(s,"maxOutputTokens")},Mf=new Set(["log","span","trace"]),_f=new Set(["ai"]),zf=new Set(["email","mail"]),$f=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),It=(e,t)=>[...t].some(s=>it(e,s).length>0),Ti=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Kf=new Set(["every","filter","flatMap","forEach","map","some"]),Bf=new Set(["all","allSettled","race"]),Ci=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(Kf.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Bf.has(n))return t},Vf=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Ti.has(t.getKind())){const s=Ci(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Uf=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Ti.has(t.getKind())){if(t=Ci(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Wf=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const x=m.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(m.getParent())}),p=u.getCatchClause();return f&&p!==void 0&&p.getDescendantsOfKind(d.ThrowStatement).length>0})},qf=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},jf=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Hf=e=>{let t=!1,s=!0;for(const n of[...$f].flatMap(i=>it(e,i))){const i=jf(n);i&&(t=!0,!Vf(i)&&!qf(i)&&!Wf(i)&&!Uf(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Gf=e=>E(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),En="lunora-advisor-exempt",Yf=/^[\s*/]+/u,Qf=/[\w-]/u,Xf=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
21
+ `},ri=new Set(["delete","get","head","options","patch","post","put"]),tc=new Set(["handler","stream"]),sc=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ws=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),nc=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ri.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},ic=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||ri.has(n.getName()))break;s=n.getExpression()}return nc(s)},rc=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Ws.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Ws.has(s.getText()))return!0}return!1},oc=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!tc.has(n.getName()))return;const i=ic(s);if(!i||!sc.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&rc(o);return{exportName:Y(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},ac=(e,t)=>{const s=[];for(const n of Z(e)){const i=oc(n,t);i&&s.push(i)}return s},cc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ac(i,I(t,n)))}return s},lc=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},dc=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?ge(t):void 0}},uc=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Vs(a)}))return!1;const n=D(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&Vs(i)},qs=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=lc(e);return n!==void 0&&dc(n)===t?!0:t==="args"&&uc(e)},oi=(e,t)=>r.isIdentifier(e)?qs(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>qs(s,t)),fc=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},js=e=>{const t=r.isIdentifier(e)?D(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!es(t)?t.getInitializer():void 0},Mt=e=>oi(e,"args"),J=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of E(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},G=e=>{if(Mt(e))return!0;const t=J(e);return t!==void 0&&Mt(t)},pc=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=J(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},me=e=>{if(bt(e))return!0;const t=js(e);if(t!==void 0&&bt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=js(i);return o!==void 0&&bt(o)})},ze=(e,t)=>oi(e,t),gc=(e,t)=>{if(ze(e,t))return!0;const s=J(e);if(s!==void 0&&ze(s,t))return!0;const n=fc(e);if(n!==void 0){const i=J(n);return i!==void 0&&ze(i,t)}return!1},mc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:X(e.getExpression(),["ai"]),hc=(e,t)=>{if(!mc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)||me(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},vc=(e,t)=>O(e,t,hc),Ec=new Set(["generateText","streamText"]),xc=new Set(["messages","prompt","system"]),Sc=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],yc=(e,t)=>Sc.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),Ac=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[qr(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&yc(i,s));return n===void 0?void 0:`${n}.${s}`},bc=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=Ac(t);if(s!==void 0)return s}},Nc=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=ge(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Pc=e=>{if(Mt(e))return!0;const t=Nc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},wc=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!xc.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&Pc(s))return!0}return!1},Ic=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=T(n.getExpression());if(i===void 0||!Ec.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(T(c.getExpression())==="tool"&&(a=bc(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:wc(o)})}return s},Tc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ic(i,I(t,n)))}return s},Cc=e=>X(e,["fetch"]),Oc=(e,t)=>{if(!Cc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!G(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},kc=(e,t)=>O(e,t,Oc),rs=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=ot(s.getExpression());return n===void 0||rs(n,t)})}finally{t.delete(e)}},Rc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=q(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:ot(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:rs(i)}},Fc=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?ot(o):void 0;a===void 0?s=!0:(t.push(a),s||=rs(a))}n=i.getExpression()}return{objects:t,opaque:s}},os=(e,t)=>t?Fc(t):Rc(e),ai=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=ot(s.getExpression());return n===void 0?[]:ai(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Lc=e=>e.flatMap(t=>ai(t,new Set)),Dc=new Set(["check","length","max"]),_t=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(Dc.has(s.getName()))return!0;t=n}},zt=e=>Jr(e)||e==="@lunora/values",Mc=e=>{const t=new Set(["v"]);for(const s of qn(e,"v",zt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&zt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},_c=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},zc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),$c=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&zt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),as=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return zc(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&$c(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Kc=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},Bc=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Vc=e=>r.isReturnStatement(e)?e.getExpression():void 0,Uc=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Bc(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Vc(t);return s?[s]:[]}),ci=(e,t)=>{if(as(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return ci(e.getExpression(),t)},Wc=(e,t)=>{const s=Kc(e.getExpression(),e.getSourceFile());if(!s)return[];const n=_t(e),i=new Set(Uc(s).map(o=>ci(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=as(o,t);return a===void 0?[]:[{bounded:_t(o)||n&&i.has(o),factory:a}]})},qc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=as(s,t),i=n===void 0?[]:[{bounded:_t(s),factory:n}];return r.isCallExpression(s)?[...i,...Wc(s,t)]:i}),jc=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=qc(a,t),l=y(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Hc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=ie(n);if(i?.visibility!=="public")return;const{objects:o}=os(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=jc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:Y(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Gc=(e,t)=>{const s=[],n=Mc(e),i={destructured:_c(e,n),namespaces:n};for(const o of Z(e)){const a=Hc(o,t,i);a&&s.push(a)}return s},Yc=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gc(i,I(t,n)))}return s},Nt=e=>e?.getKind()===d.TrueKeyword,Qc=e=>e?.getKind()===d.FalseKeyword,Xc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Jc=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Zc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&T(t.getExpression())==="scim"),el=e=>e!==void 0&&r.isCallExpression(e)&&Jc.has(T(e.getExpression())??""),tl=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),sl=e=>{const t=F(e,"advanced"),s=F(e,"emailAndPassword"),n=F(e,"session");return{analyzable:!0,disableCsrfCheck:Nt(F(t,"disableCSRFCheck")),emailPasswordEnabled:Nt(F(s,"enabled")),requireEmailVerification:Nt(F(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Zc(F(e,"plugins"))&&el(F(e,"database")),secureCookiesDisabled:Qc(F(t,"useSecureCookies")),sessionFreshAgeZero:Xc(F(n,"freshAge")),trustedOriginsWildcard:tl(F(e,"trustedOrigins"))}},nl=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),il=(e,t)=>{if(T(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?sl(s):nl();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},rl=(e,t)=>Lr(e,t,il),ol=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Vn(e.getExpression(),t.matchReceiver)?s:void 0},al=(e,t,s)=>{const n=ol(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!G(i)||me(i))&&!(s.requireUnmodifiedReach===!0&&!pc(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},at=(e,t,s)=>O(e,t,(n,i)=>al(n,i,s)),cl=new Set(["content","pdf","scrape","screenshot"]),ll=(e,t)=>at(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:cl}),dl=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),ul=new Set(["RateLimiter"]),fl=new Set(["extend"]),Hs="lunora",pl=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],li=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},$t=e=>e&&r.isObjectLiteralExpression(e)?li(e):{analyzable:!1,presentKeys:[],trueKeys:[]},gl=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&_n(t.getBody());return s?li(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},ml=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=T(n.getExpression());i!==void 0&&(dl.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...$t(n.getArguments()[0])}):fl.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...gl(n.getArguments()[0])}))}for(const n of E(e,d.NewExpression)){const i=T(n.getExpression());i===void 0||!ul.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...$t(n.getArguments()[0])})}return s},hl=e=>{for(const t of pl){const s=v(e,t);if(!M(s))continue;const n=new Xt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Je(s,"utf8")),i=[];for(const o of E(n,d.CallExpression))T(o.getExpression())===Hs&&i.push({callee:Hs,file:t,line:o.getStartLineNumber(),...$t(o.getArguments()[0])});return i}return[]},vl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of et(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...ml(o,n))}return s.push(...hl(Ze(t))),s},Gs="ctx.containers.",El=e=>{if(!e.startsWith(Gs))return!1;const t=e.slice(Gs.length);return t.length>0&&!t.includes(".")},xl=(e,t)=>at(e,t,{argIndex:0,matchReceiver:El,methods:new Set(["get"])}),Sl=new Set(["allow","deny","setAllowed"]),yl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=q(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},Al=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!yl(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},bl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!Sl.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Nl=(e,t)=>Al(e,t)??bl(e,t),Pl=(e,t)=>O(e,t,Nl),wl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="count")return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}return r.isPropertyAccessExpression(s)&&$(s.getExpression())?s.getName():void 0},Il=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&$(s)?1:0]},Tl=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Cl=e=>{if(e===void 0||!r.isObjectLiteralExpression(e))return;const t=[];for(const n of e.getProperties()){if(!r.isPropertyAssignment(n)&&!r.isShorthandPropertyAssignment(n))return;t.push(n.getName())}return t.length>0&&t.every(n=>Tl.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Ol=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return O(e,t,(i,o)=>{const a=wl(i);if(a===void 0)return;const c=Cl(Il(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},kl=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Rl=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return kl.has(s)?s:void 0},Fl=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=y(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Ll=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of et(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of E(o,d.CallExpression)){const c=Rl(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?Fl(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},Dl=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Ml=new Set(["dbRateLimit","rateLimit"]),_l=e=>{const t=$n(e);if(!t)return!1;const s=q(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},zl=(e,t)=>{const s=T(e.getExpression());if(s===void 0)return;const n=Dl.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:_l(e.getArguments()[n]),file:t,limitName:Ml.has(s)?zn(e):"",line:e.getStartLineNumber()}},$l=(e,t)=>O(e,t,zl),Kl=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=ie(t);if(s?.kind!=="query")return;const n=Dr(t,s.receiver);return n?{exportName:Y(e)??e.getName(),handler:n}:void 0},Ys=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Bl=e=>{const t=Ys(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Ys(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Vl=(e,t)=>{const s=[];for(const n of it(e.handler,"flags"))s.push({callee:Bl(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Ul=(e,t)=>{const s=[];for(const n of Z(e)){const i=Kl(n);i&&s.push(...Vl(i,t))}return s},Wl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ul(i,I(t,n)))}return s},ql=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:X(e.getExpression(),["flags"]),jl=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Hl=(e,t)=>{if(!ql(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=jl(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},Gl=(e,t)=>O(e,t,Hl),Yl=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Ql=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Xl=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of E(i,d.CallExpression))Yl(a)&&s.push({file:o,indexName:Ql(a),line:a.getStartLineNumber()})}return s},Jl=new Set(["delete","get","head","options","patch","post","put"]),Zl=new Set(["handler","stream"]),ed=new Set(["runAction","runMutation"]),td=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Te=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,di=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(ge(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Qs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:di(s,"ctx")},Xs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:di(s,"request")},Js=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(ed.has(a)&&Te(c,t))return a;if(td.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Te(c.getExpression(),t))return`db.${a}`}},Zs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Te(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Te(n.getInitializer(),t))){for(const o of i.getElements())if(ge(o)==="auth")return!0}}return!1},sd=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,nd=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Te(n.getExpression(),t)},id=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],ui=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:id(s)},rd=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?ui(t,a.getText()):[]}return[]},od=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=ui(s,t.getText());return n.length>0?n:rd(t,s)},en=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>nd(i,t)&&od(i).some(o=>sd.test(o)))},ad=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Zl.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Jl.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},cd=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Dt(e.getArguments()[0]),l=c&&Qs(c,!0);if(!c||l===void 0||en(c,Xs(c,!0)))return;const u=Js(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Zs(c,l),sideEffect:u}}const n=ad(e);if(n===void 0)return;const i=Dt(e.getArguments()[0]),o=i&&Qs(i,!1);if(!i||o===void 0||en(i,Xs(i,!1)))return;const a=Js(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Zs(i,o),sideEffect:a}},ld=(e,t)=>O(e,t,cd),dd=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ud=new Set(["append","set"]),fi=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",tn=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>dd.has(T(n.getExpression())??"")&&ze(n,t)),fd=(e,t)=>{if(tn(e,t))return!0;const s=J(e);return s!==void 0&&tn(s,t)},Kt=(e,t)=>gc(e,t)&&!fd(e,t),pd=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=J(e);return t!==void 0&&r.isNewExpression(t)&&T(t.getExpression())==="Headers"},je=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=J(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},cs=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Kt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:fi(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Kt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=je(n.getExpression());i!==void 0&&cs(i,t,s)}},pi=(e,t)=>{const s=je(e);if(s===void 0)return;const n=q(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=je(n.getInitializer());i!==void 0&&cs(i,"response-init",t)},gd=(e,t)=>{const s=T(e.getExpression());if(s==="Response")pi(e.getArguments()[1],t);else if(s==="Headers"){const n=je(e.getArguments()[0]);n!==void 0&&cs(n,"headers-ctor",t)}},md=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){pi(e.getArguments()[1],t);return}if(ud.has(n)&&pd(i)){const o=e.getArguments()[1];o!==void 0&&Kt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:fi(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},hd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))gd(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))md(s,t)},vd=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Dt(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return hd(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},Ed=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression))s.push(...vd(n,t));return s},xd=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ed(i,I(t,n)))}return s},gi="identity.ts",Sd=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return rt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},yd=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&rt(n.getModuleSpecifierValue())}return!1},Ad=e=>{if(r.isIdentifier(e))return Sd(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&yd(t)}return!1},bd=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Ad(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw de(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=nt(s,"member");a!==void 0&&t.push({exportName:a})}return t},Nd=(e,t)=>{const s=v(t,gi);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=bd(n);if(i.length!==0){if(i.length>1)throw de(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Pd=new Set(["auth","context.auth"]),wd="userId",Id=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(y(s))}return t},Td=(e,t)=>{const s=v(t,gi);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(T(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?Id(o):void 0}},sn=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return Pd.has(t.getText())||X(t,["auth"])?e:void 0},Cd=e=>{if(r.isPropertyAccessExpression(e)&&sn(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&sn(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},nn=(e,t,s)=>{const n=Cd(e);return n===void 0?void 0:{declared:n===wd||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},Od=(e,t)=>{const s=Td(e,t);return s===void 0?[]:[...ae(e,t,d.PropertyAccessExpression,(n,i)=>nn(n,i,s)),...ae(e,t,d.ElementAccessExpression,(n,i)=>nn(n,i,s))]},kd=(e,t)=>{if(T(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=F(s,"key");if(!(!n||!G(n)||me(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Rd=(e,t)=>O(e,t,kd),Fd=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ld=(e,t,s=[])=>{const n=at(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:Fd});return ts(n,s)},Dd=new Set(["queue","send"]),rn=new Set(["bcc","cc","to"]),Md=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Dd.has(t))return;const s=e.getExpression();return X(s,["mail"])||X(s,["email"])?t:void 0},_d=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return rn.has(y(t))&&G(n)&&!me(n)}if(!r.isPropertyAssignment(t)||!rn.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&G(s)&&!me(s)}):!1,zd=(e,t)=>{const s=Md(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!_d(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},$d=(e,t)=>O(e,t,zd),Kd=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=qe(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=qe(l);if(u===void 0)continue;const f=Qn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Bd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;return n?.receiver?ns(n.receiver).flatMap(i=>Kd(i,Y(e)??e.getName(),t)):[]},Vd=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Bd(a,o))}return s},Ud=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},Wd=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=q(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},qd=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return oo(s.getExpression())?s:void 0},jd=e=>{const t=qd(e),s=t===void 0?void 0:Wd(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?Y(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Ud(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Hd=e=>e.getVariableDeclarations().flatMap(t=>jd(t)),Gd=(e,t)=>{const s=v(t,ro);if(!M(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Hd(n)},Yd=new Set(["delete","get","patch"]),Qd=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Xd=new Set(["auth","identity","session","user"]),Jd=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Zd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!$(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},eu=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},tu=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),su=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,nu=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>tu(s.getExpression(),t)&&su(s.getThenStatement())),iu=(e,t)=>{for(const s of E(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Yd.has(i))continue;const o=n.getExpression(),a=$(o);if(!(a||r.isPropertyAccessExpression(o)&&$(o.getExpression())))continue;const l=a?2:1;if(s.getArguments().slice(0,l).some(f=>r.isIdentifier(f)&&f.getText()===t))return i}},ru=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>ss(tt(s))!==void 0)),ou=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Jd.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),au=e=>{for(const t of E(e,d.Identifier))if(Qd.has(t.getText()))return!0;return[...Xd].some(t=>it(e,t).length>0)?!0:ru(e)||ou(e)},cu=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ie(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Yn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&jn(n.receiver,"use","rls"),a=au(i),c=new Set,l=[];for(const u of E(i,d.CallExpression)){const f=Zd(u);if(f===void 0)continue;const p=eu(u);if(p===void 0||c.has(p)||!nu(i,p))continue;const m=iu(i,p);m!==void 0&&(c.add(p),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},lu=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...cu(a,o))}return s},mi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?D(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},du=e=>{const t=C(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!st(s)},uu=e=>{const t=C(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},fu=e=>{const s=C(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!st(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},He=e=>{const t=D(e);return t===void 0||Br(t.getSourceFile())},Bt=(e,t)=>{const s=C(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&He(o);if(mi(tt(o),t))return!(r.isPropertyAccessExpression(o)&&Un.has(o.getName()))||r.isExpressionStatement(C(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!He(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},$e={kind:"opaque"},pu={kind:"unreached"},gu=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Vt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?D(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=gu(s);return i===void 0||es(i)?void 0:i}const n=ce(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},hi=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?$e:c===void 0?a.some(l=>l.isRestParameter())?$e:pu:c.isRestParameter()?$e:{kind:"parameter",parameter:c}},mu=e=>{const t=C(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Vt(s.getExpression());return n===void 0?$e:hi(n,s,t)},hu=new Set(["__defineGetter__","__defineSetter__","__proto__"]),vu=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,vi=e=>{const t=C(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=vu(s);if(n!==void 0)return N(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},Eu=4,Ei=(e,t,s=0)=>{if(Kr(e))return!0;if(du(e)){const i=C(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!hu.has(c)}if(uu(e)||fu(e)||vi(e)||Bt(e,t))return!0;const n=mu(e);return n?.kind==="unreached"||n?.kind==="parameter"&&xu(n.parameter,s+1)},on=new WeakMap,xu=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=on.get(e.compilerNode);if(n!==void 0)return n;if(t>Eu)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||D(a)?.compilerNode!==e.compilerNode||Ei(a,void 0,t));return(o||t===0)&&on.set(e.compilerNode,o),o},an=new WeakMap,Su=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=D(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},yu=(e,t,s)=>{const{context:n,impl:i}=e,o=an.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(p=>{const m=p.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(p=>[p.getText(),p.getParentOrThrow().compilerNode])),u=p=>r.isIdentifier(a)?Ei(p,n):!st(p),f=!Su(i,s)&&c.every(p=>(p.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(p=>{const m=p.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(p)||D(p)?.compilerNode!==x?!0:u(p)});return an.set(i.compilerNode,f),f},cn=new WeakMap,Au=e=>{let t=cn.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=ao(s);return n===void 0?[]:[[n.compilerNode,s]]})),cn.set(e.compilerNode,t)),t},bu=e=>{const t=Au(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:Y(n)??n.getName()};return a!==void 0&&yu(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},Pt="args",Ne=e=>{const t=Zt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===Pt?t.member:void 0}if(!r.isIdentifier(e))return;const s=D(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=ce(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&ge(i)===Pt||r.isIdentifier(o)&&o.getText()===Pt?ge(s):void 0},Nu=new Set(["auth","identity","user"]),Ut=e=>{const t=i=>{const o=ss(i);return o!==void 0&&o.length>0&&Nu.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=J(s);return n!==void 0&&t(n)},xi=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Ne(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?J(n):void 0;if(o!==void 0)for(const a of xi(o,t-1))s.add(a)}return s},Ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Ke(n),...Ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const p=Ne(h(u)??u);return p===void 0?[]:Ke(f).filter(m=>m===p)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Ne(h(n)??n),c=Ne(h(i)??i);return a!==void 0&&Ut(i)&&o.push(a),c!==void 0&&Ut(n)&&o.push(c),o},Pu=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&Yr(i.getExpression(),"defineIdentityGuard")},wu=e=>{if(!Pu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Ne(h(s)??s),o=t.some((a,c)=>c!==n&&Ut(a));return i!==void 0&&o?[i]:[]})},Iu=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},Tu=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),ln=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},Cu=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Ou=(e,t)=>{const s=new Set;for(const n of E(e,d.IfStatement))if(n.getEnd()<=t&&ln(n,e)&&Iu(n.getThenStatement()))for(const i of Ke(n.getExpression()))s.add(i);for(const n of E(e,d.CallExpression))if(n.getEnd()<=t&&Cu(n)&&ln(n,e))for(const i of wu(n))s.add(i);return s},ku=(e,t)=>{const s=xi(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Tu);if(n===void 0)return!1;const i=Ou(n,e.getStart());return[...s].every(o=>i.has(o))},Ru=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),Fu=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Wt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Si=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Lu=e=>{const t=C(e),s=t.getParent();if(r.isVariableDeclaration(s))return N(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Du=e=>{const t=Lu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||ce(t)?[t]:void 0:Si(t)},Pe=e=>e.isUnion()?e.getUnionTypes().every(t=>Pe(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>Pe(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Ge=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Be=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},Mu=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&Fu.get(s.getText())?.has(t.getName())===!0&&He(s)},_u=e=>{const t=Ft(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=C(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ge(n,Wn)?n:void 0},zu=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=C(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ge(n,Ru,t)?n:void 0},$u=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},Ku=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&N(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},dn=e=>{const t=C(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Mu(s);return zu(s,t)??$u(s,t)??Ku(s,t)??(n?s:_u(t))},Bu=5e4,yi=()=>({inProgress:new Set,verdicts:new Map});class Vu{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Bu&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Uu=8,Wu=8;class qu{budget;scope;taint;verdicts=yi();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!Pe(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Si(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Uu?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(C(l),!0,a,0))&&(t===n||!Pe(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=dn(o);m!==void 0;m=dn(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=C(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&Pe(o.getType());if(st(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Du(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const p=this.nestedReturningFunctionOf(o);return p!==void 0?this.resultCompromises(p,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=C(t).getParent();if(n>=Wu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===C(t)?this.valueCompromises(i,!1,s,n+1):!Ge(i,Wt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||ce(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=C(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Be(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Ge(t,Wt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Vt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!Bt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(Bt(s,this.scope.context))return!1;const i=Vt(t.getExpression()),o=i===void 0?void 0:hi(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||vi(t)||N(Ft(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=Ft(t);return N(s,this.scope.impl)?void 0:s}}const ju=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Hu=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=D(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Gu=new Set(["all","allSettled","any","race"]),un=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,wt=8;class Yu{budget=new Vu;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=yi();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new qu(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,wt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>Vr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=D(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(p=>p.getInitializer())].some(p=>p!==void 0&&this.isTaintedValue(p,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(p=>p.compilerNode===t.compilerNode):-1,o=C(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const p=h(a.getExpression());if(!r.isPropertyAccessExpression(p)||!Wt.has(p.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(p.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&ce(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(p=>{const m=C(p),x=m.getParent();return!r.isCallExpression(x)||x.getExpression()!==m||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&He(i)&&Gu.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(p=>!r.isSpreadElement(p)&&this.isRootedInContext(p,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Be(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=D(t),i=un(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&Un.has(i)?!1:i!==void 0&&Wn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Be(a)!==void 0)&&(i===void 0||!ju.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=tt(i),c=r.isIdentifier(a)?un(D(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Be(i);if(o===void 0)return!Hu(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Mr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(mi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?D(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=ce(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=es(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,wt))return!1;if(this.variableDepth>=wt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const fn=new WeakMap,Qu=e=>{const t=fn.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Yu(e);return fn.set(e.impl.compilerNode,s),s},Xu=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Ju=new Set(["insert","insertManyUnsafe","patch","replace"]),Zu=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Ju.has(t)&&jr(e.getExpression())?t:void 0},ef=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},tf=(e,t)=>{const s=Zt(e);return s?.member===t?h(s.object):void 0},pn=(e,t)=>r.isIdentifier(e)&&D(e)?.compilerNode===t.compilerNode,Ai=(e,t,s,n=1)=>{const i=tf(e,s);if(i!==void 0)return pn(i,t);const o=r.isIdentifier(e)?D(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&ge(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||ce(l)&&pn(h(l.getInitializer()),t))}const a=ce(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Ai(a,t,s,n-1)},qt=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...qt(t.getWhenTrue()),...qt(t.getWhenFalse())]:[t]},sf=(e,t,s)=>{const n=[],i=s===void 0?void 0:Qu(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Xu.has(a))continue;const l=qt(c).filter(f=>i===void 0?G(f)&&!Hr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&Ai(c,s.parameter,a),p=l.every(m=>ku(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...p&&{guarded:!0}})}}return n},nf=(e,t,s)=>{const n=Zu(e.getExpression()),i=n==="patch"||n==="replace"?2:1,o=n===void 0?void 0:e.getArguments()[i];if(n===void 0||o===void 0)return[];const a=ef(o,n);if(a.length===0)return[];const c=S(e),l=bu(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>sf(f,u,l))},rf=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=O(e,t,(c,l)=>nf(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return ts(o,s).map(c=>Ur(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},of=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),af=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,cf=e=>{const t=q(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?af(t.getInitializer()):void 0},lf=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!of.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?cf(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},df=(e,t)=>O(e,t,lf),uf=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),ff=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},pf=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=q(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},bi=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Ni=(e,t)=>e===t||e.startsWith(`${t}.`),Pi=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},gn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},wi=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>gn(s));return r.isIdentifier(e)&&gn(e)&&t.push(e),t},gf=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},mf=e=>{const t=bi(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},hf=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:mf(e),i=new Set,o=a=>Pi(a).some(c=>n.some(l=>Ni(c.getText(),l)))?!0:wi(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of gf(a))i.add(l)}return{names:i,prefixes:n}},vf=(e,t)=>Pi(e).some(s=>t.prefixes.some(n=>Ni(s.getText(),n)))?!0:wi(e).some(s=>t.names.has(s.getText())),Ef=e=>{const t=_r(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},xf=(e,t,s)=>{const n=bi(e,0);if(n===void 0)return[];const i=hf(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!Kn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!vf(u,i))continue;const f=Ef(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:S(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Sf=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=ff(n),o=i===void 0?void 0:uf.get(i);if(o===void 0)continue;const a=pf(n,o);a!==void 0&&s.push(...xf(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},yf=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Sf(i,I(t,n)))}return s},mn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},hn=new Set(["account","credential","member","passkey","session","user"]),Af=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),bf=e=>{const s=Af(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return hn.has(s)||hn.has(n)},Nf=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Pf=(e,t)=>{const{objects:s,opaque:n}=os(e,t);return Lc(s).some(i=>Nf(i))?!0:n?void 0:!1},wf=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!q(t,"captcha"),usesRateLimit:!!q(t,"rateLimit")}},If=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Ve={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Tf=e=>{const t=If(e),s=t?T(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=wf(t);return{...Ve,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in mn?{...Ve,[mn[s]]:!0}:Ve},Cf=e=>{const t={...Ve};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=Tf(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},Of=new Set(["insert","insertMany","insertManyUnsafe","replace"]),kf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Of.has(t.getName()))return!1;const s=t.getExpression();if(!$(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:bf(i.getLiteralText())},Rf=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),vn=new Set(["queues","scheduler","topics","workflows"]),Ff=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Rf.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&vn.has(s.getName())&&Gr(s.getExpression()))return!0;s=s.getExpression()}const n=ss(s);return n?.length===1&&vn.has(n[0]??"")},Lf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},Ii=new Set(["generateObject","generateText","streamObject","streamText"]),Df=e=>{const t=T(e.getExpression());return t!==void 0&&Ii.has(t)},Mf=e=>{const t=T(e.getExpression());if(t===void 0||!Ii.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!q(s,"maxOutputTokens")},_f=new Set(["log","span","trace"]),zf=new Set(["ai"]),$f=new Set(["email","mail"]),Kf=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),It=(e,t)=>[...t].some(s=>it(e,s).length>0),Ti=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Bf=new Set(["every","filter","flatMap","forEach","map","some"]),Vf=new Set(["all","allSettled","race"]),Ci=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(Bf.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Vf.has(n))return t},Uf=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Ti.has(t.getKind())){const s=Ci(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Wf=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Ti.has(t.getKind())){if(t=Ci(t),t===void 0)return!1;continue}t=t.getParent()}return!1},qf=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const x=m.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(m.getParent())}),p=u.getCatchClause();return f&&p!==void 0&&p.getDescendantsOfKind(d.ThrowStatement).length>0})},jf=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Hf=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Gf=e=>{let t=!1,s=!0;for(const n of[...Kf].flatMap(i=>it(e,i))){const i=Hf(n);i&&(t=!0,!Uf(i)&&!jf(i)&&!qf(i)&&!Wf(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Yf=e=>E(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),En="lunora-advisor-exempt",Qf=/^[\s*/]+/u,Xf=/[\w-]/u,Jf=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
22
22
  `);for(const n of s.split(`
23
- `)){const i=n.replace(Yf,"");if(!i.startsWith(En))continue;const o=i.slice(En.length);if(Qf.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:""}},Jf=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=q(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Zf=(e,t)=>{const s=Jf(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},ep=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of E(e,d.CallExpression))if(Of(l)&&(o=!0),Rf(l)&&(t=!0),Ff(l)&&(i=!0),Lf(l)&&(s=!0),Df(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Hf(e);return{callsMail:It(e,zf),emitsEvent:It(e,Mf),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||It(e,_f),throwsBareError:Gf(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},tp=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ie(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Tf(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Zf(e,s);return{...o?ep(o):{},...Xf(e),...i,analyzableBody:o!==void 0,exportName:Y(e)??e.getName(),file:t,hasEmailArg:Nf(s,n.receiver),kind:n.kind,visibility:n.visibility}},sp=(e,t)=>{const s=[];for(const n of Z(e)){const i=tp(n,t);i&&s.push(i)}return s},np=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sp(i,I(t,n)))}return s},ip=new Set(["dbRateLimit","rateLimit"]),rp=e=>r.isArrowFunction(e)?e.getBody():e,op=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Oi=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},ki=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},ap=(e,t)=>G(e)||t!==void 0&&ki(e,t).some(s=>Oi(s)),cp=(e,t)=>t===void 0?me(e):ki(e,t).some(s=>!Oi(s)),lp=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!ip.has(s))return;const n=F($n(e.getArguments()[2]),"key");if(!n)return;const i=rp(n),o=op(n);if(!(!ap(i,o)||cp(i,o)))return{callee:s,scope:S(e),file:t,limitName:zn(e),line:e.getStartLineNumber()}},dp=(e,t)=>O(e,t,lp),up=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),fp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!up.has(t.getName()))return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&$(s.getExpression()))return s.getName()},pp=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&$(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},gp=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},Ri=(e,t=!1)=>{const s=gp(e);if(r.isIdentifier(s)){if(t)return;const n=J(s);return n===void 0?void 0:Ri(n,!0)}if(r.isCallExpression(s))return fp(s)??pp(s)},mp=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of E(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},hp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ie(s);if(n?.kind!=="query")return[];const i=Yn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Qr(n.receiver,"output"),a=n.receiver!==void 0&&jn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of mp(i)){const f=Ri(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},vp=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...hp(a,o))}return s},Ep=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(y(s));return t},xp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Gn(o);if(a===void 0)continue;const c=Ep(F(a.options,"with"));c.length!==0&&i.push({exportName:Y(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Sp=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...xp(a,o))}return s},H=(e,t)=>`${e}:${t}`,xn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},yp=(e,t)=>[...ae(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?xn(s,n,s.getName(),s.isExported()):void 0),...ae(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?xn(i,n,s.getName(),i.isExported()):void 0})],Ap=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(H(c,a))},bp=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Np=(e,t)=>{const s=new Map(e.map(n=>[H(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(H(i.file,i.name))?.set(bp(n),{fields:n.fields,method:n.method,table:n.table})}return s},Pp=(e,t,s)=>E(e.node,d.CallExpression).map(n=>Ap(n,t,s)).filter(n=>n!==void 0),wp=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(H(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(H(o.file,o.name))?.push(a)}},Ip=(e,t,s)=>{const n=new Map(e.map(a=>[H(a.file,a.name),a])),i=new Map(e.map(a=>[`${is(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[H(a.file,a.name),Pp(a,n,t)]));return wp(s,n,i,o),o},Tp=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Cp=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(H(i.file,i.name))??[])Tp(t.get(H(i.file,i.name)),t.get(H(o.file,o.name)))&&(n=!0)}},Op=(e,t,s,n)=>{const i=yp(e,t),o=Np(i,s);return Cp(i,o,Ip(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(H(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ye=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ye(e.getLeft()),s=Ye(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},kp=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Ye(t)!==void 0},Rp=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return y(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Fp=(e,t,s)=>Eo(e)?!zr(s)&&xo(Rp(t)):!0,Lp=(e,t)=>{const s=[],n=[...E(e,d.BinaryExpression),...E(e,d.StringLiteral),...E(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(kp(o))continue;const a=Ye(o);if(a===void 0)continue;const c=ho(a);if(c===void 0||!Fp(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:vo(a)}))}return s},Dp=(e,t)=>{const s=[],n=new Xt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of A(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Je(i,"utf8"),{overwrite:!0});s.push(...Lp(o,I(t,i)))}return s},Mp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Gn(o);if(a===void 0)continue;const c=F(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&G(c);!l&&!u||i.push({exportName:Y(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},_p=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Mp(a,o))}return s},zp=new Set(["query","unsafe"]),$p=e=>!r.isPropertyAccessExpression(e)||!zp.has(e.getName())?!1:X(e.getExpression(),["sql"]),Kp=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Bp=(e,t)=>{if(!$p(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Kp(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},Vp=(e,t)=>O(e,t,Bp),Up=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Wp=e=>{for(const[t,s]of Up)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},qp=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Wp(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},jp=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Hp=(e,t,s=[])=>{const n=at(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:jp,requireUnmodifiedReach:!0});return ts(n,s)},Gp=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Yp=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Qp=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),o==="expiresInSeconds"&&(s=Yp(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Xp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Gp.get(t);return s===void 0?void 0:Vn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Jp=(e,t)=>{const s=Xp(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...Qp(e.getArguments()[s.optionsIndex])}},Zp=(e,t)=>O(e,t,Jp),eg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Fi=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:eg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>le(i)||s(i));if(!(n===void 0||le(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},ls=(e,t)=>N(e.getFirstAncestor(s=>N(s,t)||le(s)),t),tg=(e,t)=>N(e,t)||e.getFirstAncestor(s=>N(s,t))!==void 0,Li=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return N(e,t)||ls(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Fi(e);return s!==void 0&&!tg(s,t)}return!1},Di=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],sg=e=>Di(e).some(t=>Li(t,e)),ng=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},ig=e=>Di(e).some(t=>Li(t,e)||r.isBreakStatement(t)&&N(Fi(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>ng(t)&&ls(t,e)),rg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>ls(t,e)),og=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),ag=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Tt=(e,t)=>{const s=og(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||ig(e)||rg(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(le)!==void 0))return{file:t,kind:ag(e),line:e.getStartLineNumber(),scope:i}},cg=(e,t)=>[...ae(e,t,d.WhileStatement,Tt),...ae(e,t,d.ForStatement,Tt),...ae(e,t,d.DoStatement,Tt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),lg=new Set(["when","where"]),Ct=new Set(["definePolicy","defineShape"]),dg=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Ct.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return Ct.has(i)?i:void 0}const s=t.getText();return Ct.has(s)?s:void 0},ug=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,Mi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(ug(e))return"empty-object";if(r.isParenthesizedExpression(e))return Mi(e.getExpression())}},ds=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),fg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ds(t)===e),_i=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>ds(t)===e),pg=e=>{const t=fg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||_i(e).length>0},gg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>ds(t)===e),jt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",mg=(e,t)=>jt(e)||jt(t),hg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Sn=e=>!jt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),vg=(e,t,s)=>{const n=hg.get(e);if(n!==void 0)return mg(t,s)?n==="positive"?"negative":"positive":Sn(t)||Sn(s)?void 0:n},we=e=>{if(r.isParenthesizedExpression(e))return we(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=vg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=we(e.getLeft()),i=we(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},yn=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},Eg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},xg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Sg=e=>{const t=[];for(const s of _i(e)){const n=we(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of gg(e)){const n=we(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?yn(s.getThenStatement()):yn(s.getElseStatement())??Eg(s);i!==void 0&&t.push(xg(i))}return t},yg=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},Ag=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!lg.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&pg(a))for(const c of Sg(a)){const l=Mi(c);l!==void 0&&i.push({exportName:yg(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},bg=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=dg(n);i!==void 0&&s.push(...Ag(n,i,t))}return s},Ng=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...bg(i,I(t,n)))}return s},Pg=new Set(["query","upsert","upsertMany","upsertNow"]),ve=new Set,wg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(Pg.has(t))return X(e.getExpression(),["vectors"])?t:void 0},us=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},zi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},$i=e=>zi(e)?.getDeclarations()[0],Ig=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Ki=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},An=(e,t,s)=>{const n=zi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Ki($i(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return fs(o,t,s-1)}return G(e)},fs=(e,t,s)=>{const n=us(e);return me(n)?!1:r.isIdentifier(n)?An(n,t,s):G(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>Ig(i)&&An(i,t,s))},Bi=e=>{const t=Ki($i(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ne=(e,t)=>{const s=us(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ne(s.getWhenTrue(),t),...ne(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ne(s.getLeft(),t),...ne(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Bi(s);return n===void 0?[]:ne(n,!1)}return[]},Tg=(e,t)=>{const s=ne(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>Qe(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Cg=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Og=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),Qe=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Tg(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Cg(n)&&(s=[Og(n)]);return s},kg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},Rg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return ve;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return ve;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Ht=(e,t=!0,s=ve)=>{const n=us(e);if(r.isIdentifier(n)){const o=t?Bi(n):void 0;return o===void 0?[{node:n,parameters:s}]:Ht(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Ht(o.getExpression(),t,s):ne(o,!0).flatMap(a=>Qe(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=fs(i.getExpression(),ve,1)?Rg(o):ve;return kg(o).flatMap(c=>ne(c,!0).flatMap(l=>Qe(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Fg=(e,t)=>{const s=wg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Ht(n):ne(n,!0).flatMap(o=>Qe(o,!0).map(a=>({node:a,parameters:ve})))).some(({node:o,parameters:a})=>fs(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},Lg=(e,t)=>O(e,t,Fg),Dg=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:p,wranglerVariables:m,workflows:x}=s;return Rr({adminRoutes:ac(e,t),aiRawRuns:hc(e,t),aiToolSideEffects:Ic(e,t),argumentDerivedFetches:Oc(e,t),argumentValidators:Gc(e,t),authApiCalls:eo(e,t),authConfigs:il(e,t),browserUrlAccesses:cl(e,t),callEdges:n.callEdges,configCalls:hl(e,t),containerKeyAccesses:El(e,t),containerOverrides:Nl(e,t),containers:i,countReads:Cl(e,t,f.tables),crons:o,cronTargets:o.flatMap(_=>_.functionPath===void 0?[]:[_.functionPath]),exportSinks:Fl(e,t),staleMigrationImports:qp(e,t),failOpenGuards:zl(e,t),flagReads:Ul(e,t),flagSecurityDefaults:Hl(e,t),geoIndexUsages:Ql(e,t),httpActionGuards:cd(e,t),httpHeaderWrites:Ed(e,t),hyperdriveCalls:no(e,t),identityClaimReads:Cd(e,t),imageDeliveryUrlAccesses:kd(e,t),inserts:n.inserts,kvKeyAccesses:Fd(e,t,a),mailRecipientAccesses:zd(e,t),maskProcedures:io(e,t),maskStrategies:Bd(e,t),mutatorWrites:Hd(e,t),nondeterministicCalls:lo(e,t),normalizeIdAuthorizations:cu(e,t),notifyCalls:fo(e,t),notifyConfig:uo(e,t),mutators:l,ownerFieldWrites:nf(e,t,a,l),unrestrictedWhereBranches:Ng(e,t),paymentWebhooks:lf(e,t),privilegedDispatches:Sf(e,t),procedureProtections:np(e,t),queries:n.queries,queues:u,r2sqlCalls:po(e,t),ratelimitKeySelectors:dp(e,t),rawRowReturns:vp(e,t),relationLoads:Sp(e,t),rlsProcedures:go(e,t),schema:f,secretLiterals:Dp(e,t),modules:c,shapes:p,softDeleteReads:_p(e,t),sqlInterpolations:Vp(e,t),storageKeyAccesses:Hp(e,t,a),storageUploads:Zp(e,t),tableWrites:n.tableWrites,rowEffects:Op(e,t,n.tableWrites,n.callEdges),unboundedLoops:cg(e,t),vectorNamespaceAccesses:Lg(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:m})},Mg=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),_g=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>Mg(i))]},zg=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),$g=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",bn={error:"ERROR",info:"INFO",warn:"WARN"},Nn={ERROR:2,INFO:0,WARN:1},Kg=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"}),Bg=(e,t)=>{const{advisor:s}=Xn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(bn,n)?bn[n]:void 0;return i===void 0?[...t,Kg(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=>$g(o)||Nn[o.level]>=Nn[i])},Vg=(e,t)=>{const{advisor:s}=Xn(e),n=_g(t,s?.accept??[]);return Bg(e,s?.acceptUnreadable===!0?[...n,zg()]:n)},Ug={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Wg="crons",qg=Po.replace(/\.ts$/u,""),he=(e,t)=>`${is(e)}:${t}`,Ot=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},jg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Ug[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,...Ot("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Ot("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Ot("workflow",t.workflow,"workflow name")}))],Hg=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Gg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Hg(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Yg=e=>jg(e).flatMap(t=>Gg(t)),Qg=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:Wg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Xg=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),be=(e,t)=>t===void 0?e:{...e,module:t},Jg=e=>{const t=new Map,s=new Map,n=Xg(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(he(c.file,c.exportName),l)};for(const c of e.functions){const l=he(c.filePath,c.exportName),u=[...mo(c.filePath),c.exportName].join(".");o(be({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Me(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=he(c.filePath,c.exportName);o(be({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Me(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(be({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(be({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Me(e.modules,c.filePath)),he(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(be({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Me(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},he(qg,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}},Zg=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,em=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(he(e.file,e.exportName))??{reason:Zg(e.exportName)},tm=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=em(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},kt=e=>`${e.from}|${e.kind}|${e.to}`,sm=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,nm=e=>{const{nodes:t,sites:s}=Jg(e),n=new Map,i=new Map;for(const o of[...Qg(e),...Yg(e)]){const a=tm(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(kt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(sm(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>kt(o).localeCompare(kt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},im=e=>`${Jn}export const architecture = ${Io(e,"Record<string, unknown>")};
24
- `,Pn=(e,t="api")=>{const s=new Map;for(const n of e){const i=is(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new L("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},rm=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Zn(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=>ei(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:zo)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)},om=(e,t,s={})=>{if(t===void 0)return;const n=rm(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
23
+ `)){const i=n.replace(Qf,"");if(!i.startsWith(En))continue;const o=i.slice(En.length);if(Xf.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:""}},Zf=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=q(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},ep=(e,t)=>{const s=Zf(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},tp=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of E(e,d.CallExpression))if(kf(l)&&(o=!0),Ff(l)&&(t=!0),Lf(l)&&(i=!0),Df(l)&&(s=!0),Mf(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Gf(e);return{callsMail:It(e,$f),emitsEvent:It(e,_f),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||It(e,zf),throwsBareError:Yf(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},sp=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=ie(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Cf(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=ep(e,s);return{...o?tp(o):{},...Jf(e),...i,analyzableBody:o!==void 0,exportName:Y(e)??e.getName(),file:t,hasEmailArg:Pf(s,n.receiver),kind:n.kind,visibility:n.visibility}},np=(e,t)=>{const s=[];for(const n of Z(e)){const i=sp(n,t);i&&s.push(i)}return s},ip=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...np(i,I(t,n)))}return s},rp=new Set(["dbRateLimit","rateLimit"]),op=e=>r.isArrowFunction(e)?e.getBody():e,ap=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Oi=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},ki=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},cp=(e,t)=>G(e)||t!==void 0&&ki(e,t).some(s=>Oi(s)),lp=(e,t)=>t===void 0?me(e):ki(e,t).some(s=>!Oi(s)),dp=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!rp.has(s))return;const n=F($n(e.getArguments()[2]),"key");if(!n)return;const i=op(n),o=ap(n);if(!(!cp(i,o)||lp(i,o)))return{callee:s,scope:S(e),file:t,limitName:zn(e),line:e.getStartLineNumber()}},up=(e,t)=>O(e,t,dp),fp=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),pp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!fp.has(t.getName()))return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&$(s.getExpression()))return s.getName()},gp=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&$(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},mp=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},Ri=(e,t=!1)=>{const s=mp(e);if(r.isIdentifier(s)){if(t)return;const n=J(s);return n===void 0?void 0:Ri(n,!0)}if(r.isCallExpression(s))return pp(s)??gp(s)},hp=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of E(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},vp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=ie(s);if(n?.kind!=="query")return[];const i=Yn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&Qr(n.receiver,"output"),a=n.receiver!==void 0&&jn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of hp(i)){const f=Ri(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:Y(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Ep=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...vp(a,o))}return s},xp=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(y(s));return t},Sp=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Gn(o);if(a===void 0)continue;const c=xp(F(a.options,"with"));c.length!==0&&i.push({exportName:Y(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},yp=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(...Sp(a,o))}return s},H=(e,t)=>`${e}:${t}`,xn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Ap=(e,t)=>[...ae(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?xn(s,n,s.getName(),s.isExported()):void 0),...ae(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?xn(i,n,s.getName(),i.isExported()):void 0})],bp=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(H(c,a))},Np=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,Pp=(e,t)=>{const s=new Map(e.map(n=>[H(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(H(i.file,i.name))?.set(Np(n),{fields:n.fields,method:n.method,table:n.table})}return s},wp=(e,t,s)=>E(e.node,d.CallExpression).map(n=>bp(n,t,s)).filter(n=>n!==void 0),Ip=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(H(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(H(o.file,o.name))?.push(a)}},Tp=(e,t,s)=>{const n=new Map(e.map(a=>[H(a.file,a.name),a])),i=new Map(e.map(a=>[`${is(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[H(a.file,a.name),wp(a,n,t)]));return Ip(s,n,i,o),o},Cp=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},Op=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(H(i.file,i.name))??[])Cp(t.get(H(i.file,i.name)),t.get(H(o.file,o.name)))&&(n=!0)}},kp=(e,t,s,n)=>{const i=Ap(e,t),o=Pp(i,s);return Op(i,o,Tp(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(H(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ye=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ye(e.getLeft()),s=Ye(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Rp=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Ye(t)!==void 0},Fp=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return y(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Lp=(e,t,s)=>Eo(e)?!zr(s)&&xo(Fp(t)):!0,Dp=(e,t)=>{const s=[],n=[...E(e,d.BinaryExpression),...E(e,d.StringLiteral),...E(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(Rp(o))continue;const a=Ye(o);if(a===void 0)continue;const c=ho(a);if(c===void 0||!Lp(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:vo(a)}))}return s},Mp=(e,t)=>{const s=[],n=new Xt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of A(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Je(i,"utf8"),{overwrite:!0});s.push(...Dp(o,I(t,i)))}return s},_p=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?ie(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Gn(o);if(a===void 0)continue;const c=F(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&G(c);!l&&!u||i.push({exportName:Y(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},zp=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of Z(i))s.push(..._p(a,o))}return s},$p=new Set(["query","unsafe"]),Kp=e=>!r.isPropertyAccessExpression(e)||!$p.has(e.getName())?!1:X(e.getExpression(),["sql"]),Bp=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Vp=(e,t)=>{if(!Kp(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Bp(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},Up=(e,t)=>O(e,t,Vp),Wp=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],qp=e=>{for(const[t,s]of Wp)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},jp=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=qp(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Hp=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Gp=(e,t,s=[])=>{const n=at(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Hp,requireUnmodifiedReach:!0});return ts(n,s)},Yp=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Qp=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Xp=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=y(i);t.push(o),o==="expiresInSeconds"&&(s=Qp(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(y(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Jp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Yp.get(t);return s===void 0?void 0:Vn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Zp=(e,t)=>{const s=Jp(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...Xp(e.getArguments()[s.optionsIndex])}},eg=(e,t)=>O(e,t,Zp),tg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Fi=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:tg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>le(i)||s(i));if(!(n===void 0||le(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},ls=(e,t)=>N(e.getFirstAncestor(s=>N(s,t)||le(s)),t),sg=(e,t)=>N(e,t)||e.getFirstAncestor(s=>N(s,t))!==void 0,Li=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return N(e,t)||ls(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Fi(e);return s!==void 0&&!sg(s,t)}return!1},Di=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],ng=e=>Di(e).some(t=>Li(t,e)),ig=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},rg=e=>Di(e).some(t=>Li(t,e)||r.isBreakStatement(t)&&N(Fi(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>ig(t)&&ls(t,e)),og=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>ls(t,e)),ag=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),cg=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",Tt=(e,t)=>{const s=ag(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||rg(e)||og(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(le)!==void 0))return{file:t,kind:cg(e),line:e.getStartLineNumber(),scope:i}},lg=(e,t)=>[...ae(e,t,d.WhileStatement,Tt),...ae(e,t,d.ForStatement,Tt),...ae(e,t,d.DoStatement,Tt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),dg=new Set(["when","where"]),Ct=new Set(["definePolicy","defineShape"]),ug=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return Ct.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return Ct.has(i)?i:void 0}const s=t.getText();return Ct.has(s)?s:void 0},fg=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,Mi=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(fg(e))return"empty-object";if(r.isParenthesizedExpression(e))return Mi(e.getExpression())}},ds=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),pg=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ds(t)===e),_i=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>ds(t)===e),gg=e=>{const t=pg(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||_i(e).length>0},mg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>ds(t)===e),jt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",hg=(e,t)=>jt(e)||jt(t),vg=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Sn=e=>!jt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Eg=(e,t,s)=>{const n=vg.get(e);if(n!==void 0)return hg(t,s)?n==="positive"?"negative":"positive":Sn(t)||Sn(s)?void 0:n},we=e=>{if(r.isParenthesizedExpression(e))return we(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Eg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=we(e.getLeft()),i=we(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},yn=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},xg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Sg=e=>r.isReturnStatement(e)?e.getExpression()??e:e,yg=e=>{const t=[];for(const s of _i(e)){const n=we(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of mg(e)){const n=we(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?yn(s.getThenStatement()):yn(s.getElseStatement())??xg(s);i!==void 0&&t.push(Sg(i))}return t},Ag=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},bg=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!dg.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&gg(a))for(const c of yg(a)){const l=Mi(c);l!==void 0&&i.push({exportName:Ag(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return i},Ng=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=ug(n);i!==void 0&&s.push(...bg(n,i,t))}return s},Pg=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ng(i,I(t,n)))}return s},wg=new Set(["query","upsert","upsertMany","upsertNow"]),ve=new Set,Ig=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(wg.has(t))return X(e.getExpression(),["vectors"])?t:void 0},us=e=>{let t=e;for(;r.isParenthesizedExpression(t)||r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isTypeAssertion(t);)t=t.getExpression();return t},zi=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},$i=e=>zi(e)?.getDeclarations()[0],Tg=e=>{const t=e.getParent();return r.isBindingElement(t)||(r.isPropertyAccessExpression(t)||r.isPropertyAssignment(t)||r.isVariableDeclaration(t)||r.isParameterDeclaration(t)||r.isMethodDeclaration(t))&&t.getNameNode()===e?!1:!r.isQualifiedName(t)||t.getLeft()===e},Ki=e=>{let t=e;for(;t!==void 0&&(r.isBindingElement(t)||r.isObjectBindingPattern(t)||r.isArrayBindingPattern(t));)t=t.getParent();return t!==void 0&&r.isVariableDeclaration(t)?t:void 0},An=(e,t,s)=>{const n=zi(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Ki($i(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return fs(o,t,s-1)}return G(e)},fs=(e,t,s)=>{const n=us(e);return me(n)?!1:r.isIdentifier(n)?An(n,t,s):G(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>Tg(i)&&An(i,t,s))},Bi=e=>{const t=Ki($i(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ne=(e,t)=>{const s=us(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ne(s.getWhenTrue(),t),...ne(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ne(s.getLeft(),t),...ne(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=Bi(s);return n===void 0?[]:ne(n,!1)}return[]},Cg=(e,t)=>{const s=ne(e,t);if(s.length===0)return{replaces:!0,sources:[e]};const n=s.map(o=>Qe(o,!1)),i=n.flat();if(i.length!==0)return{replaces:n.every(o=>o.length>0),sources:i}},Og=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",kg=e=>r.isShorthandPropertyAssignment(e)?e.getNameNode():e.getInitializer()??e.getNameNode(),Qe=(e,t)=>{let s=[];for(const n of e.getProperties())if(r.isSpreadAssignment(n)){const i=Cg(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Og(n)&&(s=[kg(n)]);return s},Rg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return[];const t=e.getBody();return r.isBlock(t)?t.getDescendantsOfKind(d.ReturnStatement).filter(s=>s.getFirstAncestor(n=>r.isFunctionLikeDeclaration(n))===e).flatMap(s=>s.getExpression()??[]):[t]},Fg=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return ve;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return ve;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},Ht=(e,t=!0,s=ve)=>{const n=us(e);if(r.isIdentifier(n)){const o=t?Bi(n):void 0;return o===void 0?[{node:n,parameters:s}]:Ht(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?Ht(o.getExpression(),t,s):ne(o,!0).flatMap(a=>Qe(a,!0).map(c=>({node:c,parameters:s}))));const i=r.isCallExpression(n)?n.getExpression():void 0;if(r.isCallExpression(n)&&r.isPropertyAccessExpression(i)&&i.getName()==="map"){const o=n.getArguments()[0],a=fs(i.getExpression(),ve,1)?Fg(o):ve;return Rg(o).flatMap(c=>ne(c,!0).flatMap(l=>Qe(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Lg=(e,t)=>{const s=Ig(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?Ht(n):ne(n,!0).flatMap(o=>Qe(o,!0).map(a=>({node:a,parameters:ve})))).some(({node:o,parameters:a})=>fs(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},Dg=(e,t)=>O(e,t,Lg),Mg=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:p,wranglerVariables:m,workflows:x}=s;return Rr({adminRoutes:cc(e,t),aiRawRuns:vc(e,t),aiToolSideEffects:Tc(e,t),argumentDerivedFetches:kc(e,t),argumentValidators:Yc(e,t),authApiCalls:eo(e,t),authConfigs:rl(e,t),browserUrlAccesses:ll(e,t),callEdges:n.callEdges,configCalls:vl(e,t),containerKeyAccesses:xl(e,t),containerOverrides:Pl(e,t),containers:i,countReads:Ol(e,t,f.tables),crons:o,cronTargets:o.flatMap(_=>_.functionPath===void 0?[]:[_.functionPath]),exportSinks:Ll(e,t),staleMigrationImports:jp(e,t),failOpenGuards:$l(e,t),flagReads:Wl(e,t),flagSecurityDefaults:Gl(e,t),geoIndexUsages:Xl(e,t),httpActionGuards:ld(e,t),httpHeaderWrites:xd(e,t),hyperdriveCalls:no(e,t),identityClaimReads:Od(e,t),imageDeliveryUrlAccesses:Rd(e,t),inserts:n.inserts,kvKeyAccesses:Ld(e,t,a),mailRecipientAccesses:$d(e,t),maskProcedures:io(e,t),maskStrategies:Vd(e,t),mutatorWrites:Gd(e,t),nondeterministicCalls:lo(e,t),normalizeIdAuthorizations:lu(e,t),notifyCalls:fo(e,t),notifyConfig:uo(e,t),mutators:l,ownerFieldWrites:rf(e,t,a,l),unrestrictedWhereBranches:Pg(e,t),paymentWebhooks:df(e,t),privilegedDispatches:yf(e,t),procedureProtections:ip(e,t),queries:n.queries,queues:u,r2sqlCalls:po(e,t),ratelimitKeySelectors:up(e,t),rawRowReturns:Ep(e,t),relationLoads:yp(e,t),rlsProcedures:go(e,t),schema:f,secretLiterals:Mp(e,t),modules:c,shapes:p,softDeleteReads:zp(e,t),sqlInterpolations:Up(e,t),storageKeyAccesses:Gp(e,t,a),storageUploads:eg(e,t),tableWrites:n.tableWrites,rowEffects:kp(e,t,n.tableWrites,n.callEdges),unboundedLoops:lg(e,t),vectorNamespaceAccesses:Dg(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:m})},_g=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),zg=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>_g(i))]},$g=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),Kg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",bn={error:"ERROR",info:"INFO",warn:"WARN"},Nn={ERROR:2,INFO:0,WARN:1},Bg=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"}),Vg=(e,t)=>{const{advisor:s}=Xn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(bn,n)?bn[n]:void 0;return i===void 0?[...t,Bg(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=>Kg(o)||Nn[o.level]>=Nn[i])},Ug=(e,t)=>{const{advisor:s}=Xn(e),n=zg(t,s?.accept??[]);return Vg(e,s?.acceptUnreadable===!0?[...n,$g()]:n)},Wg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},qg="crons",jg=wo.replace(/\.ts$/u,""),he=(e,t)=>`${is(e)}:${t}`,Ot=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Hg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Wg[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,...Ot("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Ot("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Ot("workflow",t.workflow,"workflow name")}))],Gg=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Yg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Gg(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Qg=e=>Hg(e).flatMap(t=>Yg(t)),Xg=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:qg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Jg=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),be=(e,t)=>t===void 0?e:{...e,module:t},Zg=e=>{const t=new Map,s=new Map,n=Jg(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(he(c.file,c.exportName),l)};for(const c of e.functions){const l=he(c.filePath,c.exportName),u=[...mo(c.filePath),c.exportName].join(".");o(be({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Me(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=he(c.filePath,c.exportName);o(be({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Me(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(be({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(be({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Me(e.modules,c.filePath)),he(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(be({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Me(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},he(jg,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}},em=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,tm=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(he(e.file,e.exportName))??{reason:em(e.exportName)},sm=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=tm(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},kt=e=>`${e.from}|${e.kind}|${e.to}`,nm=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,im=e=>{const{nodes:t,sites:s}=Zg(e),n=new Map,i=new Map;for(const o of[...Xg(e),...Qg(e)]){const a=sm(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(kt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(nm(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>kt(o).localeCompare(kt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},rm=e=>`${Jn}export const architecture = ${To(e,"Record<string, unknown>")};
24
+ `,Pn=(e,t="api")=>{const s=new Map;for(const n of e){const i=is(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new L("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},om=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Zn(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=>ei(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:$o)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)},am=(e,t,s={})=>{if(t===void 0)return;const n=om(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
25
25
  `);throw new L("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
26
26
  ${i}
27
27
 
28
- Install them with your package manager, then re-run codegen.`)},am="env.ts",cm=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return rt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},lm=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&rt(n.getModuleSpecifierValue())}return!1},dm=e=>{if(r.isIdentifier(e))return cm(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&lm(t)}return!1},um=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!dm(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw de(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=nt(s,"member");a!==void 0&&t.push({exportName:a})}return t},fm=(e,t)=>{const s=v(t,am);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=um(n);if(i.length!==0){if(i.length>1)throw de(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},pm={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},gm=new Set(["allowedHosts","deniedHosts","interceptHttps"]),mm=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},hm=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(y(s));if(!r.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),vm=new Set(["durable"]),Em=new Set(["rollback"]),Vi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},xm="defineApp",Ie="app",wn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>y(s)===Ie&&s.getInitializer()?.getText()===t)||t===Ie&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>y(s)===Ie),Sm=e=>{if(e===void 0||!Ho.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&y(e)===Ie;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return y(t)===Ie;if(r.isVariableDeclaration(t))return wn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&wn(e.getSourceFile(),s)},ym="AppBuilder",Ui=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},Am=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===ym&&s.getDeclarations().some(n=>Ui(n))},bm=e=>e.getText()===xm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Ui(t)),Wi=(e,t,s=new Set)=>{const n=tt(t);if(n===void 0||!r.isIdentifier(n))return!1;if(bm(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return Sm(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Wi(e,a.getInitializer(),s)}}return!1},qi=(e,t)=>{const s=Zt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Wi(e,s.object)||Am(s.object))},Nm=new Map([["defineContainer",{keys:gm,signal:"containerEgressPolicy"}],["defineStep",{keys:Em,signal:"workflowRollback"}],["stream",{keys:vm,signal:"durableStreams"}]]),Pm=(e,t)=>{const s=Nm.get(Vi(t));if(s!==void 0)return t.getArguments().some(n=>hm(mm(e,n),s.keys))?s.signal:void 0},wm=(e,t)=>pm[Vi(t)]??(qi(e,t)?"deliveryAuthorization":void 0),Im=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of A(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Uo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=E(o,d.CallExpression);for(const c of a){const l=Pm(o,c)??wm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>Hn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Xt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Je(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>qi(i,o))}return n},Tm=(e,t)=>{const s=Wo();for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(qo(i,s))return!0}return!1},Cm="createWorker",Om="extend",In=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Tn=e=>{const t=[],s=In(F(e,"backupCron"));s!==void 0&&t.push(s);const n=F(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=In(i.getNameNode());o!==void 0&&t.push(o)}return t},km=e=>{const t=T(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Cm)return r.isObjectLiteralExpression(s)?Tn(s):[];if(t!==Om||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=_n(s.getBody());return n===void 0?[]:Tn(n)},Rm=(e,t)=>{const s=[];for(const{filePath:n}of et(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...km(o))}return[...new Set(s)]},ji=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:ji(e.inner)},Fm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=ji(n);return i!==void 0&&t.has(i)}))},Lm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new L("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new L("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Dm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=bd(s,t),a=fm(s,t),c=wo(s,t),{queues:l,topics:u}=Yo(s,t),f=Xo(n),p=Ko(s,t);Lm(c,p);const m=Bo(s,t),x=Jo(s,t),_=Vo(s,t,c,p),K=Rm(s,t),P=Im(s,t,Go(n)),V=Qo(s,t),ee=Tm(s,t),w=jo(s,t);w.browser=w.browser||V.usesSandboxBrowser;const U=_e(n,e.target),Q=Zo(w,U,{agents:p.length>0,commitOrderedTables:i.tables.some(b=>b.commitOrdered===!0),cronTriggers:_.length>0,crossShardFanout:i.tables.some(b=>aa(b)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(b=>b.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(b=>b.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(b=>b.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:Fm(i),secretValues:ee,secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(b=>b.schedules!==void 0)}),R=Q.usage,z=$o(R),te=Q.signals.vectorStore!==!1,se=Q.signals.services===!1?[]:f,re=ti(n),oe=re??new Set,B=oe.has("lunorash");om(i,re,{hasVectors:te,scheduler:R.scheduler||_.length>0,storage:R.storage||x.rules.length>0||Object.keys(si(i)).length>0,usage:R});const k=M(v(t,"flags.ts")),W=M(v(t,"notify.ts"));return{agents:p,capabilities:z,containers:m,crons:_,dataModelContent:ua(i),declaredDependencies:re,dependencies:oe,entryCronTriggers:K,env:a,featureUsage:R,hasFlags:k,hasNotify:W,identity:o,platformGate:{...Q,diagnostics:[...ea(n,e.target),...Q.diagnostics,...ta(U,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[sa(U)]:[],...P.socketRoutes&&P.deliveryAuthorization?[na(U)]:[]]},queues:l,serverContent:la({agents:p,capabilities:z,containers:m,env:a,hasVectors:te,hasFlags:k,hasNotify:W,identity:o,queues:l,schema:i,services:se,storageRuleBuckets:x.rules.map(b=>b.bucket),topics:u,useUmbrella:B,workflows:c}),services:se,storageRulesMetadata:x,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:B,workflows:c}},Hi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Mm=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},_m=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),zm=/^[\w$]+:[\w$]+$/u,$m=(e,t)=>{const s=Bn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Cn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Km=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Cn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Jt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Cn(s):void 0}}},Bm=(e,t,s)=>({schedule:{argKeys:Km(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Vm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Kn.has(s))return $m(s,n);if((s==="runAfter"||s==="runAt")&&Mm(t)){const l=Bn(i)??(r.isStringLiteral(i)&&zm.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Bm(s,n,o)}}const a=_m.get(s),c=a===void 0?void 0:Hi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Um=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Gi=e=>Fr.isOptionalChain(e.compilerNode),Wm=(e,t)=>r.isIfStatement(t)?!N(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?N(e,t.getStatement()):r.isForStatement(t)?N(e,t.getStatement())||N(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:le(t)?t.getFirstAncestor(le)!==void 0:r.isConditionalExpression(t)?!N(e,t.getCondition()):r.isBinaryExpression(t)?!N(e,t.getLeft())&&Um.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Gi(t)?!N(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&sg(s)),qm=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&N(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(le);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&N(o.getFirstAncestor(le),i))===!0},jm=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&N(e,t.getStatement())||r.isForStatement(t)&&(N(e,t.getStatement())||N(t.getIncrementor(),e)),Hm=(e,t)=>{if(Gi(e)||t==="schedule"&&qm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Wm(s,i)){if(!jm(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},On=(e,t,s)=>{if(s===void 0)return;const n=Hm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Gm=(e,t)=>[...O(e,t,(s,n)=>On(s,n,Vm(s))),...ae(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Hi(s,"services");return On(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Ym=new Set(["boolean","number","object","string"]),Qm=e=>{const t=e.getName();if(!Ym.has(t))return;const s=e.getExpression();return X(s,["flags"])||X(s,["flags","details"])?t:void 0},Xm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Qm(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},Jm=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=Xm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},Zm=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||fa(o))return;const a=e.getSourceFile().getFilePath();if(pa(i,e,a)){const c=ga(i,e,a,0,new Set);return c===void 0&&ma(o),c}return o},eh=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Xr(t.getNameNode());return s===void 0||s==="namespace"}),th=(e,t)=>{for(const{filePath:s}of et(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of E(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||eh(a)))return i}}},sh="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",nh=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw de(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 (${sh}). 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})},ih="room:",rh="__lunora_socket__:",oh=/^[A-Za-z]\w*$/u,kn=e=>oh.test(e),ah=e=>`${e}:`.startsWith(ih)||`${e}:`.startsWith(rh),Yi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Qi=e=>Yi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),Rn=e=>y(e),ps=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&y(s)===t),fe=(e,t)=>{const s=de(e,`defineLiveStream ${t}`);return new L("LIVE_STREAM_NOT_LITERAL",s.message)},Xi=(e,t,s)=>{const n=ps(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw fe(n??e,`needs ${s} so codegen can read its topics`);if(Qi(i))throw fe(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},ch=(e,t)=>{const s=Rn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw fe(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Qi(n))throw fe(n,`cannot spread into or compute the keys of topic "${s}"`);if(!kn(s)||ah(s))throw new L("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(ps(n,"key")===void 0)return{fields:[],name:s};const a=Xi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>Rn(l)),c=a.find(l=>!kn(l));if(c!==void 0)throw new L("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},lh=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw fe(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Yi(n))throw fe(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=ps(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw fe(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Xi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:I(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>ch(a,l))}},dh=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new L("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},uh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},fh=(e,t)=>E(e,d.CallExpression).filter(s=>Hn(s,"defineLiveStream")).map(s=>{const n=uh(s),i=r.isVariableDeclaration(n)?nt(n,"binding"):void 0;if(i===void 0)throw new L("LIVE_STREAM_NOT_EXPORTED",de(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return lh(s,i,t)}),ph=(e,t)=>{const s=A(t).flatMap(n=>fh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return dh(s),s},gh=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,mh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?gh(e):!0,Ji=(e,t=!1)=>{for(const s of e.getProperties()){if(mh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Ji(n,!0))return!0}return!1},hh=(e,t)=>{for(const s of A(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of ni(n))for(const o of ns(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Ji(a)))return!0}}return!1},vh=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=qe(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=qe(a);c!==void 0&&s.push({column:c,strategy:Qn(a),table:i})}}return s},Eh=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of ni(i))for(const a of ns(o))for(const c of vh(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},xh=["providerSubscriptionId","state"],Sh=["providerEventId","processedAt"],Fn=(e,t)=>t.every(s=>s in e.shape),yh=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&&Fn(t,xh)&&Fn(s,Sh)},Ah=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],bh=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},Nh=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},Ph="@lunora/privacy",Zi="userId",Ln=new Set(["user","users"]),wh=e=>e.replaceAll("\\","/"),Ih="privacy",Th=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),ct=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ce=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",gs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Ch=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},lt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Oh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Ch(s,"tables"),i=ct(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:gs(n).map(a=>Ce(a)))t.datasets.set(o,i)},ms=8,Ee=(e,t=0)=>{if(t>ms)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Ee(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Ee(i,t+1)},kh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:Ee(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?gs(n):[],o=new Set(i.map(a=>Ce(a)));for(const a of Ah)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?ct(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ce(a)==="user"&&t.userTables.add(c))}},Dn=(e,t,s)=>{t.datasets.set(ct(e.getArguments()[0])??s,s)},Rh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ce(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},er=(e,t=0)=>{const s=Ee(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>ms)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?er(i.getExpression(),t+1):[Rh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Fh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:er(t)},Lh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Ee(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?gs(n):[])t.excluded.set(Ce(i),r.isPropertyAssignment(i)?ct(i.getInitializer())??"":"")},Dh=(e,t)=>{switch(lt(e)){case"actionCacheDataset":{Dn(e,t,"actionCache");break}case"authDataset":{kh(e,t);break}case"defineDataset":{Oh(e,t);break}case"documentHistoryDataset":{Dn(e,t,"documentHistory");break}}},hs=e=>e!==void 0&&r.isCallExpression(e)&&lt(e)==="defineDataset",tr=e=>e!==void 0&&r.isCallExpression(e)&&Th.has(lt(e)??""),Mh=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(hs(i)||tr(i))?n:void 0},sr=(e,t,s=0)=>{const n=Ee(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>ms)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!sr(i.getExpression(),t,s+1))return!1}else if(!hs(i)&&!tr(i)){const o=r.isIdentifier(i)?Mh(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},_h=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||sr(t,s)?s:void 0},zh=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if(Dh(i,t),lt(i)==="definePrivacy"){const o=Fh(i);Lh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:_h(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>hs(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},$h=(e,t)=>{const s=v(t,"schema.ts"),n=[...A(t),...M(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>wh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Kh=(e,t,s)=>{if(s?.has(Ph)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Ln};const n={datasets:new Map,excluded:new Map,userTables:new Set(Ln)},i=[],o=[];for(const f of $h(e,t)){const p=zh(f,n);i.push(...p.declared),o.push(...p.privacyCalls)}const a=new Set;for(const f of o){for(const p of f.passed??[])a.add(p);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:bh(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},nr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&nr(n,t)),Bh=(e,t)=>e.extensionKey!==Ih&&(Zi in e.shape||Object.values(e.shape).some(s=>nr(s,t))),Vh=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${Zi}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Uh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Bh(o,t.userTables)).map(o=>o.name),[n]=Nh(s,t.classifications);if(n!==void 0)throw new L("PRIVACY_COVERAGE",Vh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new L("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Wh=(e,t)=>{const s=ia(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},qh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Mn=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),jh="",Hh=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Gh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Jt.Const?t.getInitializer():void 0},Ue=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ue(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Gh(e);if(n!==void 0)return Ue(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},Yh=(e,t)=>{if(qh.has(e))return{method:e,tables:Ue(t)??[jh]}},Rt=(e,t,s)=>e===void 0?void 0:{...e,fields:Hh(t,e.method,s)},Qh=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Jt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},Xh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Qh(n);if(i!==void 0)return Mn.has(s)?Rt({method:s,tables:[i]},e,1):void 0;if($(n))return Rt(Yh(s,e.getArguments()[0]),e,2);if(Mn.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Rt({method:s,tables:[n.getName()]},e,1)},Jh=(e,t)=>O(e,t,(s,n)=>{const i=Xh(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),Zh=(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"}),ev=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||q(s,"args")===void 0)return!1}return os(e,t).opaque},tv=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ie(a);c!==void 0&&ev(a,c.receiver)&&s.push(Zh(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},sv=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...tv(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},nv=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Xe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),ir=e=>!e.isAny(),rr=e=>{const t=e.getType();if(!ir(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:nv.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},iv=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},or={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."},rv=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.`}),ov={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)."},av=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),cv={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)."},lv=(e,t,s)=>{if(!t.some(i=>Wr(i)))return ov;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return av.has(s.typeName)&&!n&&!t.some(i=>Na(i))?cv:or},ar=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:rv(u),p=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${p}`:p,title:"Procedure exists at runtime but is missing from the generated API"}},dv=(e,t,s)=>{const n=[];for(const i of Z(e)){const o=r.isIdentifier(i.getNameNode())?Lt(i):[i.getName()],c=o.some(u=>Xe(s,t,u))||!iv(i)?void 0:rr(i),[l=i.getName()]=o;c!==void 0&&n.push(ar(t,l,c,i.getStartLineNumber(),lv(i,o,c)))}return n},uv=(e,t,s)=>{if(Xe(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=rr(i.getExpression());o!==void 0&&n.push(ar(t,"default",o,i.getStartLineNumber(),or))}return n},fv=(e,t,s)=>[...dv(e,t,s),...uv(e,t,s)],pv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Lt(n).some(i=>Xe(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Lt(n).find(o=>Xe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),gv=({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"}),mv=(e,t,s)=>{const n=[],i=[];for(const a of A(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...fv(c,l,s)),i.push(...pv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!ir(a.getType()))&&n.push(gv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},hv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},vv=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Ev=(e,t)=>O(e,t,(s,n)=>hv(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:vv(s)}:void 0),cr=e=>e==="@lunora/workflow",xv=e=>new Set(e.getImportDeclarations().filter(t=>cr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),Sv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),yv=(e,t)=>{const s=qn(e,"defineWorkflowEvent",cr),n=xv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!Sv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?nt(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new L("WORKFLOW_EVENT_NOT_LITERAL",de(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:I(t,e.getFilePath()),type:l.getLiteralValue()})}return i},Av=(e,t)=>{const s=A(t).flatMap(i=>yv(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new L("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},bv=e=>{const t=Lo(e,"compatibility_date"),s=Do(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:Mo(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
29
- `},Nv=e=>`// Generated by @lunora/codegen. Do not edit.
28
+ Install them with your package manager, then re-run codegen.`)},cm="env.ts",lm=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return rt(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dm=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&rt(n.getModuleSpecifierValue())}return!1},um=e=>{if(r.isIdentifier(e))return lm(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&dm(t)}return!1},fm=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!um(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw de(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=nt(s,"member");a!==void 0&&t.push({exportName:a})}return t},pm=(e,t)=>{const s=v(t,cm);if(!M(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=fm(n);if(i.length!==0){if(i.length>1)throw de(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},gm={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},mm=new Set(["allowedHosts","deniedHosts","interceptHttps"]),hm=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},vm=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(y(s));if(!r.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Em=new Set(["durable"]),xm=new Set(["rollback"]),Vi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Sm="defineApp",Ie="app",wn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>y(s)===Ie&&s.getInitializer()?.getText()===t)||t===Ie&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>y(s)===Ie),ym=e=>{if(e===void 0||!Go.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&y(e)===Ie;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return y(t)===Ie;if(r.isVariableDeclaration(t))return wn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&wn(e.getSourceFile(),s)},Am="AppBuilder",Ui=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},bm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===Am&&s.getDeclarations().some(n=>Ui(n))},Nm=e=>e.getText()===Sm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Ui(t)),Wi=(e,t,s=new Set)=>{const n=tt(t);if(n===void 0||!r.isIdentifier(n))return!1;if(Nm(n))return!0;const i=n.getText();if(s.has(i))return!1;s.add(i);for(const o of n.getAncestors()){if(r.isParametered(o)&&o.getParameters().some(a=>a.getName()===i))return ym(o);if(r.isBlock(o)||r.isSourceFile(o)){const a=o.getVariableStatements().flatMap(c=>c.getDeclarations()).find(c=>c.getName()===i);if(a!==void 0)return Wi(e,a.getInitializer(),s)}}return!1},qi=(e,t)=>{const s=Zt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Wi(e,s.object)||bm(s.object))},Pm=new Map([["defineContainer",{keys:mm,signal:"containerEgressPolicy"}],["defineStep",{keys:xm,signal:"workflowRollback"}],["stream",{keys:Em,signal:"durableStreams"}]]),wm=(e,t)=>{const s=Pm.get(Vi(t));if(s!==void 0)return t.getArguments().some(n=>vm(hm(e,n),s.keys))?s.signal:void 0},Im=(e,t)=>gm[Vi(t)]??(qi(e,t)?"deliveryAuthorization":void 0),Tm=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of A(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Wo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=E(o,d.CallExpression);for(const c of a){const l=wm(o,c)??Im(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>Hn(c,"defineLiveStream")),Object.values(n).every(Boolean))break}if(n.typedWebSockets=n.typedWebSockets||n.socketRoutes,!n.deliveryAuthorization&&s!==void 0){const i=e.getSourceFile(s)??new Xt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Je(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>qi(i,o))}return n},Cm=(e,t)=>{const s=qo();for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(jo(i,s))return!0}return!1},Om="createWorker",km="extend",In=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Tn=e=>{const t=[],s=In(F(e,"backupCron"));s!==void 0&&t.push(s);const n=F(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=In(i.getNameNode());o!==void 0&&t.push(o)}return t},Rm=e=>{const t=T(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Om)return r.isObjectLiteralExpression(s)?Tn(s):[];if(t!==km||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=_n(s.getBody());return n===void 0?[]:Tn(n)},Fm=(e,t)=>{const s=[];for(const{filePath:n}of et(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...Rm(o))}return[...new Set(s)]},ji=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:ji(e.inner)},Lm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=ji(n);return i!==void 0&&t.has(i)}))},Dm=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new L("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new L("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Mm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=Nd(s,t),a=pm(s,t),c=Io(s,t),{queues:l,topics:u}=Qo(s,t),f=Jo(n),p=Bo(s,t);Dm(c,p);const m=Vo(s,t),x=Zo(s,t),_=Uo(s,t,c,p),K=Fm(s,t),P=Tm(s,t,Yo(n)),V=Xo(s,t),ee=Cm(s,t),w=Ho(s,t);w.browser=w.browser||V.usesSandboxBrowser;const U=_e(n,e.target),Q=ea(w,U,{agents:p.length>0,commitOrderedTables:i.tables.some(b=>b.commitOrdered===!0),cronTriggers:_.length>0,crossShardFanout:i.tables.some(b=>ca(b)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(b=>b.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(b=>b.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(b=>b.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:Lm(i),secretValues:ee,secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(b=>b.schedules!==void 0)}),R=Q.usage,z=Ko(R),te=Q.signals.vectorStore!==!1,se=Q.signals.services===!1?[]:f,re=ti(n),oe=re??new Set,B=oe.has("lunorash");am(i,re,{hasVectors:te,scheduler:R.scheduler||_.length>0,storage:R.storage||x.rules.length>0||Object.keys(si(i)).length>0,usage:R});const k=M(v(t,"flags.ts")),W=M(v(t,"notify.ts"));return{agents:p,capabilities:z,containers:m,crons:_,dataModelContent:fa(i),declaredDependencies:re,dependencies:oe,entryCronTriggers:K,env:a,featureUsage:R,hasFlags:k,hasNotify:W,identity:o,platformGate:{...Q,diagnostics:[...ta(n,e.target),...Q.diagnostics,...sa(U,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[na(U)]:[],...P.socketRoutes&&P.deliveryAuthorization?[ia(U)]:[]]},queues:l,serverContent:da({agents:p,capabilities:z,containers:m,env:a,hasVectors:te,hasFlags:k,hasNotify:W,identity:o,queues:l,schema:i,services:se,storageRuleBuckets:x.rules.map(b=>b.bucket),topics:u,useUmbrella:B,workflows:c}),services:se,storageRulesMetadata:x,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:B,workflows:c}},Hi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},_m=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},zm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),$m=/^[\w$]+:[\w$]+$/u,Km=(e,t)=>{const s=Bn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Cn=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Bm=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Cn(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Jt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Cn(s):void 0}}},Vm=(e,t,s)=>({schedule:{argKeys:Bm(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Um=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Kn.has(s))return Km(s,n);if((s==="runAfter"||s==="runAt")&&_m(t)){const l=Bn(i)??(r.isStringLiteral(i)&&$m.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...Vm(s,n,o)}}const a=zm.get(s),c=a===void 0?void 0:Hi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Wm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Gi=e=>Fr.isOptionalChain(e.compilerNode),qm=(e,t)=>r.isIfStatement(t)?!N(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?N(e,t.getStatement()):r.isForStatement(t)?N(e,t.getStatement())||N(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:le(t)?t.getFirstAncestor(le)!==void 0:r.isConditionalExpression(t)?!N(e,t.getCondition()):r.isBinaryExpression(t)?!N(e,t.getLeft())&&Wm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Gi(t)?!N(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&ng(s)),jm=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&N(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(le);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&N(o.getFirstAncestor(le),i))===!0},Hm=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&N(e,t.getStatement())||r.isForStatement(t)&&(N(e,t.getStatement())||N(t.getIncrementor(),e)),Gm=(e,t)=>{if(Gi(e)||t==="schedule"&&jm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(qm(s,i)){if(!Hm(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},On=(e,t,s)=>{if(s===void 0)return;const n=Gm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Ym=(e,t)=>[...O(e,t,(s,n)=>On(s,n,Um(s))),...ae(e,t,d.PropertyAccessExpression,(s,n)=>{const i=Hi(s,"services");return On(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Qm=new Set(["boolean","number","object","string"]),Xm=e=>{const t=e.getName();if(!Qm.has(t))return;const s=e.getExpression();return X(s,["flags"])||X(s,["flags","details"])?t:void 0},Jm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Xm(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},Zm=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=Jm(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},eh=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||pa(o))return;const a=e.getSourceFile().getFilePath();if(ga(i,e,a)){const c=ma(i,e,a,0,new Set);return c===void 0&&ha(o),c}return o},th=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Xr(t.getNameNode());return s===void 0||s==="namespace"}),sh=(e,t)=>{for(const{filePath:s}of et(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of E(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||th(a)))return i}}},nh="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",ih=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw de(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 (${nh}). 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})},rh="room:",oh="__lunora_socket__:",ah=/^[A-Za-z]\w*$/u,kn=e=>ah.test(e),ch=e=>`${e}:`.startsWith(rh)||`${e}:`.startsWith(oh),Yi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Qi=e=>Yi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),Rn=e=>y(e),ps=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&y(s)===t),fe=(e,t)=>{const s=de(e,`defineLiveStream ${t}`);return new L("LIVE_STREAM_NOT_LITERAL",s.message)},Xi=(e,t,s)=>{const n=ps(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw fe(n??e,`needs ${s} so codegen can read its topics`);if(Qi(i))throw fe(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},lh=(e,t)=>{const s=Rn(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw fe(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Qi(n))throw fe(n,`cannot spread into or compute the keys of topic "${s}"`);if(!kn(s)||ch(s))throw new L("LIVE_TOPIC_INVALID",`live stream "${e}": topic name "${s}" must be a plain identifier (letters, digits and "_", starting with a letter) that does not encode into the "room:" or socket topic prefix.`);if(ps(n,"key")===void 0)return{fields:[],name:s};const a=Xi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>Rn(l)),c=a.find(l=>!kn(l));if(c!==void 0)throw new L("LIVE_TOPIC_INVALID",`live stream "${e}": key field "${s}.${c}" must be a plain identifier (letters, digits and "_", starting with a letter).`);return{fields:a,name:s}},dh=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw fe(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Yi(n))throw fe(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=ps(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw fe(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Xi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:I(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>lh(a,l))}},uh=e=>{const t=new Map;for(const s of e)for(const[n,i]of[["id",s.id],["export",s.exportName]]){const o=`${n}:${i}`,a=t.get(o);if(a!==void 0)throw new L("LIVE_STREAM_DUPLICATE",`live stream ${n} "${i}" is declared by both lunora/${a}.ts and lunora/${s.filePath}.ts; it must be unique across the app.`);t.set(o,s.filePath)}},fh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},ph=(e,t)=>E(e,d.CallExpression).filter(s=>Hn(s,"defineLiveStream")).map(s=>{const n=fh(s),i=r.isVariableDeclaration(n)?nt(n,"binding"):void 0;if(i===void 0)throw new L("LIVE_STREAM_NOT_EXPORTED",de(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return dh(s,i,t)}),gh=(e,t)=>{const s=A(t).flatMap(n=>ph(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return uh(s),s},mh=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,hh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?mh(e):!0,Ji=(e,t=!1)=>{for(const s of e.getProperties()){if(hh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Ji(n,!0))return!0}return!1},vh=(e,t)=>{for(const s of A(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of ni(n))for(const o of ns(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Ji(a)))return!0}}return!1},Eh=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=qe(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=qe(a);c!==void 0&&s.push({column:c,strategy:Qn(a),table:i})}}return s},xh=(e,t)=>{const s=new Map;for(const n of A(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of ni(i))for(const a of ns(o))for(const c of Eh(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Sh=["providerSubscriptionId","state"],yh=["providerEventId","processedAt"],Fn=(e,t)=>t.every(s=>s in e.shape),Ah=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&&Fn(t,Sh)&&Fn(s,yh)},bh=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],Nh=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},Ph=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},wh="@lunora/privacy",Zi="userId",Ln=new Set(["user","users"]),Ih=e=>e.replaceAll("\\","/"),Th="privacy",Ch=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),ct=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ce=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",gs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Oh=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},lt=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},kh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Oh(s,"tables"),i=ct(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:gs(n).map(a=>Ce(a)))t.datasets.set(o,i)},ms=8,Ee=(e,t=0)=>{if(t>ms)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Ee(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Ee(i,t+1)},Rh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:Ee(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?gs(n):[],o=new Set(i.map(a=>Ce(a)));for(const a of bh)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?ct(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ce(a)==="user"&&t.userTables.add(c))}},Dn=(e,t,s)=>{t.datasets.set(ct(e.getArguments()[0])??s,s)},Fh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ce(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},er=(e,t=0)=>{const s=Ee(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>ms)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?er(i.getExpression(),t+1):[Fh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Lh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:er(t)},Dh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Ee(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?gs(n):[])t.excluded.set(Ce(i),r.isPropertyAssignment(i)?ct(i.getInitializer())??"":"")},Mh=(e,t)=>{switch(lt(e)){case"actionCacheDataset":{Dn(e,t,"actionCache");break}case"authDataset":{Rh(e,t);break}case"defineDataset":{kh(e,t);break}case"documentHistoryDataset":{Dn(e,t,"documentHistory");break}}},hs=e=>e!==void 0&&r.isCallExpression(e)&&lt(e)==="defineDataset",tr=e=>e!==void 0&&r.isCallExpression(e)&&Ch.has(lt(e)??""),_h=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(hs(i)||tr(i))?n:void 0},sr=(e,t,s=0)=>{const n=Ee(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>ms)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!sr(i.getExpression(),t,s+1))return!1}else if(!hs(i)&&!tr(i)){const o=r.isIdentifier(i)?_h(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},zh=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||sr(t,s)?s:void 0},$h=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if(Mh(i,t),lt(i)==="definePrivacy"){const o=Lh(i);Dh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:zh(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>hs(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Kh=(e,t)=>{const s=v(t,"schema.ts"),n=[...A(t),...M(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Ih(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Bh=(e,t,s)=>{if(s?.has(wh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Ln};const n={datasets:new Map,excluded:new Map,userTables:new Set(Ln)},i=[],o=[];for(const f of Kh(e,t)){const p=$h(f,n);i.push(...p.declared),o.push(...p.privacyCalls)}const a=new Set;for(const f of o){for(const p of f.passed??[])a.add(p);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:Nh(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},nr=(e,t)=>e.kind==="id"?t.has(e.tableName??""):[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(n=>n!==void 0&&nr(n,t)),Vh=(e,t)=>e.extensionKey!==Th&&(Zi in e.shape||Object.values(e.shape).some(s=>nr(s,t))),Uh=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (a "${Zi}" column or a v.id of a user table) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Wh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Vh(o,t.userTables)).map(o=>o.name),[n]=Ph(s,t.classifications);if(n!==void 0)throw new L("PRIVACY_COVERAGE",Uh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new L("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},qh=(e,t)=>{const s=ra(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},jh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Mn=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Hh="",Gh=(e,t,s)=>{if(t!=="patch")return;const n=e.getArguments()[s];if(n===void 0||!r.isObjectLiteralExpression(n))return;const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)&&!r.isShorthandPropertyAssignment(o))return;i.push(o.getName())}return i},Yh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Jt.Const?t.getInitializer():void 0},Ue=e=>{if(e===void 0)return;if(r.isAsExpression(e)&&e.getTypeNode()?.getText()==="const"||r.isSatisfiesExpression(e))return Ue(e.getExpression());if(r.isAsExpression(e)||r.isTypeAssertion(e))return;if(r.isStringLiteral(e))return[e.getLiteralText()];if(r.isIdentifier(e)){const n=Yh(e);if(n!==void 0)return Ue(n)}if(!r.isExpression(e))return;const t=e.getType(),s=(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getLiteralValue());return s.every(n=>typeof n=="string")?s:void 0},Qh=(e,t)=>{if(jh.has(e))return{method:e,tables:Ue(t)??[Hh]}},Rt=(e,t,s)=>e===void 0?void 0:{...e,fields:Gh(t,e.method,s)},Xh=e=>{if(!r.isIdentifier(e))return;const t=e.getSymbol()?.getDeclarations()[0];if(t===void 0||!r.isVariableDeclaration(t))return;const s=t.getInitializer();if(!(!(t.getVariableStatement()?.getDeclarationKind()===Jt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},Jh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Xh(n);if(i!==void 0)return Mn.has(s)?Rt({method:s,tables:[i]},e,1):void 0;if($(n))return Rt(Qh(s,e.getArguments()[0]),e,2);if(Mn.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Rt({method:s,tables:[n.getName()]},e,1)},Zh=(e,t)=>O(e,t,(s,n)=>{const i=Jh(s);if(i===void 0)return;const o=S(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),ev=(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"}),tv=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||q(s,"args")===void 0)return!1}return os(e,t).opaque},sv=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=ie(a);c!==void 0&&tv(a,c.receiver)&&s.push(ev(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},nv=(e,t)=>{const s=[];for(const n of A(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...sv(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},iv=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredInternalAction",{call:"internalAction.input({ … }).action(handler)"}],["RegisteredInternalMutation",{call:"internalMutation.input({ … }).mutation(handler)"}],["RegisteredInternalQuery",{call:"internalQuery.input({ … }).query(handler)"}],["RegisteredInternalStream",{call:"internalQuery.input({ … }).stream(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` or `onShardInit`. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredRoom",{call:"defineRoom({ … })",note:"A dropped room has no caller to fail — its whisper topic is never wired to a handler, so joins, messages and broadcasts are silently ignored."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWebSocket",{call:"defineWebSocket({ … })",note:"A dropped socket route has no caller to fail — its path is never recognised as an upgrade route, so connections fall through to the app router and the handler never runs."}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Xe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),ir=e=>!e.isAny(),rr=e=>{const t=e.getType();if(!ir(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:iv.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},rv=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},or={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."},ov=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.`}),av={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)."},cv=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),lv={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)."},dv=(e,t,s)=>{if(!t.some(i=>Wr(i)))return av;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return cv.has(s.typeName)&&!n&&!t.some(i=>Pa(i))?lv:or},ar=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:ov(u),p=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${p}`:p,title:"Procedure exists at runtime but is missing from the generated API"}},uv=(e,t,s)=>{const n=[];for(const i of Z(e)){const o=r.isIdentifier(i.getNameNode())?Lt(i):[i.getName()],c=o.some(u=>Xe(s,t,u))||!rv(i)?void 0:rr(i),[l=i.getName()]=o;c!==void 0&&n.push(ar(t,l,c,i.getStartLineNumber(),dv(i,o,c)))}return n},fv=(e,t,s)=>{if(Xe(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=rr(i.getExpression());o!==void 0&&n.push(ar(t,"default",o,i.getStartLineNumber(),or))}return n},pv=(e,t,s)=>[...uv(e,t,s),...fv(e,t,s)],gv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Lt(n).some(i=>Xe(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Lt(n).find(o=>Xe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),mv=({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"}),hv=(e,t,s)=>{const n=[],i=[];for(const a of A(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...pv(c,l,s)),i.push(...gv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!ir(a.getType()))&&n.push(mv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},vv=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},Ev=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},xv=(e,t)=>O(e,t,(s,n)=>vv(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:Ev(s)}:void 0),cr=e=>e==="@lunora/workflow",Sv=e=>new Set(e.getImportDeclarations().filter(t=>cr(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),yv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),Av=(e,t)=>{const s=qn(e,"defineWorkflowEvent",cr),n=Sv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!yv(o.getExpression(),s,n))continue;let a=o.getParent();for(;r.isAsExpression(a)||r.isSatisfiesExpression(a)||r.isParenthesizedExpression(a)||r.isNonNullExpression(a);)a=a.getParent();const c=r.isVariableDeclaration(a)?nt(a,"binding"):void 0;if(c===void 0)continue;const l=o.getArguments()[0];if(l===void 0||!(r.isStringLiteral(l)||r.isNoSubstitutionTemplateLiteral(l)))throw new L("WORKFLOW_EVENT_NOT_LITERAL",de(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:I(t,e.getFilePath()),type:l.getLiteralValue()})}return i},bv=(e,t)=>{const s=A(t).flatMap(i=>Av(e.getSourceFile(i)??e.addSourceFileAtPath(i),t)),n=new Map;for(const i of s){const o=n.get(i.type);if(o!==void 0)throw new L("WORKFLOW_EVENT_DUPLICATE",`workflow event type ${JSON.stringify(i.type)} is declared by both lunora/${o.filePath}.ts (${o.exportName}) and lunora/${i.filePath}.ts (${i.exportName}); it must be unique across the app.`);n.set(i.type,i)}return s.toSorted((i,o)=>i.type.localeCompare(o.type))},Nv=e=>{const t=Do(e,"compatibility_date"),s=Mo(e,"observability"),n=typeof s=="object"&&s!==null?s:{enabled:!0};return`${JSON.stringify({$schema:"node_modules/wrangler/config-schema.json",...t===void 0?{}:{compatibility_date:t},main:"src/worker.ts",name:_o(e),observability:n,preview_urls:!1,workers_dev:!1},void 0,4)}
29
+ `},Pv=e=>`// Generated by @lunora/codegen. Do not edit.
30
30
  // Serves the advisor procedure list to the app's Worker, which forwards it to a hosted Studio after the admin check.
31
31
  const PROCEDURES = ${JSON.stringify(e)};
32
32
 
@@ -45,8 +45,8 @@ export default {
45
45
  return new Response(PROCEDURES, { headers: { "Content-Type": "application/json" }, status: 200 });
46
46
  },
47
47
  };
48
- `,Pv=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":Nv(t),"wrangler.jsonc":bv(e)}:{},wv=(e,t,s)=>{for(const n of s)t[n]===void 0&&pe(v(e,n),{force:!0});for(const n of[...new Set(s.map(i=>Ze(v(e,i))))].toSorted((i,o)=>o.length-i.length))M(n)&&Yt(n).length===0&&pe(n,{recursive:!0})},Iv=(e,t)=>{for(const s of Yt(e,{recursive:!0,withFileTypes:!0})){const n=v(s.parentPath,s.name);s.isFile()&&t[Qt(e,n)]===void 0&&pe(n)}},Oe=(e,t)=>{M(e)&&Je(e,"utf8")===t||Cr(e,t,"utf8")},Tv=(e,t)=>{if(t===""){pe(e,{force:!0});return}Oe(e,t)},Cv=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){pe(s,{force:!0,recursive:!0});return}if(M(s))for(const n of Yt(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Qt(e,i)]===void 0&&pe(i)}for(const[n,i]of Object.entries(t))Gt(Ze(v(e,n)),{recursive:!0}),Oe(v(e,n),i)},Ov=(e,t,s,n)=>{const i=v(e,t);if(n!==void 0)wv(i,s,n);else if(Object.keys(s).length===0){pe(i,{force:!0,recursive:!0});return}else M(i)&&Iv(i,s);for(const[o,a]of Object.entries(s)){const c=v(i,o);Gt(Ze(c),{recursive:!0}),Oe(c,a)}},kv=e=>{try{const t=Ia(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},We=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Rv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Fv=(e,t)=>{M(e)||Gt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Oe(v(e,n.name),n.content),s.push(n.name);break}case"directory":{Ov(e,n.name,n.files,n.owned),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{Cv(e,n.files),s.push(...Object.keys(n.files));break}default:Tv(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},Lv=e=>{const t=kv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Oa({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Ra({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
49
- `,openApiModuleContent:ka(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
50
- `,openRpcModuleContent:Fa(i)}},Dv=".lunora-schema.json",Mv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},_v=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new L("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new L("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 L("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})}},zv=8,$v=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:p,useUmbrella:m,workflows:x}=e,_=()=>va(()=>{const w=so(l,a,{lazyFunctions:o}),U=co(l,a);return{functions:w,httpRoutes:Ea(l,a),mutators:U}});let{erased:K,value:{functions:P,httpRoutes:V,mutators:ee}}=_();to(A(a).map(w=>l.getSourceFileOrThrow(w)),w=>Qt(a,w.getFilePath())),Pn([...P,...ee].map(w=>w.filePath)),Pn(V.filter(w=>w.stream).map(w=>w.filePath),"http-stream");for(let w=1;;w+=1){const U=u?P:P.filter(B=>B.channel?.kind!=="room"&&B.lifecycle!=="socket"),Q=Ba({agents:t,functions:U,httpRoutes:V,mutators:ee,useUmbrella:m,workflows:x}),R={agents:t,functions:U,lazyFunctions:o,migrations:c,mutators:ee,shapes:f,useUmbrella:m,usesSandbox:p},z=Xa(R),te=Ja(R),se=Va({functions:P,useUmbrella:m}),re=v(a,"_generated",ii),oe=[[s,Q],[i,se],[n,z],...Object.entries(te).map(([B,k])=>[v(re,B),k])];if(w>=zv||oe.every(([B,k])=>Rv(l,B,k)))return{apiContent:Q,erased:K,functions:P,functionModulesContent:te,functionsContent:z,httpRoutes:V,internalContent:se,mutators:ee};for(const[B,k]of oe)We(l,B,k);({erased:K,value:{functions:P,httpRoutes:V,mutators:ee}}=_())}},Kv=e=>{const t=Mv(),s=t?At.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=So(n),o=e.lazyFunctions===!0||i,a=yo(n),c=v(n,"schema.ts");if(!M(c))throw new L("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??Fo(n);Zr(Zm);const u=Aa(l,c,e.projectRoot);Uh(u.tables,Kh(l,n,ti(e.projectRoot)));const{agents:f,capabilities:p,containers:m,crons:x,dataModelContent:_,dependencies:K,entryCronTriggers:P,env:V,featureUsage:ee,hasFlags:w,hasNotify:U,identity:Q,platformGate:R,queues:z,serverContent:te,services:se,storageRulesMetadata:re,topics:oe,usesSandbox:B,useUmbrella:k,workflows:W}=Dm({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:u,target:e.target});nh(u,u.jurisdiction===void 0?void 0:th(l,n));const b=v(n,"_generated"),lr=v(b,"dataModel.ts"),dr=v(b,"server.ts"),ur=v(b,"api.ts"),fr=v(b,"internal.ts"),pr=v(b,"functions.ts");We(l,lr,_),We(l,dr,te);const vs=Object.fromEntries(se.filter(g=>g.rpcEntrypoint!==void 0).flatMap(g=>Object.entries(da(g,b))));for(const[g,yt]of Object.entries(vs))We(l,v(b,g),yt);const ke=Sa(l,n),ue=ba(l,n),dt=R.signals.typedWebSockets!==!1,{apiContent:Es,erased:gr,functions:j,functionModulesContent:xs,functionsContent:Ss,httpRoutes:ut,internalContent:ys,mutators:ft}=$v({agents:f,apiPath:ur,generatedFunctionsPath:pr,internalPath:fr,lazyFunctions:o,roomsSupported:dt,lunoraDirectory:n,migrations:ke,project:l,shapes:ue,useUmbrella:k,usesSandbox:B,workflows:W}),As=bo(l,n),pt=No(As,u,[...j,...ut].map(g=>g.filePath)),Re=As.length>0,xe=e.lint===!1&&!Re?void 0:{callEdges:Gm(l,n),inserts:xa(l,n),queries:Us(l,n,j),tableWrites:Jh(l,n),workflowCalls:Ev(l,n)},mr=Ta(xe?.queries??Us(l,n,j)),Se=e.lint===!1||xe===void 0?void 0:Dg(l,n,{callSites:xe,containers:m,crons:x,functions:j,modules:pt,mutators:ft,queues:z,schema:u,shapes:ue,workflows:W,wranglerVariables:e.wranglerVariables}),bs=Se===void 0?[]:Vg(e.projectRoot,[...Or(Se,{source:"static"}),...mv(l,n,{byName:new Set([...W,...z,...f,...m].map(g=>g.exportName)),byPath:new Set([...j,...ft,...ue,...ke].map(g=>`${g.filePath}:${g.exportName}`))}),...sv(l,n),...ha(gr,n),...La(z,e.wranglerQueueProducers)]),hr=ya(l,n),Ns=Eh(l,n);_v(ue,Ns,hh(l,n));const vr=w?Jm(l,n):[],gt=R.signals.vectorStore!==!1,Er=ra(_e(e.projectRoot,e.target),"deliveryAuthorization"),ye=Wh(ee,{containerCount:m.length,cronCount:x.length,dependencies:K,hasPaymentTables:yh(u.tables),queueCount:z.length,storageColumnCount:Object.keys(si(u)).length,storageRuleCount:re.rules.length,vectorIndexCount:u.vectorIndexes.length,target:_e(e.projectRoot,e.target),vectorStoreSupported:gt,workflowCount:W.length}),Ps=t?At.now():0,mt=Ca(u,ke.map(g=>g.id)),ht=ph(l,n),ws=ca({advisories:bs.filter(g=>g.name!=="procedure_type_check_unavailable"),agents:f,capabilities:p,containers:m,env:V,flagKeys:vr,hasFlags:w,hasNotify:U,hasIpReaders:j.some(g=>g.readsIp===!0)||ue.some(g=>g.readsIp===!0),hasRooms:dt&&j.some(g=>g.channel?.kind==="room"),hasSensitiveArgs:f.length>0||j.some(g=>Ro(g)),hasSecretValues:R.signals.secretValues===!0,hasSockets:dt&&j.some(g=>g.lifecycle==="socket"),lazyFunctions:o,hasVectors:gt,liveStreamDeclarations:ht,liveStreams:R.signals.liveStreams===!0,maskMetadata:Ns,mutators:ft,queues:z,rlsMetadata:hr,schema:u,schemaSnapshot:mt,shapes:ue,services:se,storageRules:re,studioFeatures:ye,topics:oe,useUmbrella:k,workflowEvents:Av(l,n),workflows:W}),Is=$a(ue,K.has("@lunora/db"),k),Ts=Da(m,u.jurisdiction),Cs=Ma(W,{lazy:o}),Os=_a(f,{lazy:o}),ks=za(z,e.wranglerQueueProducers),Rs=Za(ht,k),Fs=Ua(x),xr=Wa(ye.scheduler),Fe=oa(_e(e.projectRoot,e.target)),Sr=Fe.supported?qa(k):"",yr=ja(u.tables,k,u.jurisdiction),Ar=Ao(e.projectRoot)?Ha(k):"",Ls=Ga(u.vectorIndexes),Le=Qa(u,k),Ds=Ka(K.has("@lunora/seed")),De=e.apiSpec??"openapi",vt=De==="openapi"||De==="both",br=Se?.procedureProtections??[],Nr=Se===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...br]},Et=`${JSON.stringify(Nr,void 0,2)}
51
- `,xt=De==="openrpc"||De==="both",Ms=Pa(K.has("@lunora/auth")),_s=wa({agentWorkflows:f.map(g=>g.className),capabilities:p,emailAgents:f.filter(g=>g.onEmail===!0).map(g=>({className:g.className,exportName:g.exportName})),hasAccess:K.has("@lunora/cloudflare-access"),hasAuth:K.has("@lunora/auth"),hasFramework:K.has("@lunora/astro")||K.has("@lunora/svelte")||K.has("@lunora/vue")||M(v(e.projectRoot,"src","worker.ts")),hasGlobal:u.tables.some(g=>Zn(g)),hasHyperdriveGlobal:u.tables.some(g=>ei(g)),hasKvIntrospector:ye.kv,hasNotify:U,hasQueue:z.some(g=>g.mode==="push"),liveStreams:R.signals.liveStreams===!0,liveStreamsWithheld:R.liveStreamsWithheld,liveStreamDeclarations:ht,hasAdminRevocations:Fe.supported,hasScheduler:ye.scheduler,hasSourcedTables:u.tables.some(g=>g.externalSource!==void 0),hasStorage:ye.storage,hasDeliveryAuthorization:Er,hasVectors:gt,hasWorkflow:W.length>0,identity:Q,jurisdiction:u.jurisdiction,jurisdictionPinsAuth:u.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:u.tables.map(g=>({name:g.name,shardMode:g.shardMode})),useUmbrella:k,vectorIndexCount:u.vectorIndexes.length,voiceAgents:f.filter(g=>g.voice===!0&&g.voiceBindingName!==void 0).map(g=>({bindingName:g.voiceBindingName,exportName:g.exportName})),wantsArchitecture:Re,wantsOpenApi:vt,wantsOpenRpc:xt}),{openApiContent:zs,openApiModuleContent:$s,openRpcContent:Ks,openRpcModuleContent:Bs}=Lv({functions:j,httpRoutes:ut,modules:pt,projectRoot:e.projectRoot,wantsArchitecture:Re}),Ae=Re&&xe!==void 0?nm({...xe,crons:x,functions:j,httpRoutes:ut,modules:pt,queues:z,schema:u,services:se,topics:oe,workflows:W}):void 0,St=v(n,Dv),Pr=M(St),wr=e.dryRun?[]:Fv(b,[{content:_s,kind:"always",name:"app.ts"},{content:_,kind:"always",name:"dataModel.ts"},{content:Es,kind:"always",name:"api.ts"},{content:ys,kind:"always",name:"internal.ts"},{content:te,kind:"always",name:"server.ts"},{content:Ss,kind:"always",name:"functions.ts"},{files:xs,kind:"directory",name:ii},{content:ws,kind:"always",name:"shard.ts"},{content:Fs,kind:"always",name:"crons.ts"},{content:Ls,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:Ts,kind:"optional",name:"containers.ts"},{content:Cs,kind:"optional",name:"workflows.ts"},{content:Os,kind:"optional",name:"agents.ts"},{content:ks,kind:"optional",name:"queues.ts"},{content:Rs,kind:"optional",name:"live.ts"},{content:xr,kind:"optional",name:"scheduler.ts"},{content:yr,kind:"optional",name:"shardRegistry.ts"},{content:Sr,kind:"optional",name:"adminRevocations.ts"},{content:Ar,kind:"optional",name:"durableObjects.ts"},{content:Ds,kind:"optional",name:"seed.ts"},{content:Ms,kind:"optional",name:"authModule.ts"},{content:Is,kind:"optional",name:"collections.ts"},{files:vs,kind:"services"},{files:Pv(e.projectRoot,Et,a),kind:"directory",name:"companion",owned:_o},{content:vt?zs:"",kind:"optional",name:"openapi.json"},{content:vt?$s:"",kind:"optional",name:"openapi.ts"},{content:xt?Ks:"",kind:"optional",name:"openrpc.json"},{content:xt?Bs:"",kind:"optional",name:"openrpc.ts"},{content:Et,kind:"optional",name:"advisor-procedures.json"},{content:Ae===void 0?"":`${JSON.stringify(Ae,void 0,2)}
52
- `,kind:"optional",name:"architecture.json"},{content:Ae===void 0?"":im(Ae),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!Pr&&Oe(St,kr(mt)),t){const g=At.now(),yt=Math.round(g-s),Ir=Math.round(Ps-s),Tr=Math.round(g-Ps);console.error(`@lunora/codegen: codegen took ${yt.toString()}ms (discovery ${Ir.toString()}ms, emit ${Tr.toString()}ms)`)}return{advisories:bs,advisorContext:Se,agents:f,architecture:Ae,containers:m,cronTriggers:[...new Set([...Ya(x),...P])],generated:{advisorProceduresJson:Et,agents:Os,api:Es,app:_s,authModule:Ms,collections:Is,containers:Ts,crons:Fs,dataModel:_,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:xs,functions:Ss,internal:ys,live:Rs,openApi:zs,openApiModule:$s,openRpc:Ks,openRpcModule:Bs,queues:ks,seed:Ds,server:te,shard:ws,vectors:Ls,workflows:Cs},migrations:ke,outputDirectory:b,platformDiagnostics:Fe.diagnostic===void 0?R.diagnostics:[...R.diagnostics,Fe.diagnostic],queues:z,indexReferences:mr,schemaSnapshot:mt,schemaSnapshotPath:St,schemaTables:u.tables,workflows:W,writtenFiles:wr}},rx=e=>$r(()=>Kv(e));export{Dv as SCHEMA_SNAPSHOT_FILENAME,Fo as createCodegenProject,cx as findTsconfig,lx as refreshCodegenProject,rx as runCodegen,dx as tsconfigFingerprint};
48
+ `,wv=(e,t,s)=>s?{"advisor-procedures.json":t,"src/worker.ts":Pv(t),"wrangler.jsonc":Nv(e)}:{},Iv=(e,t,s)=>{for(const n of s)t[n]===void 0&&pe(v(e,n),{force:!0});for(const n of[...new Set(s.map(i=>Ze(v(e,i))))].toSorted((i,o)=>o.length-i.length))M(n)&&Yt(n).length===0&&pe(n,{recursive:!0})},Tv=(e,t)=>{for(const s of Yt(e,{recursive:!0,withFileTypes:!0})){const n=v(s.parentPath,s.name);s.isFile()&&t[Qt(e,n)]===void 0&&pe(n)}},Oe=(e,t)=>{M(e)&&Je(e,"utf8")===t||Cr(e,t,"utf8")},Cv=(e,t)=>{if(t===""){pe(e,{force:!0});return}Oe(e,t)},Ov=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){pe(s,{force:!0,recursive:!0});return}if(M(s))for(const n of Yt(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Qt(e,i)]===void 0&&pe(i)}for(const[n,i]of Object.entries(t))Gt(Ze(v(e,n)),{recursive:!0}),Oe(v(e,n),i)},kv=(e,t,s,n)=>{const i=v(e,t);if(n!==void 0)Iv(i,s,n);else if(Object.keys(s).length===0){pe(i,{force:!0,recursive:!0});return}else M(i)&&Tv(i,s);for(const[o,a]of Object.entries(s)){const c=v(i,o);Gt(Ze(c),{recursive:!0}),Oe(c,a)}},Rv=e=>{try{const t=Ta(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},We=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Fv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Lv=(e,t)=>{M(e)||Gt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Oe(v(e,n.name),n.content),s.push(n.name);break}case"directory":{kv(e,n.name,n.files,n.owned),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{Ov(e,n.files),s.push(...Object.keys(n.files));break}default:Cv(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},Dv=e=>{const t=Rv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=ka({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Fa({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
49
+ `,openApiModuleContent:Ra(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
50
+ `,openRpcModuleContent:La(i)}},Mv=".lunora-schema.json",_v=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},zv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new L("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new L("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 L("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})}},$v=8,Kv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:p,useUmbrella:m,workflows:x}=e,_=()=>Ea(()=>{const w=so(l,a,{lazyFunctions:o}),U=co(l,a);return{functions:w,httpRoutes:xa(l,a),mutators:U}});let{erased:K,value:{functions:P,httpRoutes:V,mutators:ee}}=_();to(A(a).map(w=>l.getSourceFileOrThrow(w)),w=>Qt(a,w.getFilePath())),Pn([...P,...ee].map(w=>w.filePath)),Pn(V.filter(w=>w.stream).map(w=>w.filePath),"http-stream");for(let w=1;;w+=1){const U=u?P:P.filter(B=>B.channel?.kind!=="room"&&B.lifecycle!=="socket"),Q=Va({agents:t,functions:U,httpRoutes:V,mutators:ee,useUmbrella:m,workflows:x}),R={agents:t,functions:U,lazyFunctions:o,migrations:c,mutators:ee,shapes:f,useUmbrella:m,usesSandbox:p},z=Ja(R),te=Za(R),se=Ua({functions:P,useUmbrella:m}),re=v(a,"_generated",ii),oe=[[s,Q],[i,se],[n,z],...Object.entries(te).map(([B,k])=>[v(re,B),k])];if(w>=$v||oe.every(([B,k])=>Fv(l,B,k)))return{apiContent:Q,erased:K,functions:P,functionModulesContent:te,functionsContent:z,httpRoutes:V,internalContent:se,mutators:ee};for(const[B,k]of oe)We(l,B,k);({erased:K,value:{functions:P,httpRoutes:V,mutators:ee}}=_())}},Bv=e=>{const t=_v(),s=t?At.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=So(n),o=e.lazyFunctions===!0||i,a=yo(n),c=v(n,"schema.ts");if(!M(c))throw new L("INTERNAL",`schema.ts not found at ${c}`);const l=e.project??Lo(n);Zr(eh);const u=ba(l,c,e.projectRoot);Wh(u.tables,Bh(l,n,ti(e.projectRoot)));const{agents:f,capabilities:p,containers:m,crons:x,dataModelContent:_,dependencies:K,entryCronTriggers:P,env:V,featureUsage:ee,hasFlags:w,hasNotify:U,identity:Q,platformGate:R,queues:z,serverContent:te,services:se,storageRulesMetadata:re,topics:oe,usesSandbox:B,useUmbrella:k,workflows:W}=Mm({lunoraDirectory:n,project:l,projectRoot:e.projectRoot,schema:u,target:e.target});ih(u,u.jurisdiction===void 0?void 0:sh(l,n));const b=v(n,"_generated"),lr=v(b,"dataModel.ts"),dr=v(b,"server.ts"),ur=v(b,"api.ts"),fr=v(b,"internal.ts"),pr=v(b,"functions.ts");We(l,lr,_),We(l,dr,te);const vs=Object.fromEntries(se.filter(g=>g.rpcEntrypoint!==void 0).flatMap(g=>Object.entries(ua(g,b))));for(const[g,yt]of Object.entries(vs))We(l,v(b,g),yt);const ke=ya(l,n),ue=Na(l,n),dt=R.signals.typedWebSockets!==!1,{apiContent:Es,erased:gr,functions:j,functionModulesContent:xs,functionsContent:Ss,httpRoutes:ut,internalContent:ys,mutators:ft}=Kv({agents:f,apiPath:ur,generatedFunctionsPath:pr,internalPath:fr,lazyFunctions:o,roomsSupported:dt,lunoraDirectory:n,migrations:ke,project:l,shapes:ue,useUmbrella:k,usesSandbox:B,workflows:W}),As=No(l,n),pt=Po(As,u,[...j,...ut].map(g=>g.filePath)),Re=As.length>0,xe=e.lint===!1&&!Re?void 0:{callEdges:Ym(l,n),inserts:Sa(l,n),queries:Us(l,n,j),tableWrites:Zh(l,n),workflowCalls:xv(l,n)},mr=Ca(xe?.queries??Us(l,n,j)),Se=e.lint===!1||xe===void 0?void 0:Mg(l,n,{callSites:xe,containers:m,crons:x,functions:j,modules:pt,mutators:ft,queues:z,schema:u,shapes:ue,workflows:W,wranglerVariables:e.wranglerVariables}),bs=Se===void 0?[]:Ug(e.projectRoot,[...Or(Se,{source:"static"}),...hv(l,n,{byName:new Set([...W,...z,...f,...m].map(g=>g.exportName)),byPath:new Set([...j,...ft,...ue,...ke].map(g=>`${g.filePath}:${g.exportName}`))}),...nv(l,n),...va(gr,n),...Da(z,e.wranglerQueueProducers)]),hr=Aa(l,n),Ns=xh(l,n);zv(ue,Ns,vh(l,n));const vr=w?Zm(l,n):[],gt=R.signals.vectorStore!==!1,Er=oa(_e(e.projectRoot,e.target),"deliveryAuthorization"),ye=qh(ee,{containerCount:m.length,cronCount:x.length,dependencies:K,hasPaymentTables:Ah(u.tables),queueCount:z.length,storageColumnCount:Object.keys(si(u)).length,storageRuleCount:re.rules.length,vectorIndexCount:u.vectorIndexes.length,target:_e(e.projectRoot,e.target),vectorStoreSupported:gt,workflowCount:W.length}),Ps=t?At.now():0,mt=Oa(u,ke.map(g=>g.id)),ht=gh(l,n),ws=la({advisories:bs.filter(g=>g.name!=="procedure_type_check_unavailable"),agents:f,capabilities:p,containers:m,env:V,flagKeys:vr,hasFlags:w,hasNotify:U,hasIpReaders:j.some(g=>g.readsIp===!0)||ue.some(g=>g.readsIp===!0),hasRooms:dt&&j.some(g=>g.channel?.kind==="room"),hasSensitiveArgs:f.length>0||j.some(g=>Fo(g)),hasSecretValues:R.signals.secretValues===!0,hasSockets:dt&&j.some(g=>g.lifecycle==="socket"),lazyFunctions:o,hasVectors:gt,liveStreamDeclarations:ht,liveStreams:R.signals.liveStreams===!0,maskMetadata:Ns,mutators:ft,queues:z,rlsMetadata:hr,schema:u,schemaSnapshot:mt,shapes:ue,services:se,storageRules:re,studioFeatures:ye,topics:oe,useUmbrella:k,workflowEvents:bv(l,n),workflows:W}),Is=Ka(ue,K.has("@lunora/db"),k),Ts=Ma(m,u.jurisdiction),Cs=_a(W,{lazy:o}),Os=za(f,{lazy:o}),ks=$a(z,e.wranglerQueueProducers),Rs=ec(ht,k),Fs=Wa(x),xr=qa(ye.scheduler),Fe=aa(_e(e.projectRoot,e.target)),Sr=Fe.supported?ja(k):"",yr=Ha(u.tables,k,u.jurisdiction),Ar=Ao(e.projectRoot)?Ga(k):"",Ls=Ya(u.vectorIndexes),Le=Xa(u,k),Ds=Ba(K.has("@lunora/seed")),De=e.apiSpec??"openapi",vt=De==="openapi"||De==="both",br=Se?.procedureProtections??[],Nr=Se===void 0?{analysis:"disabled",procedures:[]}:{procedures:[...br]},Et=`${JSON.stringify(Nr,void 0,2)}
51
+ `,xt=De==="openrpc"||De==="both",Ms=wa(K.has("@lunora/auth")),_s=Ia({agentWorkflows:f.map(g=>g.className),capabilities:p,emailAgents:f.filter(g=>g.onEmail===!0).map(g=>({className:g.className,exportName:g.exportName})),hasAccess:K.has("@lunora/cloudflare-access"),hasAuth:K.has("@lunora/auth"),hasFramework:K.has("@lunora/astro")||K.has("@lunora/svelte")||K.has("@lunora/vue")||M(v(e.projectRoot,"src","worker.ts")),hasGlobal:u.tables.some(g=>Zn(g)),hasHyperdriveGlobal:u.tables.some(g=>ei(g)),hasKvIntrospector:ye.kv,hasNotify:U,hasQueue:z.some(g=>g.mode==="push"),liveStreams:R.signals.liveStreams===!0,liveStreamsWithheld:R.liveStreamsWithheld,liveStreamDeclarations:ht,hasAdminRevocations:Fe.supported,hasScheduler:ye.scheduler,hasSourcedTables:u.tables.some(g=>g.externalSource!==void 0),hasStorage:ye.storage,hasDeliveryAuthorization:Er,hasVectors:gt,hasWorkflow:W.length>0,identity:Q,jurisdiction:u.jurisdiction,jurisdictionPinsAuth:u.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:u.tables.map(g=>({name:g.name,shardMode:g.shardMode})),securityHeaders:bo(n),spaAssetsBindings:e.spaAssetsBindings,useUmbrella:k,vectorIndexCount:u.vectorIndexes.length,voiceAgents:f.filter(g=>g.voice===!0&&g.voiceBindingName!==void 0).map(g=>({bindingName:g.voiceBindingName,exportName:g.exportName})),wantsArchitecture:Re,wantsOpenApi:vt,wantsOpenRpc:xt}),{openApiContent:zs,openApiModuleContent:$s,openRpcContent:Ks,openRpcModuleContent:Bs}=Dv({functions:j,httpRoutes:ut,modules:pt,projectRoot:e.projectRoot,wantsArchitecture:Re}),Ae=Re&&xe!==void 0?im({...xe,crons:x,functions:j,httpRoutes:ut,modules:pt,queues:z,schema:u,services:se,topics:oe,workflows:W}):void 0,St=v(n,Mv),Pr=M(St),wr=e.dryRun?[]:Lv(b,[{content:_s,kind:"always",name:"app.ts"},{content:_,kind:"always",name:"dataModel.ts"},{content:Es,kind:"always",name:"api.ts"},{content:ys,kind:"always",name:"internal.ts"},{content:te,kind:"always",name:"server.ts"},{content:Ss,kind:"always",name:"functions.ts"},{files:xs,kind:"directory",name:ii},{content:ws,kind:"always",name:"shard.ts"},{content:Fs,kind:"always",name:"crons.ts"},{content:Ls,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:Ts,kind:"optional",name:"containers.ts"},{content:Cs,kind:"optional",name:"workflows.ts"},{content:Os,kind:"optional",name:"agents.ts"},{content:ks,kind:"optional",name:"queues.ts"},{content:Rs,kind:"optional",name:"live.ts"},{content:xr,kind:"optional",name:"scheduler.ts"},{content:yr,kind:"optional",name:"shardRegistry.ts"},{content:Sr,kind:"optional",name:"adminRevocations.ts"},{content:Ar,kind:"optional",name:"durableObjects.ts"},{content:Ds,kind:"optional",name:"seed.ts"},{content:Ms,kind:"optional",name:"authModule.ts"},{content:Is,kind:"optional",name:"collections.ts"},{files:vs,kind:"services"},{files:wv(e.projectRoot,Et,a),kind:"directory",name:"companion",owned:zo},{content:vt?zs:"",kind:"optional",name:"openapi.json"},{content:vt?$s:"",kind:"optional",name:"openapi.ts"},{content:xt?Ks:"",kind:"optional",name:"openrpc.json"},{content:xt?Bs:"",kind:"optional",name:"openrpc.ts"},{content:Et,kind:"optional",name:"advisor-procedures.json"},{content:Ae===void 0?"":`${JSON.stringify(Ae,void 0,2)}
52
+ `,kind:"optional",name:"architecture.json"},{content:Ae===void 0?"":rm(Ae),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!Pr&&Oe(St,kr(mt)),t){const g=At.now(),yt=Math.round(g-s),Ir=Math.round(Ps-s),Tr=Math.round(g-Ps);console.error(`@lunora/codegen: codegen took ${yt.toString()}ms (discovery ${Ir.toString()}ms, emit ${Tr.toString()}ms)`)}return{advisories:bs,advisorContext:Se,agents:f,architecture:Ae,containers:m,cronTriggers:[...new Set([...Qa(x),...P])],generated:{advisorProceduresJson:Et,agents:Os,api:Es,app:_s,authModule:Ms,collections:Is,containers:Ts,crons:Fs,dataModel:_,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:xs,functions:Ss,internal:ys,live:Rs,openApi:zs,openApiModule:$s,openRpc:Ks,openRpcModule:Bs,queues:ks,seed:Ds,server:te,shard:ws,vectors:Ls,workflows:Cs},migrations:ke,outputDirectory:b,platformDiagnostics:Fe.diagnostic===void 0?R.diagnostics:[...R.diagnostics,Fe.diagnostic],queues:z,indexReferences:mr,schemaSnapshot:mt,schemaSnapshotPath:St,schemaTables:u.tables,workflows:W,writtenFiles:wr}},ox=e=>$r(()=>Bv(e));export{Mv as SCHEMA_SNAPSHOT_FILENAME,Lo as createCodegenProject,lx as findTsconfig,dx as refreshCodegenProject,ox as runCodegen,ux as tsconfigFingerprint};