@lunora/codegen 1.0.0-alpha.390 → 1.0.0-alpha.391

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 (66) hide show
  1. package/dist/index.d.mts +1 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/AGENTS_FILENAME-BxpEvZgW.mjs +1 -0
  5. package/dist/packem_shared/{CONTAINERS_FILENAME-CtgOFZMf.mjs → CONTAINERS_FILENAME-CvPP3wR-.mjs} +1 -1
  6. package/dist/packem_shared/{DEFAULT_TARGET-DvLABulO.mjs → DEFAULT_TARGET-C0xI7Xqd.mjs} +1 -1
  7. package/dist/packem_shared/{FLAGS_FILENAME-i9gHKyNr.mjs → FLAGS_FILENAME-Ce1G6kZd.mjs} +1 -1
  8. package/dist/packem_shared/{MUTATORS_FILENAME-DTaU_N1o.mjs → MUTATORS_FILENAME-JBFlT9aD.mjs} +1 -1
  9. package/dist/packem_shared/{NOTIFY_FILENAME-Dg6s62K5.mjs → NOTIFY_FILENAME-DLGxunzB.mjs} +1 -1
  10. package/dist/packem_shared/{OPENRPC_VERSION-hSkJtQPD.mjs → OPENRPC_VERSION-CLZ5Em9J.mjs} +1 -1
  11. package/dist/packem_shared/{QUEUES_FILENAME-DtBBVCwj.mjs → QUEUES_FILENAME-2K8DSvbt.mjs} +1 -1
  12. package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-DTODZYmN.mjs → SCHEMA_SNAPSHOT_FILENAME-BAEcGpbY.mjs} +10 -10
  13. package/dist/packem_shared/{SHAPES_FILENAME-DAEL3cnz.mjs → SHAPES_FILENAME-DCqsIdQQ.mjs} +1 -1
  14. package/dist/packem_shared/{WORKFLOWS_FILENAME-B_xSNMSy.mjs → WORKFLOWS_FILENAME-Cpx5Mg0z.mjs} +1 -1
  15. package/dist/packem_shared/{attribution-CCdXKMxT.mjs → attribution-7Qs8xFmy.mjs} +1 -1
  16. package/dist/packem_shared/{buildOpenApiDocument-DpYfgUNf.mjs → buildOpenApiDocument-KKQFkA_W.mjs} +1 -1
  17. package/dist/packem_shared/{capabilitiesUsedBy-BZuA-G9k.mjs → capabilitiesUsedBy-B8KULfAq.mjs} +1 -1
  18. package/dist/packem_shared/chain-DIvP6mqw.mjs +1 -0
  19. package/dist/packem_shared/{classify-procedure-call-DhTWZ4sP.mjs → classify-procedure-call-D7XTLd8w.mjs} +1 -1
  20. package/dist/packem_shared/{context-property-calls-D_iSg9RS.mjs → context-property-calls-Dh1E4-sW.mjs} +1 -1
  21. package/dist/packem_shared/{context-root-BI-JrSoL.mjs → context-root-DHXNIvVA.mjs} +1 -1
  22. package/dist/packem_shared/{createCodegenProject-MinLDwxq.mjs → createCodegenProject-khHqIXPY.mjs} +1 -1
  23. package/dist/packem_shared/{database-calls-HTuZ7b7W.mjs → database-calls-CxJgjC_X.mjs} +1 -1
  24. package/dist/packem_shared/{discoverAuthApiCalls-CsCBaGea.mjs → discoverAuthApiCalls-D-ZsZKvv.mjs} +1 -1
  25. package/dist/packem_shared/{discoverCrons-CCFPiLK0.mjs → discoverCrons-BT_qyOt8.mjs} +1 -1
  26. package/dist/packem_shared/discoverFunctions-BIdjSX48.mjs +1 -0
  27. package/dist/packem_shared/{discoverHttpRoutes-_H-Su3XJ.mjs → discoverHttpRoutes-DOkHmHzy.mjs} +1 -1
  28. package/dist/packem_shared/discoverHyperdriveCalls-BGhSZp00.mjs +1 -0
  29. package/dist/packem_shared/{discoverInserts-BdF8QUf1.mjs → discoverInserts-d_zAWqc4.mjs} +1 -1
  30. package/dist/packem_shared/discoverMaskProcedures-CFcLOe-9.mjs +1 -0
  31. package/dist/packem_shared/{discoverMigrations-ke7Gpbg0.mjs → discoverMigrations-Dq-7Od3H.mjs} +1 -1
  32. package/dist/packem_shared/{discoverNondeterministicCalls-6NWcdr8_.mjs → discoverNondeterministicCalls-CWLdAwUM.mjs} +1 -1
  33. package/dist/packem_shared/{discoverQueries-Dc6kl3QZ.mjs → discoverQueries-Bvh__ZjJ.mjs} +1 -1
  34. package/dist/packem_shared/discoverR2sqlCalls-CexxhDRt.mjs +1 -0
  35. package/dist/packem_shared/{discoverRlsMetadata-C1Ti46me.mjs → discoverRlsMetadata-CugyqoLu.mjs} +1 -1
  36. package/dist/packem_shared/{discoverRlsProcedures-BcjBdFWE.mjs → discoverRlsProcedures-CDbsnndn.mjs} +1 -1
  37. package/dist/packem_shared/{discoverSandboxUsage-Dym6BuV1.mjs → discoverSandboxUsage-CSt29RbS.mjs} +1 -1
  38. package/dist/packem_shared/{discoverSchema-rJThzt-L.mjs → discoverSchema-DTgg8rAu.mjs} +1 -1
  39. package/dist/packem_shared/{discoverStorageRulesMetadata-Bq_vDROU.mjs → discoverStorageRulesMetadata-DTXC-pY3.mjs} +1 -1
  40. package/dist/packem_shared/{emitAgents-Dg5j1R-4.mjs → emitAgents-IN6zekRg.mjs} +1 -1
  41. package/dist/packem_shared/{emitApi-DWJW8Vu9.mjs → emitApi-Cdc8MeNK.mjs} +1 -1
  42. package/dist/packem_shared/{emitFunctions-D6n4ENZO.mjs → emitFunctions-CuhcpWAQ.mjs} +1 -1
  43. package/dist/packem_shared/{emitServer-Bo1CO-pn.mjs → emitServer-Qyj11abW.mjs} +1 -1
  44. package/dist/packem_shared/{emitShard-g-4f3Zle.mjs → emitShard--7JDasb6.mjs} +1 -1
  45. package/dist/packem_shared/{exported-procedure-chains-BzpmHl2R.mjs → exported-procedure-chains-D1wkgxKb.mjs} +1 -1
  46. package/dist/packem_shared/{fingerprintSchemaSources-Bv62Ngyi.mjs → fingerprintSchemaSources-Pmxw808S.mjs} +1 -1
  47. package/dist/packem_shared/{handler-reference-Dei0GYJa.mjs → handler-reference-HsMWpHnr.mjs} +1 -1
  48. package/dist/packem_shared/{index-B_VzW7PZ.mjs → index-DzO8JT7M.mjs} +1 -1
  49. package/dist/packem_shared/{index-BK0Qs9r5.mjs → index-VKPwR6Cj.mjs} +1 -1
  50. package/dist/packem_shared/{ip-reads-BTVU8WAU.mjs → ip-reads-CAzOWzOH.mjs} +1 -1
  51. package/dist/packem_shared/{isTestPath-2xUKz-2Q.mjs → isTestPath-DrszPMtU.mjs} +1 -1
  52. package/dist/packem_shared/loadProjectConfig-Dbux4jI3.mjs +1 -0
  53. package/dist/packem_shared/{modules-DGJgVSCo.mjs → modules-CYf6V2w7.mjs} +1 -1
  54. package/dist/packem_shared/{readServiceBindings-8keWrtfK.mjs → readServiceBindings-rDIqDBSW.mjs} +1 -1
  55. package/dist/packem_shared/{server-59fi39OH.mjs → server-Box8pDwi.mjs} +1 -1
  56. package/dist/packem_shared/{shard-D_mnxT3r.mjs → shard-CVJYK961.mjs} +1 -1
  57. package/dist/packem_shared/{shard-runtime-CHda0G1i.mjs → shard-runtime-BfamDqXW.mjs} +4 -3
  58. package/dist/packem_shared/{unwrap-handler-return-BCn5GFnn.mjs → unwrap-handler-return-X7HuBhd5.mjs} +1 -1
  59. package/package.json +2 -2
  60. package/dist/packem_shared/AGENTS_FILENAME-CfhI_lii.mjs +0 -1
  61. package/dist/packem_shared/chain-C42KAC1y.mjs +0 -1
  62. package/dist/packem_shared/discoverFunctions-DJpAD4GZ.mjs +0 -1
  63. package/dist/packem_shared/discoverHyperdriveCalls-BvIP-tzX.mjs +0 -1
  64. package/dist/packem_shared/discoverMaskProcedures-C2tDAAPH.mjs +0 -1
  65. package/dist/packem_shared/discoverR2sqlCalls-BpDBg2R3.mjs +0 -1
  66. package/dist/packem_shared/loadProjectConfig-DSh5nh1Q.mjs +0 -1
@@ -1,6 +1,6 @@
1
- import{existsSync as K,readFileSync as Je,mkdirSync as jt,writeFileSync as Nr,rmSync as Pe,readdirSync as Dn}from"node:fs";import{dirname as Ht,join as E,relative as Gt}from"node:path";import{performance as St}from"node:perf_hooks";import{runAdvisor as Pr}from"@lunora/advisor";import{LunoraError as D}from"@lunora/errors";import{serializeSchemaSnapshot as wr}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Ir}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Yt,ts as Tr,VariableDeclarationKind as Qt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as w,descendantsOfKind as x,bindingKeyName as ue,collectCallRows as O,findObjectProperty as W,collectSecurityCallRows as Cr,propertyInitializer as L,listSecurityScanFiles as Ze,objectLiteralFromCallbackBody as Mn,limitNameOf as _n,optionsObjectLiteral as zn,handlerOf as Or,collectNodeRows as ie,chainRootOf as et,outermostValueWrapper as C,isWriteTarget as tt,isSameNode as b,unwrapExpression as h,isConstDeclaration as re,memberAccessOf as Xt,returningFunctionOf as kt,walkChain as kr,RUN_METHODS as Kn,functionReferenceSegments as Rr,isTestPath as Fr,isFunctionLike as oe,functionKeyOf as $n,withSourceListMemo as Lr}from"./isTestPath-2xUKz-2Q.mjs";import{j as J,h as G,d as M,b as Jt,c as S,a as st,w as Zt,k as Dr,l as Mr,f as _r,m as zr,g as Rt,i as Kr}from"./attribution-CCdXKMxT.mjs";import{b as $s,r as At,a as Q,e as $r,m as Bn,c as nt,f as es,E as Vn,C as Un,d as Br,g as Vr,i as Ur}from"./context-root-BI-JrSoL.mjs";import{a as T,i as Wn,c as te,d as qn,e as Wr,f as qr,g as jn}from"./classify-procedure-call-DhTWZ4sP.mjs";import{a as A,s as jr}from"./property-name-7cBlgK_O.mjs";import{b as Hr,a as it}from"./module-specifiers-BctA0m_p.mjs";import{r as rt,s as Gr}from"./parse-validator-BisfC8bR.mjs";import Yr from"./discoverAuthApiCalls-CsCBaGea.mjs";import{i as $,r as Hn}from"./database-calls-HTuZ7b7W.mjs";import{i as Ft,p as Gn,w as Qr,d as Xr}from"./index-B_VzW7PZ.mjs";import Jr from"./discoverHyperdriveCalls-BvIP-tzX.mjs";import{diagnosticAt as ae}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ts,a as qe,s as Yn,d as Zr}from"./index-BK0Qs9r5.mjs";import{MUTATORS_FILENAME as eo,isDefineMutatorCallee as to,mutatorServerImplOf as so,discoverMutators as no}from"./MUTATORS_FILENAME-DTaU_N1o.mjs";import io from"./discoverNondeterministicCalls-6NWcdr8_.mjs";import{discoverNotifyConfig as ro,discoverNotifyCalls as oo}from"./NOTIFY_FILENAME-Dg6s62K5.mjs";import ao from"./discoverR2sqlCalls-BpDBg2R3.mjs";import co from"./discoverRlsProcedures-BcjBdFWE.mjs";import{s as ss,n as lo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as uo,redact as fo,isHeuristicSecretKind as go,isSecretishName as po}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Qn,readProjectLazyFunctions as mo,readMergeDurableObjects as ho}from"./loadProjectConfig-DSh5nh1Q.mjs";import{a as Me,d as vo,r as Eo}from"./modules-DGJgVSCo.mjs";import{WORKFLOWS_FILENAME as xo,discoverWorkflows as So}from"./WORKFLOWS_FILENAME-B_xSNMSy.mjs";import{r as Ao}from"./json-data-Chfs2Cz5.mjs";import{a as yo,I as bo,g as No,G as Xn,d as Po,i as wo}from"./shared-DhqnD5R3.mjs";import{createCodegenProject as Io}from"./createCodegenProject-MinLDwxq.mjs";import{findTsconfig as jE,refreshCodegenProject as HE,tsconfigFingerprint as GE}from"./createCodegenProject-MinLDwxq.mjs";import{CAPABILITIES as To,usedCapabilities as Co}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Jn,isHyperdriveGlobalTable as Zn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Oo}from"./AGENTS_FILENAME-CfhI_lii.mjs";import{discoverContainers as ko}from"./CONTAINERS_FILENAME-CtgOFZMf.mjs";import Ro from"./discoverCrons-CCFPiLK0.mjs";import{contextPropertiesRead as Fo,fileWiresRequestSecretTool as Lo,createTargetScope as Do,discoverFeatureUsage as Mo}from"./capabilitiesUsedBy-BZuA-G9k.mjs";import ei from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as _o,findProjectConfigFile as zo}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as Ko}from"./QUEUES_FILENAME-DtBBVCwj.mjs";import{discoverSandboxUsage as $o}from"./discoverSandboxUsage-Dym6BuV1.mjs";import{resolveServiceBindings as Bo}from"./readServiceBindings-8keWrtfK.mjs";import Vo from"./discoverStorageRulesMetadata-Bq_vDROU.mjs";import{resolveCodegenTarget as _e,gatePlatformFeatures as Uo,readTargetDiagnostics as Wo,vectorizeDimensionDiagnostics as qo,liveStreamsDeliveryAuthorizationDiagnostic as jo,socketRoutesDeliveryAuthorizationDiagnostic as Ho,studioPlatformFor as Go,platformFeatureAvailable as Yo,gateAdminTokenRevocation as Qo}from"./DEFAULT_TARGET-DvLABulO.mjs";import{i as Xo}from"./schema-BgM8A3XV.mjs";import{b as ti,e as Jo}from"./shard-D_mnxT3r.mjs";import{e as Zo,a as ea}from"./server-59fi39OH.mjs";import{emitDataModel as ta}from"./emitDataModel-MjAOi3KM.mjs";import{i as sa,b as na,e as ia,d as ra,f as oa,c as aa}from"./unwrap-handler-return-BCn5GFnn.mjs";import ca from"./discoverHttpRoutes-_H-Su3XJ.mjs";import la from"./discoverInserts-BdF8QUf1.mjs";import{e as si}from"./exported-procedure-chains-BzpmHl2R.mjs";import da from"./discoverMigrations-ke7Gpbg0.mjs";import Bs from"./discoverQueries-Dc6kl3QZ.mjs";import ua from"./discoverRlsMetadata-C1Ti46me.mjs";import fa from"./discoverSchema-rJThzt-L.mjs";import{discoverShapes as ga}from"./SHAPES_FILENAME-DAEL3cnz.mjs";import{i as pa}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as ma,emitApp as ha}from"./emitApp-Bz0oVnTy.mjs";import{readJsonSync as va}from"@visulima/fs";import{indexReferencesOf as Ea,buildSchemaSnapshot as xa}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as Sa,emitOpenApiModule as Aa}from"./buildOpenApiDocument-DpYfgUNf.mjs";import{buildOpenRpcDocument as ya,emitOpenRpcModule as ba}from"./OPENRPC_VERSION-hSkJtQPD.mjs";import{w as Na,u as Pa,v as wa,t as Ia,x as Ta}from"./shard-runtime-CHda0G1i.mjs";import{emitCollections as Ca,emitSeed as Oa,emitApi as ka,emitInternalApi as Ra}from"./emitApi-DWJW8Vu9.mjs";import{emitCrons as Fa,emitScheduler as La,emitAdminRevocations as Da,emitShardRegistry as Ma,emitDurableObjects as _a,emitVectors as za,emitWranglerCronTriggers as Ka}from"./emitCrons-BQjDleCe.mjs";import $a from"./emitDrizzleSchema-Dszoyymv.mjs";import{LAZY_FUNCTION_DIRECTORY as ni,emitFunctions as Ba,emitLazyFunctionModules as Va}from"./emitFunctions-D6n4ENZO.mjs";const Ua=(e,t=!1)=>{if(e.length===0)return"";const s=Po(t),n=e.map(c=>{if(yo(c.exportName,"live stream export name"),!bo.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=>{No(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const v=u.fields.map(B=>`\${encodeURIComponent(key.${B})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
1
+ import{existsSync as K,readFileSync as Je,mkdirSync as jt,writeFileSync as Pr,rmSync as we,readdirSync as Dn}from"node:fs";import{dirname as Ht,join as v,relative as Gt}from"node:path";import{performance as St}from"node:perf_hooks";import{runAdvisor as wr}from"@lunora/advisor";import{LunoraError as M}from"@lunora/errors";import{serializeSchemaSnapshot as Ir}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{toAdvisorContext as Tr}from"./formatAdvisories-BCVASH7N.mjs";import{Node as r,SyntaxKind as d,Project as Yt,ts as Cr,VariableDeclarationKind as Qt}from"ts-morph";import{listLunoraSourceFiles as y,lunoraRelativePath as T,descendantsOfKind as E,bindingKeyName as fe,collectCallRows as k,findObjectProperty as U,collectSecurityCallRows as Or,propertyInitializer as D,listSecurityScanFiles as Ze,objectLiteralFromCallbackBody as Mn,limitNameOf as _n,optionsObjectLiteral as zn,handlerOf as kr,collectNodeRows as re,chainRootOf as et,outermostValueWrapper as O,isWriteTarget as tt,isSameNode as b,unwrapExpression as h,isConstDeclaration as oe,memberAccessOf as Xt,returningFunctionOf as kt,walkChain as Rr,RUN_METHODS as Kn,functionReferenceSegments as Fr,isTestPath as Lr,isFunctionLike as ae,functionKeyOf as $n,withSourceListMemo as Dr}from"./isTestPath-DrszPMtU.mjs";import{j as J,h as G,d as _,b as Jt,c as S,a as st,w as Zt,k as Mr,l as _r,f as zr,m as Kr,g as Rt,i as $r}from"./attribution-7Qs8xFmy.mjs";import{b as $s,r as At,a as Q,e as Br,m as Bn,c as nt,f as es,E as Vn,C as Un,d as Vr,g as Ur,i as Wr}from"./context-root-DHXNIvVA.mjs";import{a as C,i as Wn,c as se,d as qn,e as qr,f as jr,g as jn}from"./classify-procedure-call-D7XTLd8w.mjs";import{a as A,s as Hr}from"./property-name-7cBlgK_O.mjs";import{b as Gr,a as it}from"./module-specifiers-BctA0m_p.mjs";import{r as rt,s as Yr}from"./parse-validator-BisfC8bR.mjs";import Qr from"./discoverAuthApiCalls-D-ZsZKvv.mjs";import{i as $,r as Hn}from"./database-calls-CxJgjC_X.mjs";import{i as Ft,p as Gn,w as Xr,d as Jr}from"./index-DzO8JT7M.mjs";import Zr from"./discoverHyperdriveCalls-BGhSZp00.mjs";import{diagnosticAt as ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as ts,a as qe,s as Yn,d as eo}from"./index-VKPwR6Cj.mjs";import{MUTATORS_FILENAME as to,isDefineMutatorCallee as so,mutatorServerImplOf as no,discoverMutators as io}from"./MUTATORS_FILENAME-JBFlT9aD.mjs";import ro from"./discoverNondeterministicCalls-CWLdAwUM.mjs";import{discoverNotifyConfig as oo,discoverNotifyCalls as ao}from"./NOTIFY_FILENAME-DLGxunzB.mjs";import co from"./discoverR2sqlCalls-CexxhDRt.mjs";import lo from"./discoverRlsProcedures-CDbsnndn.mjs";import{s as ss,n as uo}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as fo,redact as go,isHeuristicSecretKind as po,isSecretishName as mo}from"./redact-Cy14LEnc.mjs";import{readProjectConfigLiterals as Qn,readProjectLazyFunctions as ho,readMergeDurableObjects as vo}from"./loadProjectConfig-Dbux4jI3.mjs";import{a as Me,d as Eo,r as xo}from"./modules-CYf6V2w7.mjs";import{WORKFLOWS_FILENAME as So,discoverWorkflows as Ao}from"./WORKFLOWS_FILENAME-Cpx5Mg0z.mjs";import{r as yo}from"./json-data-Chfs2Cz5.mjs";import{a as bo,I as No,g as Po,G as Xn,d as wo,i as Io}from"./shared-DhqnD5R3.mjs";import{createCodegenProject as To}from"./createCodegenProject-khHqIXPY.mjs";import{findTsconfig as HE,refreshCodegenProject as GE,tsconfigFingerprint as YE}from"./createCodegenProject-khHqIXPY.mjs";import{CAPABILITIES as Co,usedCapabilities as Oo}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{isD1GlobalTable as Jn,isHyperdriveGlobalTable as Zn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as ko}from"./AGENTS_FILENAME-BxpEvZgW.mjs";import{discoverContainers as Ro}from"./CONTAINERS_FILENAME-CvPP3wR-.mjs";import Fo from"./discoverCrons-BT_qyOt8.mjs";import{contextPropertiesRead as Lo,fileWiresRequestSecretTool as Do,createTargetScope as Mo,discoverFeatureUsage as _o}from"./capabilitiesUsedBy-B8KULfAq.mjs";import ei from"./readPackageDependencies-RHhGiz0k.mjs";import{PROJECT_CONFIG_FILENAMES as zo,findProjectConfigFile as Ko}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{discoverQueueDeclarations as $o}from"./QUEUES_FILENAME-2K8DSvbt.mjs";import{discoverSandboxUsage as Bo}from"./discoverSandboxUsage-CSt29RbS.mjs";import{resolveServiceBindings as Vo}from"./readServiceBindings-rDIqDBSW.mjs";import Uo from"./discoverStorageRulesMetadata-DTXC-pY3.mjs";import{resolveCodegenTarget as _e,gatePlatformFeatures as Wo,readTargetDiagnostics as qo,vectorizeDimensionDiagnostics as jo,liveStreamsDeliveryAuthorizationDiagnostic as Ho,socketRoutesDeliveryAuthorizationDiagnostic as Go,studioPlatformFor as Yo,platformFeatureAvailable as Qo,gateAdminTokenRevocation as Xo}from"./DEFAULT_TARGET-C0xI7Xqd.mjs";import{i as Jo}from"./schema-BgM8A3XV.mjs";import{b as ti,e as Zo}from"./shard-CVJYK961.mjs";import{e as ea,a as ta}from"./server-Box8pDwi.mjs";import{emitDataModel as sa}from"./emitDataModel-MjAOi3KM.mjs";import{i as na,b as ia,e as ra,d as oa,f as aa,c as ca}from"./unwrap-handler-return-X7HuBhd5.mjs";import la from"./discoverHttpRoutes-DOkHmHzy.mjs";import da from"./discoverInserts-d_zAWqc4.mjs";import{e as si}from"./exported-procedure-chains-D1wkgxKb.mjs";import ua from"./discoverMigrations-Dq-7Od3H.mjs";import Bs from"./discoverQueries-Bvh__ZjJ.mjs";import fa from"./discoverRlsMetadata-CugyqoLu.mjs";import ga from"./discoverSchema-DTgg8rAu.mjs";import{discoverShapes as pa}from"./SHAPES_FILENAME-DCqsIdQQ.mjs";import{i as ma}from"./reserved-words-CW1QFbTd.mjs";import{emitAuthModule as ha,emitApp as va}from"./emitApp-Bz0oVnTy.mjs";import{readJsonSync as Ea}from"@visulima/fs";import{indexReferencesOf as xa,buildSchemaSnapshot as Sa}from"./SchemaSnapshotParseError-DnAuFdpl.mjs";import{buildOpenApiDocument as Aa,emitOpenApiModule as ya}from"./buildOpenApiDocument-KKQFkA_W.mjs";import{buildOpenRpcDocument as ba,emitOpenRpcModule as Na}from"./OPENRPC_VERSION-CLZ5Em9J.mjs";import{w as Pa,u as wa,v as Ia,t as Ta,x as Ca}from"./shard-runtime-BfamDqXW.mjs";import{emitCollections as Oa,emitSeed as ka,emitApi as Ra,emitInternalApi as Fa}from"./emitApi-Cdc8MeNK.mjs";import{emitCrons as La,emitScheduler as Da,emitAdminRevocations as Ma,emitShardRegistry as _a,emitDurableObjects as za,emitVectors as Ka,emitWranglerCronTriggers as $a}from"./emitCrons-BQjDleCe.mjs";import Ba from"./emitDrizzleSchema-Dszoyymv.mjs";import{LAZY_FUNCTION_DIRECTORY as ni,emitFunctions as Va,emitLazyFunctionModules as Ua}from"./emitFunctions-CuhcpWAQ.mjs";const Wa=(e,t=!1)=>{if(e.length===0)return"";const s=wo(t),n=e.map(c=>{if(bo(c.exportName,"live stream export name"),!No.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=>{Po(u.name,"live topic name");const f=`(typeof ${c.exportName}Stream)["topics"]["${u.name}"]`,g=`LiveTopicRef<LiveTopicPayload<${f}>>`,m=JSON.stringify(c.id);if(u.fields.length===0)return` ${u.name}: (): ${g} => ({ __lunoraLive: ${m}, topic: ${JSON.stringify(u.name)} }),`;const x=u.fields.map(N=>`\${encodeURIComponent(key.${N})}`).join(":");return` ${u.name}: (key: LiveTopicKey<${f}>): ${g} => ({
2
2
  __lunoraLive: ${m},
3
- topic: \`${u.name}:${v}\`,
3
+ topic: \`${u.name}:${x}\`,
4
4
  }),`});return` ${c.exportName}: {
5
5
  ${l.join(`
6
6
  `)}
@@ -18,14 +18,14 @@ export const live = {
18
18
  ${i.join(`
19
19
  `)}
20
20
  };
21
- `},ii=new Set(["delete","get","head","options","patch","post","put"]),Wa=new Set(["handler","stream"]),qa=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Vs=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),ja=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ii.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()}},Ha=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)||ii.has(n.getName()))break;s=n.getExpression()}return ja(s)},Ga=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Vs.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Vs.has(s.getText()))return!0}return!1},Ya=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Wa.has(n.getName()))return;const i=Ha(s);if(!i||!qa.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&Ga(o);return{exportName:G(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Qa=(e,t)=>{const s=[];for(const n of J(e)){const i=Ya(n,t);i&&s.push(i)}return s},Xa=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qa(i,w(t,n)))}return s},Ja=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}},Za=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)?ue(t):void 0}},ec=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&$s(a)}))return!1;const n=M(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&$s(i)},Us=(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=Ja(e);return n!==void 0&&Za(n)===t?!0:t==="args"&&ec(e)},ri=(e,t)=>r.isIdentifier(e)?Us(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Us(s,t)),tc=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},Ws=e=>{const t=r.isIdentifier(e)?M(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Jt(t)?t.getInitializer():void 0},Lt=e=>ri(e,"args"),X=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of x(s,d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},H=e=>{if(Lt(e))return!0;const t=X(e);return t!==void 0&&Lt(t)},sc=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=X(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},fe=e=>{if(At(e))return!0;const t=Ws(e);if(t!==void 0&&At(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=Ws(i);return o!==void 0&&At(o)})},ze=(e,t)=>ri(e,t),nc=(e,t)=>{if(ze(e,t))return!0;const s=X(e);if(s!==void 0&&ze(s,t))return!0;const n=tc(e);if(n!==void 0){const i=X(n);return i!==void 0&&ze(i,t)}return!1},ic=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Q(e.getExpression(),["ai"]),rc=(e,t)=>{if(!ic(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)||fe(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},oc=(e,t)=>O(e,t,rc),ac=new Set(["generateText","streamText"]),cc=new Set(["messages","prompt","system"]),lc=[{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"]}],dc=(e,t)=>lc.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),uc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[$r(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&dc(i,s));return n===void 0?void 0:`${n}.${s}`},fc=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=uc(t);if(s!==void 0)return s}},gc=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=ue(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(Lt(e))return!0;const t=gc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},mc=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!cc.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&pc(s))return!0}return!1},hc=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=T(n.getExpression());if(i===void 0||!ac.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=fc(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:mc(o)})}return s},vc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...hc(i,w(t,n)))}return s},Ec=e=>Q(e,["fetch"]),xc=(e,t)=>{if(!Ec(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Sc=(e,t)=>O(e,t,xc),ns=(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=rt(s.getExpression());return n===void 0||ns(n,t)})}finally{t.delete(e)}},Ac=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=W(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:rt(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:ns(i)}},yc=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)?rt(o):void 0;a===void 0?s=!0:(t.push(a),s||=ns(a))}n=i.getExpression()}return{objects:t,opaque:s}},is=(e,t)=>t?yc(t):Ac(e),oi=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=rt(s.getExpression());return n===void 0?[]:oi(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},bc=e=>e.flatMap(t=>oi(t,new Set)),Nc=new Set(["check","length","max"]),Dt=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(Nc.has(s.getName()))return!0;t=n}},Mt=e=>Hr(e)||e==="@lunora/values",Pc=e=>{const t=new Set(["v"]);for(const s of Wn(e,"v",Mt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Mt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},wc=(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},Ic=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Tc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Mt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),rs=(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 Ic(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Tc(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Cc=(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)},Oc=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},kc=e=>r.isReturnStatement(e)?e.getExpression():void 0,Rc=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Oc(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=kc(t);return s?[s]:[]}),ai=(e,t)=>{if(rs(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return ai(e.getExpression(),t)},Fc=(e,t)=>{const s=Cc(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Dt(e),i=new Set(Rc(s).map(o=>ai(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=rs(o,t);return a===void 0?[]:[{bounded:Dt(o)||n&&i.has(o),factory:a}]})},Lc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=rs(s,t),i=n===void 0?[]:[{bounded:Dt(s),factory:n}];return r.isCallExpression(s)?[...i,...Fc(s,t)]:i}),Dc=(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=Lc(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Mc=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=te(n);if(i?.visibility!=="public")return;const{objects:o}=is(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Dc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:G(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},_c=(e,t)=>{const s=[],n=Pc(e),i={destructured:wc(e,n),namespaces:n};for(const o of J(e)){const a=Mc(o,t,i);a&&s.push(a)}return s},zc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(..._c(i,w(t,n)))}return s},yt=e=>e?.getKind()===d.TrueKeyword,Kc=e=>e?.getKind()===d.FalseKeyword,$c=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Bc=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Vc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&T(t.getExpression())==="scim"),Uc=e=>e!==void 0&&r.isCallExpression(e)&&Bc.has(T(e.getExpression())??""),Wc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),qc=e=>{const t=L(e,"advanced"),s=L(e,"emailAndPassword"),n=L(e,"session");return{analyzable:!0,disableCsrfCheck:yt(L(t,"disableCSRFCheck")),emailPasswordEnabled:yt(L(s,"enabled")),requireEmailVerification:yt(L(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Vc(L(e,"plugins"))&&Uc(L(e,"database")),secureCookiesDisabled:Kc(L(t,"useSecureCookies")),sessionFreshAgeZero:$c(L(n,"freshAge")),trustedOriginsWildcard:Wc(L(e,"trustedOrigins"))}},jc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Hc=(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?qc(s):jc();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},Gc=(e,t)=>Cr(e,t,Hc),Yc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Bn(e.getExpression(),t.matchReceiver)?s:void 0},Qc=(e,t,s)=>{const n=Yc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!H(i)||fe(i))&&!(s.requireUnmodifiedReach===!0&&!sc(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},ot=(e,t,s)=>O(e,t,(n,i)=>Qc(n,i,s)),Xc=new Set(["content","pdf","scrape","screenshot"]),Jc=(e,t)=>ot(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Xc}),Zc=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),el=new Set(["RateLimiter"]),tl=new Set(["extend"]),qs="lunora",sl=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ci=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},_t=e=>e&&r.isObjectLiteralExpression(e)?ci(e):{analyzable:!1,presentKeys:[],trueKeys:[]},nl=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Mn(t.getBody());return s?ci(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},il=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=T(n.getExpression());i!==void 0&&(Zc.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),..._t(n.getArguments()[0])}):tl.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...nl(n.getArguments()[0])}))}for(const n of x(e,d.NewExpression)){const i=T(n.getExpression());i===void 0||!el.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),..._t(n.getArguments()[0])})}return s},rl=e=>{for(const t of sl){const s=E(e,t);if(!K(s))continue;const n=new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Je(s,"utf8")),i=[];for(const o of x(n,d.CallExpression))T(o.getExpression())===qs&&i.push({callee:qs,file:t,line:o.getStartLineNumber(),..._t(o.getArguments()[0])});return i}return[]},ol=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...il(o,n))}return s.push(...rl(Ht(t))),s},js="ctx.containers.",al=e=>{if(!e.startsWith(js))return!1;const t=e.slice(js.length);return t.length>0&&!t.includes(".")},cl=(e,t)=>ot(e,t,{argIndex:0,matchReceiver:al,methods:new Set(["get"])}),ll=new Set(["allow","deny","setAllowed"]),dl=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=W(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},ul=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!dl(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},fl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!ll.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()}},gl=(e,t)=>ul(e,t)??fl(e,t),pl=(e,t)=>O(e,t,gl),ml=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},hl=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&$(s)?1:0]},vl=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),El=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=>vl.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},xl=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return O(e,t,(i,o)=>{const a=ml(i);if(a===void 0)return;const c=El(hl(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},Sl=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Al=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Sl.has(s)?s:void 0},yl=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},bl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of x(o,d.CallExpression)){const c=Al(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?yl(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},Nl=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Pl=new Set(["dbRateLimit","rateLimit"]),wl=e=>{const t=zn(e);if(!t)return!1;const s=W(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Il=(e,t)=>{const s=T(e.getExpression());if(s===void 0)return;const n=Nl.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:wl(e.getArguments()[n]),file:t,limitName:Pl.has(s)?_n(e):"",line:e.getStartLineNumber()}},Tl=(e,t)=>O(e,t,Il),Cl=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=te(t);if(s?.kind!=="query")return;const n=Or(t,s.receiver);return n?{exportName:G(e)??e.getName(),handler:n}:void 0},Hs=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Ol=e=>{const t=Hs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Hs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},kl=(e,t)=>{const s=[];for(const n of nt(e.handler,"flags"))s.push({callee:Ol(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Rl=(e,t)=>{const s=[];for(const n of J(e)){const i=Cl(n);i&&s.push(...kl(i,t))}return s},Fl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Rl(i,w(t,n)))}return s},Ll=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Q(e.getExpression(),["flags"]),Dl=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Ml=(e,t)=>{if(!Ll(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Dl(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},_l=(e,t)=>O(e,t,Ml),zl=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Kl=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},$l=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of x(i,d.CallExpression))zl(a)&&s.push({file:o,indexName:Kl(a),line:a.getStartLineNumber()})}return s},Bl=new Set(["delete","get","head","options","patch","post","put"]),Vl=new Set(["handler","stream"]),Ul=new Set(["runAction","runMutation"]),Wl=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),we=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,li=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(ue(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Gs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:li(s,"ctx")},Ys=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:li(s,"request")},Qs=(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(Ul.has(a)&&we(c,t))return a;if(Wl.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&we(c.getExpression(),t))return`db.${a}`}},Xs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&we(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!we(n.getInitializer(),t))){for(const o of i.getElements())if(ue(o)==="auth")return!0}}return!1},ql=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,jl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&we(n.getExpression(),t)},Hl=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],di=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Hl(s)},Gl=(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)?di(t,a.getText()):[]}return[]},Yl=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=di(s,t.getText());return n.length>0?n:Gl(t,s)},Js=(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=>jl(i,t)&&Yl(i).some(o=>ql.test(o)))},Ql=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Vl.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(Bl.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Xl=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ft(e.getArguments()[0]),l=c&&Gs(c,!0);if(!c||l===void 0||Js(c,Ys(c,!0)))return;const u=Qs(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Xs(c,l),sideEffect:u}}const n=Ql(e);if(n===void 0)return;const i=Ft(e.getArguments()[0]),o=i&&Gs(i,!1);if(!i||o===void 0||Js(i,Ys(i,!1)))return;const a=Qs(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Xs(i,o),sideEffect:a}},Jl=(e,t)=>O(e,t,Xl),Zl=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ed=new Set(["append","set"]),ui=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Zs=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Zl.has(T(n.getExpression())??"")&&ze(n,t)),td=(e,t)=>{if(Zs(e,t))return!0;const s=X(e);return s!==void 0&&Zs(s,t)},zt=(e,t)=>nc(e,t)&&!td(e,t),sd=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=X(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=X(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},os=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:ui(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=je(n.getExpression());i!==void 0&&os(i,t,s)}},fi=(e,t)=>{const s=je(e);if(s===void 0)return;const n=W(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=je(n.getInitializer());i!==void 0&&os(i,"response-init",t)},nd=(e,t)=>{const s=T(e.getExpression());if(s==="Response")fi(e.getArguments()[1],t);else if(s==="Headers"){const n=je(e.getArguments()[0]);n!==void 0&&os(n,"headers-ctor",t)}},id=(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"){fi(e.getArguments()[1],t);return}if(ed.has(n)&&sd(i)){const o=e.getArguments()[1];o!==void 0&&zt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:ui(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},rd=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))nd(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))id(s,t)},od=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Ft(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 rd(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},ad=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression))s.push(...od(n,t));return s},cd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ad(i,w(t,n)))}return s},gi="identity.ts",ld=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return it(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},dd=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&&it(n.getModuleSpecifierValue())}return!1},ud=e=>{if(r.isIdentifier(e))return ld(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&dd(t)}return!1},fd=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!ud(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ae(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=st(s,"member");a!==void 0&&t.push({exportName:a})}return t},gd=(e,t)=>{const s=E(t,gi);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=fd(n);if(i.length!==0){if(i.length>1)throw ae(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"]),md="userId",hd=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},vd=(e,t)=>{const s=E(t,gi);if(!K(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)?hd(o):void 0}},en=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return pd.has(t.getText())||Q(t,["auth"])?e:void 0},Ed=e=>{if(r.isPropertyAccessExpression(e)&&en(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&en(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},tn=(e,t,s)=>{const n=Ed(e);return n===void 0?void 0:{declared:n===md||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},xd=(e,t)=>{const s=vd(e,t);return s===void 0?[]:[...ie(e,t,d.PropertyAccessExpression,(n,i)=>tn(n,i,s)),...ie(e,t,d.ElementAccessExpression,(n,i)=>tn(n,i,s))]},Sd=(e,t)=>{if(T(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=L(s,"key");if(!(!n||!H(n)||fe(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Ad=(e,t)=>O(e,t,Sd),yd=new Set(["delete","get","getRaw","getWithMetadata","put"]),bd=(e,t,s=[])=>{const n=ot(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:yd});return Zt(n,s)},Nd=new Set(["queue","send"]),sn=new Set(["bcc","cc","to"]),Pd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Nd.has(t))return;const s=e.getExpression();return Q(s,["mail"])||Q(s,["email"])?t:void 0},wd=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return sn.has(A(t))&&H(n)&&!fe(n)}if(!r.isPropertyAssignment(t)||!sn.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&H(s)&&!fe(s)}):!1,Id=(e,t)=>{const s=Pd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!wd(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},Td=(e,t)=>O(e,t,Id),Cd=(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=Yn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},Od=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;return n?.receiver?ts(n.receiver).flatMap(i=>Cd(i,G(e)??e.getName(),t)):[]},kd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...Od(a,o))}return s},Rd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},Fd=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=W(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Ld=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return to(s.getExpression())?s:void 0},Dd=e=>{const t=Ld(e),s=t===void 0?void 0:Fd(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?G(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Rd(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Md=e=>e.getVariableDeclarations().flatMap(t=>Dd(t)),_d=(e,t)=>{const s=E(t,eo);if(!K(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Md(n)},zd=new Set(["delete","get","patch"]),Kd=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),$d=new Set(["auth","identity","session","user"]),Bd=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Vd=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():""},Ud=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},Wd=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),qd=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,jd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Wd(s.getExpression(),t)&&qd(s.getThenStatement())),Hd=(e,t)=>{for(const s of x(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!zd.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}},Gd=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>es(et(s))!==void 0)),Yd=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Bd.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Qd=e=>{for(const t of x(e,d.Identifier))if(Kd.has(t.getText()))return!0;return[...$d].some(t=>nt(e,t).length>0)?!0:Gd(e)||Yd(e)},Xd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Gn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&qn(n.receiver,"use","rls"),a=Qd(i),c=new Set,l=[];for(const u of x(i,d.CallExpression)){const f=Vd(u);if(f===void 0)continue;const g=Ud(u);if(g===void 0||c.has(g)||!jd(i,g))continue;const m=Hd(i,g);m!==void 0&&(c.add(g),l.push({exportName:G(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},Jd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...Xd(a,o))}return s},pi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?M(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},Zd=e=>{const t=C(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!tt(s)},eu=e=>{const t=C(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},tu=e=>{const s=C(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!tt(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},He=e=>{const t=M(e);return t===void 0||Mr(t.getSourceFile())},Kt=(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(pi(et(o),t))return!(r.isPropertyAccessExpression(o)&&Vn.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}},Ke={kind:"opaque"},su={kind:"unreached"},nu=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},$t=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?M(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=nu(s);return i===void 0||Jt(i)?void 0:i}const n=re(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},mi=(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?Ke:c===void 0?a.some(l=>l.isRestParameter())?Ke:su:c.isRestParameter()?Ke:{kind:"parameter",parameter:c}},iu=e=>{const t=C(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=$t(s.getExpression());return n===void 0?Ke:mi(n,s,t)},ru=new Set(["__defineGetter__","__defineSetter__","__proto__"]),ou=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,hi=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=ou(s);if(n!==void 0)return b(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},au=4,vi=(e,t,s=0)=>{if(Dr(e))return!0;if(Zd(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||!ru.has(c)}if(eu(e)||tu(e)||hi(e)||Kt(e,t))return!0;const n=iu(e);return n?.kind==="unreached"||n?.kind==="parameter"&&cu(n.parameter,s+1)},nn=new WeakMap,cu=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=nn.get(e.compilerNode);if(n!==void 0)return n;if(t>au)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||M(a)?.compilerNode!==e.compilerNode||vi(a,void 0,t));return(o||t===0)&&nn.set(e.compilerNode,o),o},rn=new WeakMap,lu=(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=M(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},du=(e,t,s)=>{const{context:n,impl:i}=e,o=rn.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const m=g.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?vi(g,n):!tt(g),f=!lu(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const m=g.getText();if(m==="arguments")return!1;const v=l.get(m);return v===void 0||c.includes(g)||M(g)?.compilerNode!==v?!0:u(g)});return rn.set(i.compilerNode,f),f},on=new WeakMap,uu=e=>{let t=on.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=so(s);return n===void 0?[]:[[n.compilerNode,s]]})),on.set(e.compilerNode,t)),t},fu=e=>{const t=uu(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:G(n)??n.getName()};return a!==void 0&&du(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},bt="args",Ae=e=>{const t=Xt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===bt?t.member:void 0}if(!r.isIdentifier(e))return;const s=M(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=re(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&ue(i)===bt||r.isIdentifier(o)&&o.getText()===bt?ue(s):void 0},gu=new Set(["auth","identity","user"]),Bt=e=>{const t=i=>{const o=es(i);return o!==void 0&&o.length>0&&gu.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=X(s);return n!==void 0&&t(n)},Ei=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=Ae(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?X(n):void 0;if(o!==void 0)for(const a of Ei(o,t-1))s.add(a)}return s},$e=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[...$e(n),...$e(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=Ae(h(u)??u);return g===void 0?[]:$e(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=Ae(h(n)??n),c=Ae(h(i)??i);return a!==void 0&&Bt(i)&&o.push(a),c!==void 0&&Bt(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)&&Wr(i.getExpression(),"defineIdentityGuard")},mu=e=>{if(!pu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=Ae(h(s)??s),o=t.some((a,c)=>c!==n&&Bt(a));return i!==void 0&&o?[i]:[]})},hu=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)},vu=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),an=(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},Eu=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),xu=(e,t)=>{const s=new Set;for(const n of x(e,d.IfStatement))if(n.getEnd()<=t&&an(n,e)&&hu(n.getThenStatement()))for(const i of $e(n.getExpression()))s.add(i);for(const n of x(e,d.CallExpression))if(n.getEnd()<=t&&Eu(n)&&an(n,e))for(const i of mu(n))s.add(i);return s},Su=(e,t)=>{const s=Ei(t);if(s.size===0)return!1;const n=e.getFirstAncestor(vu);if(n===void 0)return!1;const i=xu(n,e.getStart());return[...s].every(o=>i.has(o))},Au=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),yu=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Vt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),xi=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),bu=e=>{const t=C(e),s=t.getParent();if(r.isVariableDeclaration(s))return b(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Nu=e=>{const t=bu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||re(t)?[t]:void 0:xi(t)},ye=e=>e.isUnion()?e.getUnionTypes().every(t=>ye(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>ye(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]},Pu=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&yu.get(s.getText())?.has(t.getName())===!0&&He(s)},wu=e=>{const t=kt(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,Un)?n:void 0},Iu=(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,Au,t)?n:void 0},Tu=(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},Cu=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&b(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},cn=e=>{const t=C(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&Pu(s);return Iu(s,t)??Tu(s,t)??Cu(s,t)??(n?s:wu(t))},Ou=5e4,Si=()=>({inProgress:new Set,verdicts:new Map});class ku{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Ou&&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 Ru=8,Fu=8;class Lu{budget;scope;taint;verdicts=Si();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!ye(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)?xi(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Ru?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||!ye(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=cn(o);m!==void 0;m=cn(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=C(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&ye(o.getType());if(tt(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Nu(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=C(t).getParent();if(n>=Fu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===C(t)?this.valueCompromises(i,!1,s,n+1):!Ge(i,Vt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||re(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=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,Vt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=$t(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!Kt(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(Kt(s,this.scope.context))return!1;const i=$t(t.getExpression()),o=i===void 0?void 0:mi(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)||hi(t)||b(kt(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=kt(t);return b(s,this.scope.impl)?void 0:s}}const Du=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Mu=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=M(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)},_u=new Set(["all","allSettled","any","race"]),ln=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,Nt=8;class zu{budget=new ku;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Si();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Lu(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,Nt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>_r(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=M(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=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 g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Vt.has(g.getName()))return!0;const m=a.getArguments().filter(v=>v!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(v=>this.isTaintedValue(v,!1))}const c=r.isVariableDeclaration(a)&&re(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const m=C(g),v=m.getParent();return!r.isCallExpression(v)||v.getExpression()!==m||this.isCallSiteTainted(v,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&He(i)&&_u.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0: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=M(t),i=ln(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&&Vn.has(i)?!1:i!==void 0&&Un.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Be(a)!==void 0)&&(i===void 0||!Du.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=et(i),c=r.isIdentifier(a)?ln(M(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!Mu(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=kr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(pi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?M(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=re(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=Jt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,Nt))return!1;if(this.variableDepth>=Nt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const dn=new WeakMap,Ku=e=>{const t=dn.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new zu(e);return dn.set(e.impl.compilerNode,s),s},$u=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Bu=new Set(["insert","insertManyUnsafe","patch","replace"]),Vu=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Bu.has(t)&&Br(e.getExpression())?t:void 0},Uu=(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},Wu=(e,t)=>{const s=Xt(e);return s?.member===t?h(s.object):void 0},un=(e,t)=>r.isIdentifier(e)&&M(e)?.compilerNode===t.compilerNode,Ai=(e,t,s,n=1)=>{const i=Wu(e,s);if(i!==void 0)return un(i,t);const o=r.isIdentifier(e)?M(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&ue(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||re(l)&&un(h(l.getInitializer()),t))}const a=re(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Ai(a,t,s,n-1)},Ut=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Ut(t.getWhenTrue()),...Ut(t.getWhenFalse())]:[t]},qu=(e,t,s)=>{const n=[],i=s===void 0?void 0:Ku(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!$u.has(a))continue;const l=Ut(c).filter(f=>i===void 0?H(f)&&!Vr(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&Ai(c,s.parameter,a),g=l.every(m=>Su(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},ju=(e,t,s)=>{const n=Vu(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=Uu(o,n);if(a.length===0)return[];const c=S(e),l=fu(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>qu(f,u,l))},Hu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=O(e,t,(c,l)=>ju(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Zt(o,s).map(c=>zr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},Gu=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Yu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Qu=e=>{const t=W(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?Yu(t.getInitializer()):void 0},Xu=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!Gu.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Qu(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Ju=(e,t)=>O(e,t,Xu),Zu=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),ef=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},tf=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=W(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},yi=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},bi=(e,t)=>e===t||e.startsWith(`${t}.`),Ni=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},fn=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)},Pi=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>fn(s));return r.isIdentifier(e)&&fn(e)&&t.push(e),t},sf=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},nf=e=>{const t=yi(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},rf=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:nf(e),i=new Set,o=a=>Ni(a).some(c=>n.some(l=>bi(c.getText(),l)))?!0:Pi(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 sf(a))i.add(l)}return{names:i,prefixes:n}},of=(e,t)=>Ni(e).some(s=>t.prefixes.some(n=>bi(s.getText(),n)))?!0:Pi(e).some(s=>t.names.has(s.getText())),af=e=>{const t=Rr(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},cf=(e,t,s)=>{const n=yi(e,0);if(n===void 0)return[];const i=rf(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||!of(u,i))continue;const f=af(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},lf=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=ef(n),o=i===void 0?void 0:Zu.get(i);if(o===void 0)continue;const a=tf(n,o);a!==void 0&&s.push(...cf(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},df=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lf(i,w(t,n)))}return s},gn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},pn=new Set(["account","credential","member","passkey","session","user"]),uf=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ff=e=>{const s=uf(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return pn.has(s)||pn.has(n)},gf=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}=is(e,t);return bc(s).some(i=>gf(i))?!0:n?void 0:!1},mf=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!W(t,"captcha"),usesRateLimit:!!W(t,"rateLimit")}},hf=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},vf=e=>{const t=hf(e),s=t?T(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=mf(t);return{...Ve,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in gn?{...Ve,[gn[s]]:!0}:Ve},Ef=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=vf(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},xf=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Sf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!xf.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:ff(i.getLiteralText())},Af=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),mn=new Set(["queues","scheduler","topics","workflows"]),yf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Af.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&mn.has(s.getName())&&Ur(s.getExpression()))return!0;s=s.getExpression()}const n=es(s);return n?.length===1&&mn.has(n[0]??"")},bf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},wi=new Set(["generateObject","generateText","streamObject","streamText"]),Nf=e=>{const t=T(e.getExpression());return t!==void 0&&wi.has(t)},Pf=e=>{const t=T(e.getExpression());if(t===void 0||!wi.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!W(s,"maxOutputTokens")},wf=new Set(["log","span","trace"]),If=new Set(["ai"]),Tf=new Set(["email","mail"]),Cf=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Pt=(e,t)=>[...t].some(s=>nt(e,s).length>0),Ii=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Of=new Set(["every","filter","flatMap","forEach","map","some"]),kf=new Set(["all","allSettled","race"]),Ti=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(Of.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&kf.has(n))return t},Rf=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(Ii.has(t.getKind())){const s=Ti(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Ff=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Ii.has(t.getKind())){if(t=Ti(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Lf=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(m=>{const v=m.getExpression();return r.isIdentifier(v)&&v.getText()===l&&r.isAwaitExpression(m.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Df=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}},Mf=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}},_f=e=>{let t=!1,s=!0;for(const n of[...Cf].flatMap(i=>nt(e,i))){const i=Mf(n);i&&(t=!0,!Rf(i)&&!Df(i)&&!Lf(i)&&!Ff(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},zf=e=>x(e,d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),hn="lunora-advisor-exempt",Kf=/^[\s*/]+/u,$f=/[\w-]/u,Bf=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
21
+ `},ii=new Set(["delete","get","head","options","patch","post","put"]),qa=new Set(["handler","stream"]),ja=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Vs=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Ha=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ii.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Ga=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||ii.has(n.getName()))break;s=n.getExpression()}return Ha(s)},Ya=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(Vs.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&Vs.has(s.getText()))return!0}return!1},Qa=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!qa.has(n.getName()))return;const i=Ga(s);if(!i||!ja.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&Ya(o);return{exportName:G(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Xa=(e,t)=>{const s=[];for(const n of J(e)){const i=Qa(n,t);i&&s.push(i)}return s},Ja=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Xa(i,T(t,n)))}return s},Za=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}},ec=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)?fe(t):void 0}},tc=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&$s(a)}))return!1;const n=_(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&$s(i)},Us=(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=Za(e);return n!==void 0&&ec(n)===t?!0:t==="args"&&tc(e)},ri=(e,t)=>r.isIdentifier(e)?Us(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>Us(s,t)),sc=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},Ws=e=>{const t=r.isIdentifier(e)?_(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Jt(t)?t.getInitializer():void 0},Lt=e=>ri(e,"args"),X=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},H=e=>{if(Lt(e))return!0;const t=X(e);return t!==void 0&&Lt(t)},nc=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=X(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},ge=e=>{if(At(e))return!0;const t=Ws(e);if(t!==void 0&&At(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=Ws(i);return o!==void 0&&At(o)})},ze=(e,t)=>ri(e,t),ic=(e,t)=>{if(ze(e,t))return!0;const s=X(e);if(s!==void 0&&ze(s,t))return!0;const n=sc(e);if(n!==void 0){const i=X(n);return i!==void 0&&ze(i,t)}return!1},rc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:Q(e.getExpression(),["ai"]),oc=(e,t)=>{if(!rc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)||ge(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},ac=(e,t)=>k(e,t,oc),cc=new Set(["generateText","streamText"]),lc=new Set(["messages","prompt","system"]),dc=[{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"]}],uc=(e,t)=>dc.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),fc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Br(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&uc(i,s));return n===void 0?void 0:`${n}.${s}`},gc=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=fc(t);if(s!==void 0)return s}},pc=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=fe(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},mc=e=>{if(Lt(e))return!0;const t=pc(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},hc=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!lc.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&mc(s))return!0}return!1},vc=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=C(n.getExpression());if(i===void 0||!cc.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(C(c.getExpression())==="tool"&&(a=gc(c),a!==void 0))break;a!==void 0&&s.push({scope:S(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:hc(o)})}return s},Ec=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vc(i,T(t,n)))}return s},xc=e=>Q(e,["fetch"]),Sc=(e,t)=>{if(!xc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},Ac=(e,t)=>k(e,t,Sc),ns=(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=rt(s.getExpression());return n===void 0||ns(n,t)})}finally{t.delete(e)}},yc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=U(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:rt(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:ns(i)}},bc=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)?rt(o):void 0;a===void 0?s=!0:(t.push(a),s||=ns(a))}n=i.getExpression()}return{objects:t,opaque:s}},is=(e,t)=>t?bc(t):yc(e),oi=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=rt(s.getExpression());return n===void 0?[]:oi(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},Nc=e=>e.flatMap(t=>oi(t,new Set)),Pc=new Set(["check","length","max"]),Dt=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(Pc.has(s.getName()))return!0;t=n}},Mt=e=>Gr(e)||e==="@lunora/values",wc=e=>{const t=new Set(["v"]);for(const s of Wn(e,"v",Mt))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&Mt(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Ic=(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},Tc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Cc=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&Mt(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),rs=(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 Tc(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Cc(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Oc=(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},Rc=e=>r.isReturnStatement(e)?e.getExpression():void 0,Fc=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=Rc(t);return s?[s]:[]}),ai=(e,t)=>{if(rs(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return ai(e.getExpression(),t)},Lc=(e,t)=>{const s=Oc(e.getExpression(),e.getSourceFile());if(!s)return[];const n=Dt(e),i=new Set(Fc(s).map(o=>ai(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=rs(o,t);return a===void 0?[]:[{bounded:Dt(o)||n&&i.has(o),factory:a}]})},Dc=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=rs(s,t),i=n===void 0?[]:[{bounded:Dt(s),factory:n}];return r.isCallExpression(s)?[...i,...Lc(s,t)]:i}),Mc=(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=Dc(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},_c=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=se(n);if(i?.visibility!=="public")return;const{objects:o}=is(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Mc(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:G(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},zc=(e,t)=>{const s=[],n=wc(e),i={destructured:Ic(e,n),namespaces:n};for(const o of J(e)){const a=_c(o,t,i);a&&s.push(a)}return s},Kc=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...zc(i,T(t,n)))}return s},yt=e=>e?.getKind()===d.TrueKeyword,$c=e=>e?.getKind()===d.FalseKeyword,Bc=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Vc=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Uc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&C(t.getExpression())==="scim"),Wc=e=>e!==void 0&&r.isCallExpression(e)&&Vc.has(C(e.getExpression())??""),qc=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),jc=e=>{const t=D(e,"advanced"),s=D(e,"emailAndPassword"),n=D(e,"session");return{analyzable:!0,disableCsrfCheck:yt(D(t,"disableCSRFCheck")),emailPasswordEnabled:yt(D(s,"enabled")),requireEmailVerification:yt(D(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Uc(D(e,"plugins"))&&Wc(D(e,"database")),secureCookiesDisabled:$c(D(t,"useSecureCookies")),sessionFreshAgeZero:Bc(D(n,"freshAge")),trustedOriginsWildcard:qc(D(e,"trustedOrigins"))}},Hc=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Gc=(e,t)=>{if(C(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?jc(s):Hc();return{scope:S(e),file:t,line:e.getStartLineNumber(),...i}},Yc=(e,t)=>Or(e,t,Gc),Qc=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Bn(e.getExpression(),t.matchReceiver)?s:void 0},Xc=(e,t,s)=>{const n=Qc(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!H(i)||ge(i))&&!(s.requireUnmodifiedReach===!0&&!nc(i)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:n}},ot=(e,t,s)=>k(e,t,(n,i)=>Xc(n,i,s)),Jc=new Set(["content","pdf","scrape","screenshot"]),Zc=(e,t)=>ot(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Jc}),el=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),tl=new Set(["RateLimiter"]),sl=new Set(["extend"]),qs="lunora",nl=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ci=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},_t=e=>e&&r.isObjectLiteralExpression(e)?ci(e):{analyzable:!1,presentKeys:[],trueKeys:[]},il=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&Mn(t.getBody());return s?ci(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},rl=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=C(n.getExpression());i!==void 0&&(el.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),..._t(n.getArguments()[0])}):sl.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...il(n.getArguments()[0])}))}for(const n of E(e,d.NewExpression)){const i=C(n.getExpression());i===void 0||!tl.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),..._t(n.getArguments()[0])})}return s},ol=e=>{for(const t of nl){const s=v(e,t);if(!K(s))continue;const n=new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(t,Je(s,"utf8")),i=[];for(const o of E(n,d.CallExpression))C(o.getExpression())===qs&&i.push({callee:qs,file:t,line:o.getStartLineNumber(),..._t(o.getArguments()[0])});return i}return[]},al=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...rl(o,n))}return s.push(...ol(Ht(t))),s},js="ctx.containers.",cl=e=>{if(!e.startsWith(js))return!1;const t=e.slice(js.length);return t.length>0&&!t.includes(".")},ll=(e,t)=>ot(e,t,{argIndex:0,matchReceiver:cl,methods:new Set(["get"])}),dl=new Set(["allow","deny","setAllowed"]),ul=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=U(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},fl=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!ul(e)))return{detail:"enableInternet: true",scope:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},gl=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!dl.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()}},pl=(e,t)=>fl(e,t)??gl(e,t),ml=(e,t)=>k(e,t,pl),hl=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},vl=e=>{const t=e.getExpression(),s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return e.getArguments()[s!==void 0&&$(s)?1:0]},El=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),xl=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=>El.has(n))||t.some(n=>n==="AND"||n==="OR"||n==="NOT")?void 0:t},Sl=(e,t,s)=>{const n=new Map(s.map(i=>[i.name,i.aggregateIndexed===!0]));return k(e,t,(i,o)=>{const a=hl(i);if(a===void 0)return;const c=xl(vl(i));return{file:o,indexed:n.get(a)!==!1,...c===void 0?{}:{filterFields:c},line:i.getStartLineNumber(),scope:S(i),table:a}})},Al=new Set(["defineExportSink","r2Sink","webhookExportSink"]),yl=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return Al.has(s)?s:void 0},bl=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Nl=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of E(o,d.CallExpression)){const c=yl(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?bl(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},Pl=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),wl=new Set(["dbRateLimit","rateLimit"]),Il=e=>{const t=zn(e);if(!t)return!1;const s=U(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Tl=(e,t)=>{const s=C(e.getExpression());if(s===void 0)return;const n=Pl.get(s);if(n!==void 0)return{callee:s,scope:S(e),failOpen:Il(e.getArguments()[n]),file:t,limitName:wl.has(s)?_n(e):"",line:e.getStartLineNumber()}},Cl=(e,t)=>k(e,t,Tl),Ol=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=se(t);if(s?.kind!=="query")return;const n=kr(t,s.receiver);return n?{exportName:G(e)??e.getName(),handler:n}:void 0},Hs=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},kl=e=>{const t=Hs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Hs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Rl=(e,t)=>{const s=[];for(const n of nt(e.handler,"flags"))s.push({callee:kl(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Fl=(e,t)=>{const s=[];for(const n of J(e)){const i=Ol(n);i&&s.push(...Rl(i,t))}return s},Ll=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Fl(i,T(t,n)))}return s},Dl=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:Q(e.getExpression(),["flags"]),Ml=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},_l=(e,t)=>{if(!Dl(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=Ml(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:S(e),file:t,key:i,line:e.getStartLineNumber()}},zl=(e,t)=>k(e,t,_l),Kl=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},$l=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Bl=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of E(i,d.CallExpression))Kl(a)&&s.push({file:o,indexName:$l(a),line:a.getStartLineNumber()})}return s},Vl=new Set(["delete","get","head","options","patch","post","put"]),Ul=new Set(["handler","stream"]),Wl=new Set(["runAction","runMutation"]),ql=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Ie=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,li=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(fe(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Gs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:li(s,"ctx")},Ys=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:li(s,"request")},Qs=(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(Wl.has(a)&&Ie(c,t))return a;if(ql.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Ie(c.getExpression(),t))return`db.${a}`}},Xs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Ie(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Ie(n.getInitializer(),t))){for(const o of i.getElements())if(fe(o)==="auth")return!0}}return!1},jl=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Hl=(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"&&Ie(n.getExpression(),t)},Gl=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],di=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Gl(s)},Yl=(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)?di(t,a.getText()):[]}return[]},Ql=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=di(s,t.getText());return n.length>0?n:Yl(t,s)},Js=(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=>Hl(i,t)&&Ql(i).some(o=>jl.test(o)))},Xl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Ul.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(Vl.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Jl=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ft(e.getArguments()[0]),l=c&&Gs(c,!0);if(!c||l===void 0||Js(c,Ys(c,!0)))return;const u=Qs(c,l);return u===void 0?void 0:{scope:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Xs(c,l),sideEffect:u}}const n=Xl(e);if(n===void 0)return;const i=Ft(e.getArguments()[0]),o=i&&Gs(i,!1);if(!i||o===void 0||Js(i,Ys(i,!1)))return;const a=Qs(i,o);return a===void 0?void 0:{scope:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Xs(i,o),sideEffect:a}},Zl=(e,t)=>k(e,t,Jl),ed=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),td=new Set(["append","set"]),ui=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Zs=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>ed.has(C(n.getExpression())??"")&&ze(n,t)),sd=(e,t)=>{if(Zs(e,t))return!0;const s=X(e);return s!==void 0&&Zs(s,t)},zt=(e,t)=>ic(e,t)&&!sd(e,t),nd=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=X(e);return t!==void 0&&r.isNewExpression(t)&&C(t.getExpression())==="Headers"},je=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=X(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},os=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:ui(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();zt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=je(n.getExpression());i!==void 0&&os(i,t,s)}},fi=(e,t)=>{const s=je(e);if(s===void 0)return;const n=U(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=je(n.getInitializer());i!==void 0&&os(i,"response-init",t)},id=(e,t)=>{const s=C(e.getExpression());if(s==="Response")fi(e.getArguments()[1],t);else if(s==="Headers"){const n=je(e.getArguments()[0]);n!==void 0&&os(n,"headers-ctor",t)}},rd=(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"){fi(e.getArguments()[1],t);return}if(td.has(n)&&nd(i)){const o=e.getArguments()[1];o!==void 0&&zt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:ui(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},od=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))id(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))rd(s,t)},ad=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Ft(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 od(n,{scope:S(e),relativePath:t,requestName:o.getText(),rows:a}),a},cd=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression))s.push(...ad(n,t));return s},ld=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...cd(i,T(t,n)))}return s},gi="identity.ts",dd=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return it(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},ud=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&&it(n.getModuleSpecifierValue())}return!1},fd=e=>{if(r.isIdentifier(e))return dd(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&ud(t)}return!1},gd=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!fd(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ce(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=st(s,"member");a!==void 0&&t.push({exportName:a})}return t},pd=(e,t)=>{const s=v(t,gi);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=gd(n);if(i.length!==0){if(i.length>1)throw ce(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},md=new Set(["auth","context.auth"]),hd="userId",vd=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},Ed=(e,t)=>{const s=v(t,gi);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(C(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?vd(o):void 0}},en=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return md.has(t.getText())||Q(t,["auth"])?e:void 0},xd=e=>{if(r.isPropertyAccessExpression(e)&&en(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&en(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},tn=(e,t,s)=>{const n=xd(e);return n===void 0?void 0:{declared:n===hd||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:S(e)}},Sd=(e,t)=>{const s=Ed(e,t);return s===void 0?[]:[...re(e,t,d.PropertyAccessExpression,(n,i)=>tn(n,i,s)),...re(e,t,d.ElementAccessExpression,(n,i)=>tn(n,i,s))]},Ad=(e,t)=>{if(C(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=D(s,"key");if(!(!n||!H(n)||ge(n)))return{scope:S(e),file:t,line:e.getStartLineNumber()}},yd=(e,t)=>k(e,t,Ad),bd=new Set(["delete","get","getRaw","getWithMetadata","put"]),Nd=(e,t,s=[])=>{const n=ot(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:bd});return Zt(n,s)},Pd=new Set(["queue","send"]),sn=new Set(["bcc","cc","to"]),wd=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!Pd.has(t))return;const s=e.getExpression();return Q(s,["mail"])||Q(s,["email"])?t:void 0},Id=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return sn.has(A(t))&&H(n)&&!ge(n)}if(!r.isPropertyAssignment(t)||!sn.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&H(s)&&!ge(s)}):!1,Td=(e,t)=>{const s=wd(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Id(n)))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},Cd=(e,t)=>k(e,t,Td),Od=(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=Yn(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)?se(s):void 0;return n?.receiver?ts(n.receiver).flatMap(i=>Od(i,G(e)??e.getName(),t)):[]},Rd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of J(i))s.push(...kd(a,o))}return s},Fd=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},Ld=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=U(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Dd=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return so(s.getExpression())?s:void 0},Md=e=>{const t=Dd(e),s=t===void 0?void 0:Ld(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?G(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Fd(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},_d=e=>e.getVariableDeclarations().flatMap(t=>Md(t)),zd=(e,t)=>{const s=v(t,to);if(!K(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return _d(n)},Kd=new Set(["delete","get","patch"]),$d=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Bd=new Set(["auth","identity","session","user"]),Vd=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Ud=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():""},Wd=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},qd=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),jd=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Hd=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>qd(s.getExpression(),t)&&jd(s.getThenStatement())),Gd=(e,t)=>{for(const s of E(e,d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Kd.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}},Yd=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>es(et(s))!==void 0)),Qd=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Vd.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Xd=e=>{for(const t of E(e,d.Identifier))if($d.has(t.getText()))return!0;return[...Bd].some(t=>nt(e,t).length>0)?!0:Yd(e)||Qd(e)},Jd=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=se(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Gn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&qn(n.receiver,"use","rls"),a=Xd(i),c=new Set,l=[];for(const u of E(i,d.CallExpression)){const f=Ud(u);if(f===void 0)continue;const g=Wd(u);if(g===void 0||c.has(g)||!Hd(i,g))continue;const m=Gd(i,g);m!==void 0&&(c.add(g),l.push({exportName:G(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:f,usesRls:o,visibility:n.visibility}))}return l},Zd=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of J(i))s.push(...Jd(a,o))}return s},pi=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?_(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},eu=e=>{const t=O(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!tt(s)},tu=e=>{const t=O(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},su=e=>{const s=O(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!tt(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},He=e=>{const t=_(e);return t===void 0||_r(t.getSourceFile())},Kt=(e,t)=>{const s=O(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(pi(et(o),t))return!(r.isPropertyAccessExpression(o)&&Vn.has(o.getName()))||r.isExpressionStatement(O(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!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}},Ke={kind:"opaque"},nu={kind:"unreached"},iu=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},$t=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?_(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=iu(s);return i===void 0||Jt(i)?void 0:i}const n=oe(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},mi=(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?Ke:c===void 0?a.some(l=>l.isRestParameter())?Ke:nu:c.isRestParameter()?Ke:{kind:"parameter",parameter:c}},ru=e=>{const t=O(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=$t(s.getExpression());return n===void 0?Ke:mi(n,s,t)},ou=new Set(["__defineGetter__","__defineSetter__","__proto__"]),au=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,hi=e=>{const t=O(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=au(s);if(n!==void 0)return b(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},cu=4,vi=(e,t,s=0)=>{if(Mr(e))return!0;if(eu(e)){const i=O(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!ou.has(c)}if(tu(e)||su(e)||hi(e)||Kt(e,t))return!0;const n=ru(e);return n?.kind==="unreached"||n?.kind==="parameter"&&lu(n.parameter,s+1)},nn=new WeakMap,lu=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=nn.get(e.compilerNode);if(n!==void 0)return n;if(t>cu)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||_(a)?.compilerNode!==e.compilerNode||vi(a,void 0,t));return(o||t===0)&&nn.set(e.compilerNode,o),o},rn=new WeakMap,du=(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=_(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},uu=(e,t,s)=>{const{context:n,impl:i}=e,o=rn.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const m=g.getNameNode();return r.isIdentifier(m)?[m]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?vi(g,n):!tt(g),f=!du(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const m=g.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(g)||_(g)?.compilerNode!==x?!0:u(g)});return rn.set(i.compilerNode,f),f},on=new WeakMap,fu=e=>{let t=on.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=no(s);return n===void 0?[]:[[n.compilerNode,s]]})),on.set(e.compilerNode,t)),t},gu=e=>{const t=fu(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:G(n)??n.getName()};return a!==void 0&&uu(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},bt="args",ye=e=>{const t=Xt(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===bt?t.member:void 0}if(!r.isIdentifier(e))return;const s=_(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=oe(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&fe(i)===bt||r.isIdentifier(o)&&o.getText()===bt?fe(s):void 0},pu=new Set(["auth","identity","user"]),Bt=e=>{const t=i=>{const o=es(i);return o!==void 0&&o.length>0&&pu.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=X(s);return n!==void 0&&t(n)},Ei=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=ye(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?X(n):void 0;if(o!==void 0)for(const a of Ei(o,t-1))s.add(a)}return s},$e=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[...$e(n),...$e(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=ye(h(u)??u);return g===void 0?[]:$e(f).filter(m=>m===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=ye(h(n)??n),c=ye(h(i)??i);return a!==void 0&&Bt(i)&&o.push(a),c!==void 0&&Bt(n)&&o.push(c),o},mu=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)&&qr(i.getExpression(),"defineIdentityGuard")},hu=e=>{if(!mu(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=ye(h(s)??s),o=t.some((a,c)=>c!==n&&Bt(a));return i!==void 0&&o?[i]:[]})},vu=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)},Eu=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),an=(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},xu=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),Su=(e,t)=>{const s=new Set;for(const n of E(e,d.IfStatement))if(n.getEnd()<=t&&an(n,e)&&vu(n.getThenStatement()))for(const i of $e(n.getExpression()))s.add(i);for(const n of E(e,d.CallExpression))if(n.getEnd()<=t&&xu(n)&&an(n,e))for(const i of hu(n))s.add(i);return s},Au=(e,t)=>{const s=Ei(t);if(s.size===0)return!1;const n=e.getFirstAncestor(Eu);if(n===void 0)return!1;const i=Su(n,e.getStart());return[...s].every(o=>i.has(o))},yu=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),bu=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Vt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),xi=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),Nu=e=>{const t=O(e),s=t.getParent();if(r.isVariableDeclaration(s))return b(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},Pu=e=>{const t=Nu(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||oe(t)?[t]:void 0:xi(t)},be=e=>e.isUnion()?e.getUnionTypes().every(t=>be(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>be(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]},wu=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)&&bu.get(s.getText())?.has(t.getName())===!0&&He(s)},Iu=e=>{const t=kt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=O(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Ge(n,Un)?n:void 0},Tu=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=O(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Ge(n,yu,t)?n:void 0},Cu=(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},Ou=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&b(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},cn=e=>{const t=O(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&wu(s);return Tu(s,t)??Cu(s,t)??Ou(s,t)??(n?s:Iu(t))},ku=5e4,Si=()=>({inProgress:new Set,verdicts:new Map});class Ru{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 Fu=8,Lu=8;class Du{budget;scope;taint;verdicts=Si();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!be(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)?xi(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Fu?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(O(l),!0,a,0))&&(t===n||!be(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let m=cn(o);m!==void 0;m=cn(o)){if(r.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=O(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&be(o.getType());if(tt(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=Pu(o);if(u!==void 0)return u.some(m=>n(m,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=O(t).getParent();if(n>=Lu)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===O(t)?this.valueCompromises(i,!1,s,n+1):!Ge(i,Vt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||oe(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=O(c),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,Vt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=$t(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!Kt(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(Kt(s,this.scope.context))return!1;const i=$t(t.getExpression()),o=i===void 0?void 0:mi(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)||hi(t)||b(kt(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=kt(t);return b(s,this.scope.impl)?void 0:s}}const Mu=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),_u=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=_(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)},zu=new Set(["all","allSettled","any","race"]),ln=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,Nt=8;class Ku{budget=new Ru;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Si();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Du(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,Nt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>zr(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=_(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=O(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Vt.has(g.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(g.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&oe(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const m=O(g),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)&&zu.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0: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=_(t),i=ln(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&&Vn.has(i)?!1:i!==void 0&&Un.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Be(a)!==void 0)&&(i===void 0||!Mu.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=et(i),c=r.isIdentifier(a)?ln(_(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!_u(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=Rr(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(pi(i,this.scope.context))return!0;const o=r.isIdentifier(i)?_(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=oe(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=Jt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,Nt))return!1;if(this.variableDepth>=Nt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const dn=new WeakMap,$u=e=>{const t=dn.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Ku(e);return dn.set(e.impl.compilerNode,s),s},Bu=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Vu=new Set(["insert","insertManyUnsafe","patch","replace"]),Uu=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Vu.has(t)&&Vr(e.getExpression())?t:void 0},Wu=(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},qu=(e,t)=>{const s=Xt(e);return s?.member===t?h(s.object):void 0},un=(e,t)=>r.isIdentifier(e)&&_(e)?.compilerNode===t.compilerNode,Ai=(e,t,s,n=1)=>{const i=qu(e,s);if(i!==void 0)return un(i,t);const o=r.isIdentifier(e)?_(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&fe(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||oe(l)&&un(h(l.getInitializer()),t))}const a=oe(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Ai(a,t,s,n-1)},Ut=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Ut(t.getWhenTrue()),...Ut(t.getWhenFalse())]:[t]},ju=(e,t,s)=>{const n=[],i=s===void 0?void 0:$u(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!Bu.has(a))continue;const l=Ut(c).filter(f=>i===void 0?H(f)&&!Ur(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&Ai(c,s.parameter,a),g=l.every(m=>Au(t.call,m));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Hu=(e,t,s)=>{const n=Uu(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=Wu(o,n);if(a.length===0)return[];const c=S(e),l=gu(e),u={call:e,method:n,ownerField:l===void 0?void 0:s(l.mutatorName),relativePath:t,scope:c};return a.flatMap(f=>ju(f,u,l))},Gu=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=k(e,t,(c,l)=>Hu(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Zt(o,s).map(c=>Kr(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},Yu=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Qu=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Xu=e=>{const t=U(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?Qu(t.getInitializer()):void 0},Ju=(e,t)=>{const s=C(e.getExpression());if(s===void 0||!Yu.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Xu(n):void 0;return{callee:s,scope:S(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Zu=(e,t)=>k(e,t,Ju),ef=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),tf=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},sf=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=U(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},yi=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},bi=(e,t)=>e===t||e.startsWith(`${t}.`),Ni=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},fn=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)},Pi=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>fn(s));return r.isIdentifier(e)&&fn(e)&&t.push(e),t},nf=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},rf=e=>{const t=yi(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},of=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:rf(e),i=new Set,o=a=>Ni(a).some(c=>n.some(l=>bi(c.getText(),l)))?!0:Pi(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 nf(a))i.add(l)}return{names:i,prefixes:n}},af=(e,t)=>Ni(e).some(s=>t.prefixes.some(n=>bi(s.getText(),n)))?!0:Pi(e).some(s=>t.names.has(s.getText())),cf=e=>{const t=Fr(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},lf=(e,t,s)=>{const n=yi(e,0);if(n===void 0)return[];const i=of(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||!af(u,i))continue;const f=cf(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},df=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=tf(n),o=i===void 0?void 0:ef.get(i);if(o===void 0)continue;const a=sf(n,o);a!==void 0&&s.push(...lf(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},uf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...df(i,T(t,n)))}return s},gn={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},pn=new Set(["account","credential","member","passkey","session","user"]),ff=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),gf=e=>{const s=ff(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return pn.has(s)||pn.has(n)},pf=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},mf=(e,t)=>{const{objects:s,opaque:n}=is(e,t);return Nc(s).some(i=>pf(i))?!0:n?void 0:!1},hf=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!U(t,"captcha"),usesRateLimit:!!U(t,"rateLimit")}},vf=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},Ef=e=>{const t=vf(e),s=t?C(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=hf(t);return{...Ve,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in gn?{...Ve,[gn[s]]:!0}:Ve},xf=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=Ef(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},Sf=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Af=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Sf.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:gf(i.getLiteralText())},yf=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),mn=new Set(["queues","scheduler","topics","workflows"]),bf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!yf.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&mn.has(s.getName())&&Wr(s.getExpression()))return!0;s=s.getExpression()}const n=es(s);return n?.length===1&&mn.has(n[0]??"")},Nf=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},wi=new Set(["generateObject","generateText","streamObject","streamText"]),Pf=e=>{const t=C(e.getExpression());return t!==void 0&&wi.has(t)},wf=e=>{const t=C(e.getExpression());if(t===void 0||!wi.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!U(s,"maxOutputTokens")},If=new Set(["log","span","trace"]),Tf=new Set(["ai"]),Cf=new Set(["email","mail"]),Of=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),Pt=(e,t)=>[...t].some(s=>nt(e,s).length>0),Ii=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),kf=new Set(["every","filter","flatMap","forEach","map","some"]),Rf=new Set(["all","allSettled","race"]),Ti=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"&&Rf.has(n))return t},Ff=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(Ii.has(t.getKind())){const s=Ti(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Lf=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Ii.has(t.getKind())){if(t=Ti(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Df=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())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Mf=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}},_f=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}},zf=e=>{let t=!1,s=!0;for(const n of[...Of].flatMap(i=>nt(e,i))){const i=_f(n);i&&(t=!0,!Ff(i)&&!Mf(i)&&!Df(i)&&!Lf(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Kf=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"}),hn="lunora-advisor-exempt",$f=/^[\s*/]+/u,Bf=/[\w-]/u,Vf=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(Kf,"");if(!i.startsWith(hn))continue;const o=i.slice(hn.length);if($f.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:""}},Vf=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=W(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Uf=(e,t)=>{const s=Vf(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)},Wf=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of x(e,d.CallExpression))if(Sf(l)&&(o=!0),yf(l)&&(t=!0),bf(l)&&(i=!0),Nf(l)&&(s=!0),Pf(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=_f(e);return{callsMail:Pt(e,Tf),emitsEvent:Pt(e,wf),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Pt(e,If),throwsBareError:zf(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},qf=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=te(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Ef(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Uf(e,s);return{...o?Wf(o):{},...Bf(e),...i,analyzableBody:o!==void 0,exportName:G(e)??e.getName(),file:t,hasEmailArg:pf(s,n.receiver),kind:n.kind,visibility:n.visibility}},jf=(e,t)=>{const s=[];for(const n of J(e)){const i=qf(n,t);i&&s.push(i)}return s},Hf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...jf(i,w(t,n)))}return s},Gf=new Set(["dbRateLimit","rateLimit"]),Yf=e=>r.isArrowFunction(e)?e.getBody():e,Qf=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Ci=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Oi=(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)})},Xf=(e,t)=>H(e)||t!==void 0&&Oi(e,t).some(s=>Ci(s)),Jf=(e,t)=>t===void 0?fe(e):Oi(e,t).some(s=>!Ci(s)),Zf=(e,t)=>{const s=T(e.getExpression());if(s===void 0||!Gf.has(s))return;const n=L(zn(e.getArguments()[2]),"key");if(!n)return;const i=Yf(n),o=Qf(n);if(!(!Xf(i,o)||Jf(i,o)))return{callee:s,scope:S(e),file:t,limitName:_n(e),line:e.getStartLineNumber()}},eg=(e,t)=>O(e,t,Zf),tg=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),sg=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!tg.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()},ng=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()}},ig=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},ki=(e,t=!1)=>{const s=ig(e);if(r.isIdentifier(s)){if(t)return;const n=X(s);return n===void 0?void 0:ki(n,!0)}if(r.isCallExpression(s))return sg(s)??ng(s)},rg=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of x(e,d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},og=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=te(s);if(n?.kind!=="query")return[];const i=Gn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&qr(n.receiver,"output"),a=n.receiver!==void 0&&qn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of rg(i)){const f=ki(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:G(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},ag=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...og(a,o))}return s},cg=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},lg=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=Hn(o);if(a===void 0)continue;const c=cg(L(a.options,"with"));c.length!==0&&i.push({exportName:G(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},dg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...lg(a,o))}return s},j=(e,t)=>`${e}:${t}`,vn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},ug=(e,t)=>[...ie(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?vn(s,n,s.getName(),s.isExported()):void 0),...ie(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?vn(i,n,s.getName(),i.isExported()):void 0})],fg=(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=w(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(j(c,a))},gg=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,pg=(e,t)=>{const s=new Map(e.map(n=>[j(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(j(i.file,i.name))?.set(gg(n),{fields:n.fields,method:n.method,table:n.table})}return s},mg=(e,t,s)=>x(e.node,d.CallExpression).map(n=>fg(n,t,s)).filter(n=>n!==void 0),hg=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(j(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(j(o.file,o.name))?.push(a)}},vg=(e,t,s)=>{const n=new Map(e.map(a=>[j(a.file,a.name),a])),i=new Map(e.map(a=>[`${ss(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[j(a.file,a.name),mg(a,n,t)]));return hg(s,n,i,o),o},Eg=(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},xg=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(j(i.file,i.name))??[])Eg(t.get(j(i.file,i.name)),t.get(j(o.file,o.name)))&&(n=!0)}},Sg=(e,t,s,n)=>{const i=ug(e,t),o=pg(i,s);return xg(i,o,vg(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(j(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}},Ag=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},yg=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},bg=(e,t,s)=>go(e)?!Fr(s)&&po(yg(t)):!0,Ng=(e,t)=>{const s=[],n=[...x(e,d.BinaryExpression),...x(e,d.StringLiteral),...x(e,d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(Ag(o))continue;const a=Ye(o);if(a===void 0)continue;const c=uo(a);if(c===void 0||!bg(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:fo(a)}))}return s},Pg=(e,t)=>{const s=[],n=new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Je(i,"utf8"),{overwrite:!0});s.push(...Ng(o,w(t,i)))}return s},wg=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?te(s):void 0;if(!n)return[];const i=[];for(const o of x(e,d.CallExpression)){const a=Hn(o);if(a===void 0)continue;const c=L(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&H(c);!l&&!u||i.push({exportName:G(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Ig=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of J(i))s.push(...wg(a,o))}return s},Tg=new Set(["query","unsafe"]),Cg=e=>!r.isPropertyAccessExpression(e)||!Tg.has(e.getName())?!1:Q(e.getExpression(),["sql"]),Og=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),kg=(e,t)=>{if(!Cg(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Og(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},Rg=(e,t)=>O(e,t,kg),Fg=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Lg=e=>{for(const[t,s]of Fg)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Dg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Lg(a);c!==void 0&&s.push({file:w(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Mg=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),_g=(e,t,s=[])=>{const n=ot(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Mg,requireUnmodifiedReach:!0});return Zt(n,s)},zg=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Kg=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,$g=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=Kg(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Bg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=zg.get(t);return s===void 0?void 0:Bn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Vg=(e,t)=>{const s=Bg(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...$g(e.getArguments()[s.optionsIndex])}},Ug=(e,t)=>O(e,t,Vg),Wg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Ri=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Wg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>oe(i)||s(i));if(!(n===void 0||oe(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},as=(e,t)=>b(e.getFirstAncestor(s=>b(s,t)||oe(s)),t),qg=(e,t)=>b(e,t)||e.getFirstAncestor(s=>b(s,t))!==void 0,Fi=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return b(e,t)||as(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Ri(e);return s!==void 0&&!qg(s,t)}return!1},Li=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)],jg=e=>Li(e).some(t=>Fi(t,e)),Hg=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},Gg=e=>Li(e).some(t=>Fi(t,e)||r.isBreakStatement(t)&&b(Ri(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Hg(t)&&as(t,e)),Yg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>as(t,e)),Qg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),Xg=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",wt=(e,t)=>{const s=Qg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||Gg(e)||Yg(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(oe)!==void 0))return{file:t,kind:Xg(e),line:e.getStartLineNumber(),scope:i}},Jg=(e,t)=>[...ie(e,t,d.WhileStatement,wt),...ie(e,t,d.ForStatement,wt),...ie(e,t,d.DoStatement,wt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),Zg=new Set(["when","where"]),It=new Set(["definePolicy","defineShape"]),ep=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return It.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 It.has(i)?i:void 0}const s=t.getText();return It.has(s)?s:void 0},tp=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,Di=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(tp(e))return"empty-object";if(r.isParenthesizedExpression(e))return Di(e.getExpression())}},cs=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),sp=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>cs(t)===e),Mi=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>cs(t)===e),np=e=>{const t=sp(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Mi(e).length>0},ip=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>cs(t)===e),Wt=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()==="",rp=(e,t)=>Wt(e)||Wt(t),op=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),En=e=>!Wt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),ap=(e,t,s)=>{const n=op.get(e);if(n!==void 0)return rp(t,s)?n==="positive"?"negative":"positive":En(t)||En(s)?void 0:n},be=e=>{if(r.isParenthesizedExpression(e))return be(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=ap(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=be(e.getLeft()),i=be(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},xn=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}}},cp=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},lp=e=>r.isReturnStatement(e)?e.getExpression()??e:e,dp=e=>{const t=[];for(const s of Mi(e)){const n=be(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of ip(e)){const n=be(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?xn(s.getThenStatement()):xn(s.getElseStatement())??cp(s);i!==void 0&&t.push(lp(i))}return t},up=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},fp=(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)||!Zg.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&np(a))for(const c of dp(a)){const l=Di(c);l!==void 0&&i.push({exportName:up(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},gp=(e,t)=>{const s=[];for(const n of x(e,d.CallExpression)){const i=ep(n);i!==void 0&&s.push(...fp(n,i,t))}return s},pp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...gp(i,w(t,n)))}return s},mp=new Set(["query","upsert","upsertMany","upsertNow"]),me=new Set,hp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(mp.has(t))return Q(e.getExpression(),["vectors"])?t:void 0},ls=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},_i=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},zi=e=>_i(e)?.getDeclarations()[0],vp=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},Sn=(e,t,s)=>{const n=_i(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Ki(zi(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return ds(o,t,s-1)}return H(e)},ds=(e,t,s)=>{const n=ls(e);return fe(n)?!1:r.isIdentifier(n)?Sn(n,t,s):H(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>vp(i)&&Sn(i,t,s))},$i=e=>{const t=Ki(zi(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},ee=(e,t)=>{const s=ls(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...ee(s.getWhenTrue(),t),...ee(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...ee(s.getLeft(),t),...ee(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=$i(s);return n===void 0?[]:ee(n,!1)}return[]},Ep=(e,t)=>{const s=ee(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}},xp=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Sp=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=Ep(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else xp(n)&&(s=[Sp(n)]);return s},Ap=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]},yp=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return me;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return me;const s=r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.BindingElement).map(n=>n.getNameNode());return new Set(s.flatMap(n=>r.isIdentifier(n)?n.getSymbol()?.compilerSymbol??[]:[]))},qt=(e,t=!0,s=me)=>{const n=ls(e);if(r.isIdentifier(n)){const o=t?$i(n):void 0;return o===void 0?[{node:n,parameters:s}]:qt(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?qt(o.getExpression(),t,s):ee(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=ds(i.getExpression(),me,1)?yp(o):me;return Ap(o).flatMap(c=>ee(c,!0).flatMap(l=>Qe(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},bp=(e,t)=>{const s=hp(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?qt(n):ee(n,!0).flatMap(o=>Qe(o,!0).map(a=>({node:a,parameters:me})))).some(({node:o,parameters:a})=>ds(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},Np=(e,t)=>O(e,t,bp),Pp=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:m,workflows:v}=s;return Ir({adminRoutes:Xa(e,t),aiRawRuns:oc(e,t),aiToolSideEffects:vc(e,t),argumentDerivedFetches:Sc(e,t),argumentValidators:zc(e,t),authApiCalls:Yr(e,t),authConfigs:Gc(e,t),browserUrlAccesses:Jc(e,t),callEdges:n.callEdges,configCalls:ol(e,t),containerKeyAccesses:cl(e,t),containerOverrides:pl(e,t),containers:i,countReads:xl(e,t,f.tables),crons:o,cronTargets:o.flatMap(B=>B.functionPath===void 0?[]:[B.functionPath]),exportSinks:bl(e,t),staleMigrationImports:Dg(e,t),failOpenGuards:Tl(e,t),flagReads:Fl(e,t),flagSecurityDefaults:_l(e,t),geoIndexUsages:$l(e,t),httpActionGuards:Jl(e,t),httpHeaderWrites:cd(e,t),hyperdriveCalls:Jr(e,t),identityClaimReads:xd(e,t),imageDeliveryUrlAccesses:Ad(e,t),inserts:n.inserts,kvKeyAccesses:bd(e,t,a),mailRecipientAccesses:Td(e,t),maskProcedures:Zr(e,t),maskStrategies:kd(e,t),mutatorWrites:_d(e,t),nondeterministicCalls:io(e,t),normalizeIdAuthorizations:Jd(e,t),notifyCalls:oo(e,t),notifyConfig:ro(e,t),mutators:l,ownerFieldWrites:Hu(e,t,a,l),unrestrictedWhereBranches:pp(e,t),paymentWebhooks:Ju(e,t),privilegedDispatches:df(e,t),procedureProtections:Hf(e,t),queries:n.queries,queues:u,r2sqlCalls:ao(e,t),ratelimitKeySelectors:eg(e,t),rawRowReturns:ag(e,t),relationLoads:dg(e,t),rlsProcedures:co(e,t),schema:f,secretLiterals:Pg(e,t),modules:c,shapes:g,softDeleteReads:Ig(e,t),sqlInterpolations:Rg(e,t),storageKeyAccesses:_g(e,t,a),storageUploads:Ug(e,t),tableWrites:n.tableWrites,rowEffects:Sg(e,t,n.tableWrites,n.callEdges),unboundedLoops:Jg(e,t),vectorNamespaceAccesses:Np(e,t),workflowCalls:n.workflowCalls,workflows:v,wranglerVariables:m})},wp=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"}),Ip=(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=>wp(i))]},Tp=()=>({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"}),Cp=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",An={error:"ERROR",info:"INFO",warn:"WARN"},yn={ERROR:2,INFO:0,WARN:1},Op=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"}),kp=(e,t)=>{const{advisor:s}=Qn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(An,n)?An[n]:void 0;return i===void 0?[...t,Op(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=>Cp(o)||yn[o.level]>=yn[i])},Rp=(e,t)=>{const{advisor:s}=Qn(e),n=Ip(t,s?.accept??[]);return kp(e,s?.acceptUnreadable===!0?[...n,Tp()]:n)},Fp={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Lp="crons",Dp=xo.replace(/\.ts$/u,""),pe=(e,t)=>`${ss(e)}:${t}`,Tt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Mp=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Fp[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,...Tt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Tt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Tt("workflow",t.workflow,"workflow name")}))],_p=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",zp=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:_p(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Kp=e=>Mp(e).flatMap(t=>zp(t)),$p=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:Lp,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Bp=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),Se=(e,t)=>t===void 0?e:{...e,module:t},Vp=e=>{const t=new Map,s=new Map,n=Bp(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(pe(c.file,c.exportName),l)};for(const c of e.functions){const l=pe(c.filePath,c.exportName),u=[...lo(c.filePath),c.exportName].join(".");o(Se({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Me(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=pe(c.filePath,c.exportName);o(Se({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Me(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(Se({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(Se({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Me(e.modules,c.filePath)),pe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(Se({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Me(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},pe(Dp,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}},Up=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Wp=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(pe(e.file,e.exportName))??{reason:Up(e.exportName)},qp=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Wp(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`}},Ct=e=>`${e.from}|${e.kind}|${e.to}`,jp=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Hp=e=>{const{nodes:t,sites:s}=Vp(e),n=new Map,i=new Map;for(const o of[...$p(e),...Kp(e)]){const a=qp(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(Ct(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(jp(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>Ct(o).localeCompare(Ct(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}},Gp=e=>`${Xn}export const architecture = ${Ao(e,"Record<string, unknown>")};
24
- `,bn=(e,t="api")=>{const s=new Map;for(const n of e){const i=ss(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 D("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})}}},Yp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Jn(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>Zn(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?[]:To)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)},Qp=(e,t,s={})=>{if(t===void 0)return;const n=Yp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
25
- `);throw new D("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
23
+ `)){const i=n.replace($f,"");if(!i.startsWith(hn))continue;const o=i.slice(hn.length);if(Bf.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:""}},Uf=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=U(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Wf=(e,t)=>{const s=Uf(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)},qf=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of E(e,d.CallExpression))if(Af(l)&&(o=!0),bf(l)&&(t=!0),Nf(l)&&(i=!0),Pf(l)&&(s=!0),wf(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=zf(e);return{callsMail:Pt(e,Cf),emitsEvent:Pt(e,If),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Pt(e,Tf),throwsBareError:Kf(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},jf=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=se(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?xf(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Wf(e,s);return{...o?qf(o):{},...Vf(e),...i,analyzableBody:o!==void 0,exportName:G(e)??e.getName(),file:t,hasEmailArg:mf(s,n.receiver),kind:n.kind,visibility:n.visibility}},Hf=(e,t)=>{const s=[];for(const n of J(e)){const i=jf(n,t);i&&s.push(i)}return s},Gf=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hf(i,T(t,n)))}return s},Yf=new Set(["dbRateLimit","rateLimit"]),Qf=e=>r.isArrowFunction(e)?e.getBody():e,Xf=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Ci=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Oi=(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)})},Jf=(e,t)=>H(e)||t!==void 0&&Oi(e,t).some(s=>Ci(s)),Zf=(e,t)=>t===void 0?ge(e):Oi(e,t).some(s=>!Ci(s)),eg=(e,t)=>{const s=C(e.getExpression());if(s===void 0||!Yf.has(s))return;const n=D(zn(e.getArguments()[2]),"key");if(!n)return;const i=Qf(n),o=Xf(n);if(!(!Jf(i,o)||Zf(i,o)))return{callee:s,scope:S(e),file:t,limitName:_n(e),line:e.getStartLineNumber()}},tg=(e,t)=>k(e,t,eg),sg=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),ng=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!sg.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()},ig=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()}},rg=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},ki=(e,t=!1)=>{const s=rg(e);if(r.isIdentifier(s)){if(t)return;const n=X(s);return n===void 0?void 0:ki(n,!0)}if(r.isCallExpression(s))return ng(s)??ig(s)},og=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},ag=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=se(s);if(n?.kind!=="query")return[];const i=Gn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&jr(n.receiver,"output"),a=n.receiver!==void 0&&qn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of og(i)){const f=ki(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:G(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},cg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of J(i))s.push(...ag(a,o))}return s},lg=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},dg=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?se(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Hn(o);if(a===void 0)continue;const c=lg(D(a.options,"with"));c.length!==0&&i.push({exportName:G(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},ug=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of J(i))s.push(...dg(a,o))}return s},j=(e,t)=>`${e}:${t}`,vn=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},fg=(e,t)=>[...re(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?vn(s,n,s.getName(),s.isExported()):void 0),...re(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?vn(i,n,s.getName(),i.isExported()):void 0})],gg=(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=T(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(j(c,a))},pg=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,mg=(e,t)=>{const s=new Map(e.map(n=>[j(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(j(i.file,i.name))?.set(pg(n),{fields:n.fields,method:n.method,table:n.table})}return s},hg=(e,t,s)=>E(e.node,d.CallExpression).map(n=>gg(n,t,s)).filter(n=>n!==void 0),vg=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(j(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(j(o.file,o.name))?.push(a)}},Eg=(e,t,s)=>{const n=new Map(e.map(a=>[j(a.file,a.name),a])),i=new Map(e.map(a=>[`${ss(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[j(a.file,a.name),hg(a,n,t)]));return vg(s,n,i,o),o},xg=(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},Sg=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(j(i.file,i.name))??[])xg(t.get(j(i.file,i.name)),t.get(j(o.file,o.name)))&&(n=!0)}},Ag=(e,t,s,n)=>{const i=fg(e,t),o=mg(i,s);return Sg(i,o,Eg(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(j(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}},yg=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},bg=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},Ng=(e,t,s)=>po(e)?!Lr(s)&&mo(bg(t)):!0,Pg=(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(yg(o))continue;const a=Ye(o);if(a===void 0)continue;const c=fo(a);if(c===void 0||!Ng(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:go(a)}))}return s},wg=(e,t)=>{const s=[],n=new Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0});for(const i of y(t,{includeSkipped:!0})){const o=e.getSourceFile(i)??n.createSourceFile(i,Je(i,"utf8"),{overwrite:!0});s.push(...Pg(o,T(t,i)))}return s},Ig=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?se(s):void 0;if(!n)return[];const i=[];for(const o of E(e,d.CallExpression)){const a=Hn(o);if(a===void 0)continue;const c=D(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&H(c);!l&&!u||i.push({exportName:G(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Tg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=T(t,n);for(const a of J(i))s.push(...Ig(a,o))}return s},Cg=new Set(["query","unsafe"]),Og=e=>!r.isPropertyAccessExpression(e)||!Cg.has(e.getName())?!1:Q(e.getExpression(),["sql"]),kg=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Rg=(e,t)=>{if(!Og(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!kg(s)))return{file:t,line:s.getStartLineNumber(),scope:S(e)}},Fg=(e,t)=>k(e,t,Rg),Lg=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Dg=e=>{for(const[t,s]of Lg)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Mg=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Dg(a);c!==void 0&&s.push({file:T(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},_g=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),zg=(e,t,s=[])=>{const n=ot(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:_g,requireUnmodifiedReach:!0});return Zt(n,s)},Kg=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),$g=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Bg=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=$g(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Vg=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Kg.get(t);return s===void 0?void 0:Bn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Ug=(e,t)=>{const s=Vg(e.getExpression());if(s!==void 0)return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...Bg(e.getArguments()[s.optionsIndex])}},Wg=(e,t)=>k(e,t,Ug),qg=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),Ri=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:qg(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>ae(i)||s(i));if(!(n===void 0||ae(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},as=(e,t)=>b(e.getFirstAncestor(s=>b(s,t)||ae(s)),t),jg=(e,t)=>b(e,t)||e.getFirstAncestor(s=>b(s,t))!==void 0,Fi=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return b(e,t)||as(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=Ri(e);return s!==void 0&&!jg(s,t)}return!1},Li=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)],Hg=e=>Li(e).some(t=>Fi(t,e)),Gg=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},Yg=e=>Li(e).some(t=>Fi(t,e)||r.isBreakStatement(t)&&b(Ri(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Gg(t)&&as(t,e)),Qg=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>as(t,e)),Xg=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),Jg=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",wt=(e,t)=>{const s=Xg(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||Yg(e)||Qg(e))return;const i=S(e);if(!(i.kind==="module"&&e.getFirstAncestor(ae)!==void 0))return{file:t,kind:Jg(e),line:e.getStartLineNumber(),scope:i}},Zg=(e,t)=>[...re(e,t,d.WhileStatement,wt),...re(e,t,d.ForStatement,wt),...re(e,t,d.DoStatement,wt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),ep=new Set(["when","where"]),It=new Set(["definePolicy","defineShape"]),tp=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return It.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 It.has(i)?i:void 0}const s=t.getText();return It.has(s)?s:void 0},sp=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,Di=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(sp(e))return"empty-object";if(r.isParenthesizedExpression(e))return Di(e.getExpression())}},cs=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),np=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>cs(t)===e),Mi=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>cs(t)===e),ip=e=>{const t=np(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Mi(e).length>0},rp=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>cs(t)===e),Wt=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()==="",op=(e,t)=>Wt(e)||Wt(t),ap=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),En=e=>!Wt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),cp=(e,t,s)=>{const n=ap.get(e);if(n!==void 0)return op(t,s)?n==="positive"?"negative":"positive":En(t)||En(s)?void 0:n},Ne=e=>{if(r.isParenthesizedExpression(e))return Ne(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=cp(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=Ne(e.getLeft()),i=Ne(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},xn=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}}},lp=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},dp=e=>r.isReturnStatement(e)?e.getExpression()??e:e,up=e=>{const t=[];for(const s of Mi(e)){const n=Ne(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of rp(e)){const n=Ne(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?xn(s.getThenStatement()):xn(s.getElseStatement())??lp(s);i!==void 0&&t.push(dp(i))}return t},fp=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},gp=(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)||!ep.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&ip(a))for(const c of up(a)){const l=Di(c);l!==void 0&&i.push({exportName:fp(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},pp=(e,t)=>{const s=[];for(const n of E(e,d.CallExpression)){const i=tp(n);i!==void 0&&s.push(...gp(n,i,t))}return s},mp=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pp(i,T(t,n)))}return s},hp=new Set(["query","upsert","upsertMany","upsertNow"]),he=new Set,vp=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(hp.has(t))return Q(e.getExpression(),["vectors"])?t:void 0},ls=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},_i=e=>{const t=e.getParent();return r.isShorthandPropertyAssignment(t)&&t.getNameNode()===e?t.getValueSymbol():e.getSymbol()},zi=e=>_i(e)?.getDeclarations()[0],Ep=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},Sn=(e,t,s)=>{const n=_i(e)?.compilerSymbol;if(n!==void 0&&t.has(n))return!0;if(s>0){const i=Ki(zi(e)),o=i!==void 0&&r.isVariableDeclaration(i)?i.getInitializer():void 0;if(o!==void 0)return ds(o,t,s-1)}return H(e)},ds=(e,t,s)=>{const n=ls(e);return ge(n)?!1:r.isIdentifier(n)?Sn(n,t,s):H(n)?!0:n.getDescendantsOfKind(d.Identifier).some(i=>Ep(i)&&Sn(i,t,s))},$i=e=>{const t=Ki(zi(e));return t!==void 0&&r.isVariableDeclaration(t)?t.getInitializer():void 0},te=(e,t)=>{const s=ls(e);if(r.isObjectLiteralExpression(s))return[s];if(r.isConditionalExpression(s))return[...te(s.getWhenTrue(),t),...te(s.getWhenFalse(),t)];if(r.isBinaryExpression(s)){const n=s.getOperatorToken().getKind();if(n===d.BarBarToken||n===d.QuestionQuestionToken||n===d.AmpersandAmpersandToken)return[...te(s.getLeft(),t),...te(s.getRight(),t)]}if(r.isIdentifier(s)&&t){const n=$i(s);return n===void 0?[]:te(n,!1)}return[]},xp=(e,t)=>{const s=te(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}},Sp=e=>(r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e))&&e.getName()==="namespace",Ap=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=xp(n.getExpression(),t);i!==void 0&&(s=i.replaces?i.sources:[...s,...i.sources])}else Sp(n)&&(s=[Ap(n)]);return s},yp=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]},bp=e=>{if(!e||!(r.isArrowFunction(e)||r.isFunctionExpression(e)))return he;const t=e.getParameters()[0]?.getNameNode();if(t===void 0)return he;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??[]:[]))},qt=(e,t=!0,s=he)=>{const n=ls(e);if(r.isIdentifier(n)){const o=t?$i(n):void 0;return o===void 0?[{node:n,parameters:s}]:qt(o,!1,s)}if(r.isArrayLiteralExpression(n))return n.getElements().flatMap(o=>r.isSpreadElement(o)?qt(o.getExpression(),t,s):te(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=ds(i.getExpression(),he,1)?bp(o):he;return yp(o).flatMap(c=>te(c,!0).flatMap(l=>Qe(l,!0).map(u=>({node:u,parameters:a}))))}return[{node:n,parameters:s}]},Np=(e,t)=>{const s=vp(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!(!n||!(s==="upsertMany"?qt(n):te(n,!0).flatMap(o=>Qe(o,!0).map(a=>({node:a,parameters:he})))).some(({node:o,parameters:a})=>ds(o,a,1))))return{scope:S(e),file:t,line:e.getStartLineNumber(),method:s}},Pp=(e,t)=>k(e,t,Np),wp=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:m,workflows:x}=s;return Tr({adminRoutes:Ja(e,t),aiRawRuns:ac(e,t),aiToolSideEffects:Ec(e,t),argumentDerivedFetches:Ac(e,t),argumentValidators:Kc(e,t),authApiCalls:Qr(e,t),authConfigs:Yc(e,t),browserUrlAccesses:Zc(e,t),callEdges:n.callEdges,configCalls:al(e,t),containerKeyAccesses:ll(e,t),containerOverrides:ml(e,t),containers:i,countReads:Sl(e,t,f.tables),crons:o,cronTargets:o.flatMap(N=>N.functionPath===void 0?[]:[N.functionPath]),exportSinks:Nl(e,t),staleMigrationImports:Mg(e,t),failOpenGuards:Cl(e,t),flagReads:Ll(e,t),flagSecurityDefaults:zl(e,t),geoIndexUsages:Bl(e,t),httpActionGuards:Zl(e,t),httpHeaderWrites:ld(e,t),hyperdriveCalls:Zr(e,t),identityClaimReads:Sd(e,t),imageDeliveryUrlAccesses:yd(e,t),inserts:n.inserts,kvKeyAccesses:Nd(e,t,a),mailRecipientAccesses:Cd(e,t),maskProcedures:eo(e,t),maskStrategies:Rd(e,t),mutatorWrites:zd(e,t),nondeterministicCalls:ro(e,t),normalizeIdAuthorizations:Zd(e,t),notifyCalls:ao(e,t),notifyConfig:oo(e,t),mutators:l,ownerFieldWrites:Gu(e,t,a,l),unrestrictedWhereBranches:mp(e,t),paymentWebhooks:Zu(e,t),privilegedDispatches:uf(e,t),procedureProtections:Gf(e,t),queries:n.queries,queues:u,r2sqlCalls:co(e,t),ratelimitKeySelectors:tg(e,t),rawRowReturns:cg(e,t),relationLoads:ug(e,t),rlsProcedures:lo(e,t),schema:f,secretLiterals:wg(e,t),modules:c,shapes:g,softDeleteReads:Tg(e,t),sqlInterpolations:Fg(e,t),storageKeyAccesses:zg(e,t,a),storageUploads:Wg(e,t),tableWrites:n.tableWrites,rowEffects:Ag(e,t,n.tableWrites,n.callEdges),unboundedLoops:Zg(e,t),vectorNamespaceAccesses:Pp(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:m})},Ip=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"}),Tp=(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=>Ip(i))]},Cp=()=>({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"}),Op=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",An={error:"ERROR",info:"INFO",warn:"WARN"},yn={ERROR:2,INFO:0,WARN:1},kp=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"}),Rp=(e,t)=>{const{advisor:s}=Qn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(An,n)?An[n]:void 0;return i===void 0?[...t,kp(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=>Op(o)||yn[o.level]>=yn[i])},Fp=(e,t)=>{const{advisor:s}=Qn(e),n=Tp(t,s?.accept??[]);return Rp(e,s?.acceptUnreadable===!0?[...n,Cp()]:n)},Lp={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Dp="crons",Mp=So.replace(/\.ts$/u,""),me=(e,t)=>`${ss(e)}:${t}`,Tt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},_p=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Lp[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,...Tt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...Tt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...Tt("workflow",t.workflow,"workflow name")}))],zp=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Kp=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:zp(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},$p=e=>_p(e).flatMap(t=>Kp(t)),Bp=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:Dp,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],Vp=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),Ae=(e,t)=>t===void 0?e:{...e,module:t},Up=e=>{const t=new Map,s=new Map,n=Vp(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(me(c.file,c.exportName),l)};for(const c of e.functions){const l=me(c.filePath,c.exportName),u=[...uo(c.filePath),c.exportName].join(".");o(Ae({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Me(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=me(c.filePath,c.exportName);o(Ae({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Me(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(Ae({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(Ae({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Me(e.modules,c.filePath)),me(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(Ae({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},me(Mp,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}},Wp=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,qp=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(me(e.file,e.exportName))??{reason:Wp(e.exportName)},jp=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=qp(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`}},Ct=e=>`${e.from}|${e.kind}|${e.to}`,Hp=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Gp=e=>{const{nodes:t,sites:s}=Up(e),n=new Map,i=new Map;for(const o of[...Bp(e),...$p(e)]){const a=jp(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(Ct(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Hp(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>Ct(o).localeCompare(Ct(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}},Yp=e=>`${Xn}export const architecture = ${yo(e,"Record<string, unknown>")};
24
+ `,bn=(e,t="api")=>{const s=new Map;for(const n of e){const i=ss(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 M("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})}}},Qp=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Jn(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>Zn(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?[]:Co)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)},Xp=(e,t,s={})=>{if(t===void 0)return;const n=Qp(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
25
+ `);throw new M("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.`)},Xp="env.ts",Jp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return it(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Zp=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&&it(n.getModuleSpecifierValue())}return!1},em=e=>{if(r.isIdentifier(e))return Jp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&Zp(t)}return!1},tm=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!em(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ae(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=st(s,"member");a!==void 0&&t.push({exportName:a})}return t},sm=(e,t)=>{const s=E(t,Xp);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=tm(n);if(i.length!==0){if(i.length>1)throw ae(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},nm={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},im=new Set(["allowedHosts","deniedHosts","interceptHttps"]),rm=(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())},om=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),am=new Set(["durable"]),cm=new Set(["rollback"]),Bi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},lm="defineApp",Ne="app",Nn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===Ne&&s.getInitializer()?.getText()===t)||t===Ne&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===Ne),dm=e=>{if(e===void 0||!_o.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===Ne;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===Ne;if(r.isVariableDeclaration(t))return Nn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&Nn(e.getSourceFile(),s)},um="AppBuilder",Vi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},fm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===um&&s.getDeclarations().some(n=>Vi(n))},gm=e=>e.getText()===lm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Vi(t)),Ui=(e,t,s=new Set)=>{const n=et(t);if(n===void 0||!r.isIdentifier(n))return!1;if(gm(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 dm(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 Ui(e,a.getInitializer(),s)}}return!1},Wi=(e,t)=>{const s=Xt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Ui(e,s.object)||fm(s.object))},pm=new Map([["defineContainer",{keys:im,signal:"containerEgressPolicy"}],["defineStep",{keys:cm,signal:"workflowRollback"}],["stream",{keys:am,signal:"durableStreams"}]]),mm=(e,t)=>{const s=pm.get(Bi(t));if(s!==void 0)return t.getArguments().some(n=>om(rm(e,n),s.keys))?s.signal:void 0},hm=(e,t)=>nm[Bi(t)]??(Wi(e,t)?"deliveryAuthorization":void 0),vm=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Fo(o);n.secrets=n.secrets||c.has("secrets"),n.liveContext=n.liveContext||c.has("live")}const a=x(o,d.CallExpression);for(const c of a){const l=mm(o,c)??hm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>jn(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 Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Je(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Wi(i,o))}return n},Em=(e,t)=>{const s=Do();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Lo(i,s))return!0}return!1},xm="createWorker",Sm="extend",Pn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,wn=e=>{const t=[],s=Pn(L(e,"backupCron"));s!==void 0&&t.push(s);const n=L(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=Pn(i.getNameNode());o!==void 0&&t.push(o)}return t},Am=e=>{const t=T(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===xm)return r.isObjectLiteralExpression(s)?wn(s):[];if(t!==Sm||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Mn(s.getBody());return n===void 0?[]:wn(n)},ym=(e,t)=>{const s=[];for(const{filePath:n}of Ze(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression))s.push(...Am(o))}return[...new Set(s)]},qi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:qi(e.inner)},bm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=qi(n);return i!==void 0&&t.has(i)}))},Nm=(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 D("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 D("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Pm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=gd(s,t),a=sm(s,t),c=So(s,t),{queues:l,topics:u}=Ko(s,t),f=Bo(n),g=Oo(s,t);Nm(c,g);const m=ko(s,t),v=Vo(s,t),B=Ro(s,t,c,g),ge=ym(s,t),N=vm(s,t,zo(n)),V=$o(s,t),Y=Em(s,t),I=Mo(s,t);I.browser=I.browser||V.usesSandboxBrowser;const k=_e(n,e.target),R=Uo(I,k,{agents:g.length>0,commitOrderedTables:i.tables.some(z=>z.commitOrdered===!0),cronTriggers:B.length>0,crossShardFanout:i.tables.some(z=>Xo(z)),containerEgressPolicy:N.containerEgressPolicy,containerRuntimeScheduling:m.some(z=>z.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(z=>z.sandbox===!0),deliveryAuthorization:N.deliveryAuthorization,durableStreams:N.durableStreams,globalTables:i.tables.some(z=>z.shardMode==="global"),liveContext:N.liveContext,liveStreams:N.liveStreams,typedWebSockets:N.typedWebSockets,queues:l.length>0,relationGraph:bm(i),secretValues:Y,secrets:N.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:V.usesSandboxLoader,workflowRollback:N.workflowRollback,workflowSchedules:c.some(z=>z.schedules!==void 0)}),U=R.usage,Z=Co(U),se=R.signals.vectorStore!==!1,ne=R.signals.services===!1?[]:f,ce=ei(n),_=ce??new Set,P=_.has("lunorash");Qp(i,ce,{hasVectors:se,scheduler:U.scheduler||B.length>0,storage:U.storage||v.rules.length>0||Object.keys(ti(i)).length>0,usage:U});const F=K(E(t,"flags.ts")),Ce=K(E(t,"notify.ts"));return{agents:g,capabilities:Z,containers:m,crons:B,dataModelContent:ta(i),declaredDependencies:ce,dependencies:_,entryCronTriggers:ge,env:a,featureUsage:U,hasFlags:F,hasNotify:Ce,identity:o,platformGate:{...R,diagnostics:[...Wo(n,e.target),...R.diagnostics,...qo(k,i.vectorIndexes),...N.liveStreams&&N.deliveryAuthorization?[jo(k)]:[],...N.socketRoutes&&N.deliveryAuthorization?[Ho(k)]:[]]},queues:l,serverContent:Zo({agents:g,capabilities:Z,containers:m,env:a,hasVectors:se,hasFlags:F,hasNotify:Ce,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:v.rules.map(z=>z.bucket),topics:u,useUmbrella:P,workflows:c}),services:ne,storageRulesMetadata:v,topics:u,usesSandbox:V.usesSandboxBrowser||V.usesSandboxContainer||V.usesSandboxFs,useUmbrella:P,workflows:c}},ji=(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},wm=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},Im=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Tm=/^[\w$]+:[\w$]+$/u,Cm=(e,t)=>{const s=$n(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},In=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},Om=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return In(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Qt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?In(s):void 0}}},km=(e,t,s)=>({schedule:{argKeys:Om(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Rm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Kn.has(s))return Cm(s,n);if((s==="runAfter"||s==="runAt")&&wm(t)){const l=$n(i)??(r.isStringLiteral(i)&&Tm.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,...km(s,n,o)}}const a=Im.get(s),c=a===void 0?void 0:ji(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Fm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Hi=e=>Tr.isOptionalChain(e.compilerNode),Lm=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:oe(t)?t.getFirstAncestor(oe)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Fm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Hi(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&jg(s)),Dm=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(oe);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(oe),i))===!0},Mm=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),_m=(e,t)=>{if(Hi(e)||t==="schedule"&&Dm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Lm(s,i)){if(!Mm(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Tn=(e,t,s)=>{if(s===void 0)return;const n=_m(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},zm=(e,t)=>[...O(e,t,(s,n)=>Tn(s,n,Rm(s))),...ie(e,t,d.PropertyAccessExpression,(s,n)=>{const i=ji(s,"services");return Tn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],Km=new Set(["boolean","number","object","string"]),$m=e=>{const t=e.getName();if(!Km.has(t))return;const s=e.getExpression();return Q(s,["flags"])||Q(s,["flags","details"])?t:void 0},Bm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=$m(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},Vm=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of x(i,d.CallExpression)){const a=Bm(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))},Um=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"||sa(o))return;const a=e.getSourceFile().getFilePath();if(na(i,e,a)){const c=ia(i,e,a,0,new Set);return c===void 0&&ra(o),c}return o},Wm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=jr(t.getNameNode());return s===void 0||s==="namespace"}),qm=(e,t)=>{for(const{filePath:s}of Ze(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of x(n,d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Wm(a)))return i}}},jm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Hm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ae(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 (${jm}). 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})},Gm="room:",Ym="__lunora_socket__:",Qm=/^[A-Za-z]\w*$/u,Cn=e=>Qm.test(e),Xm=e=>`${e}:`.startsWith(Gm)||`${e}:`.startsWith(Ym),Gi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Yi=e=>Gi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),On=e=>A(e),us=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),de=(e,t)=>{const s=ae(e,`defineLiveStream ${t}`);return new D("LIVE_STREAM_NOT_LITERAL",s.message)},Qi=(e,t,s)=>{const n=us(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw de(n??e,`needs ${s} so codegen can read its topics`);if(Yi(i))throw de(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Jm=(e,t)=>{const s=On(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw de(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Yi(n))throw de(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Cn(s)||Xm(s))throw new D("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(us(n,"key")===void 0)return{fields:[],name:s};const a=Qi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>On(l)),c=a.find(l=>!Cn(l));if(c!==void 0)throw new D("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}},Zm=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw de(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Gi(n))throw de(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=us(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw de(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Qi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:w(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Jm(a,l))}},eh=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 D("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)}},th=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},sh=(e,t)=>x(e,d.CallExpression).filter(s=>jn(s,"defineLiveStream")).map(s=>{const n=th(s),i=r.isVariableDeclaration(n)?st(n,"binding"):void 0;if(i===void 0)throw new D("LIVE_STREAM_NOT_EXPORTED",ae(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 Zm(s,i,t)}),nh=(e,t)=>{const s=y(t).flatMap(n=>sh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return eh(s),s},ih=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,rh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?ih(e):!0,Xi=(e,t=!1)=>{for(const s of e.getProperties()){if(rh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Xi(n,!0))return!0}return!1},oh=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of si(n))for(const o of ts(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Xi(a)))return!0}}return!1},ah=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:Yn(a),table:i})}}return s},ch=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of si(i))for(const a of ts(o))for(const c of ah(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},lh=["providerSubscriptionId","state"],dh=["providerEventId","processedAt"],kn=(e,t)=>t.every(s=>s in e.shape),uh=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&&kn(t,lh)&&kn(s,dh)},fh=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],gh=(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},mh="@lunora/privacy",Ji="userId",Rn=new Set(["user","users"]),hh=e=>e.replaceAll("\\","/"),vh="privacy",Eh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),at=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Ie=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",fs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),xh=(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},ct=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Sh=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=xh(s,"tables"),i=at(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:fs(n).map(a=>Ie(a)))t.datasets.set(o,i)},gs=8,he=(e,t=0)=>{if(t>gs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return he(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:he(i,t+1)},Ah=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:he(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[],o=new Set(i.map(a=>Ie(a)));for(const a of fh)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?at(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Ie(a)==="user"&&t.userTables.add(c))}},Fn=(e,t,s)=>{t.datasets.set(at(e.getArguments()[0])??s,s)},yh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Ie(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},Zi=(e,t=0)=>{const s=he(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>gs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Zi(i.getExpression(),t+1):[yh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},bh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Zi(t)},Nh=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:he(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[])t.excluded.set(Ie(i),r.isPropertyAssignment(i)?at(i.getInitializer())??"":"")},Ph=(e,t)=>{switch(ct(e)){case"actionCacheDataset":{Fn(e,t,"actionCache");break}case"authDataset":{Ah(e,t);break}case"defineDataset":{Sh(e,t);break}case"documentHistoryDataset":{Fn(e,t,"documentHistory");break}}},ps=e=>e!==void 0&&r.isCallExpression(e)&&ct(e)==="defineDataset",er=e=>e!==void 0&&r.isCallExpression(e)&&Eh.has(ct(e)??""),wh=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)&&(ps(i)||er(i))?n:void 0},tr=(e,t,s=0)=>{const n=he(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>gs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!tr(i.getExpression(),t,s+1))return!1}else if(!ps(i)&&!er(i)){const o=r.isIdentifier(i)?wh(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Ih=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||tr(t,s)?s:void 0},Th=(e,t)=>{const s=[];for(const i of x(e,d.CallExpression))if(Ph(i,t),ct(i)==="definePrivacy"){const o=bh(i);Nh(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Ih(o)})}return{declared:x(e,d.VariableDeclaration).filter(i=>ps(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Ch=(e,t)=>{const s=E(t,"schema.ts"),n=[...y(t),...K(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>hh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Oh=(e,t,s)=>{if(s?.has(mh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Rn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Rn)},i=[],o=[];for(const f of Ch(e,t)){const g=Th(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:gh(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},sr=(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&&sr(n,t)),kh=(e,t)=>e.extensionKey!==vh&&(Ji in e.shape||Object.values(e.shape).some(s=>sr(s,t))),Rh=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 "${Ji}" 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.`,Fh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>kh(o,t.userTables)).map(o=>o.name),[n]=ph(s,t.classifications);if(n!==void 0)throw new D("PRIVACY_COVERAGE",Rh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new D("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Lh=(e,t)=>{const s=Go(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")}},Dh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Ln=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Mh="",_h=(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},zh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Qt.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=zh(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},Kh=(e,t)=>{if(Dh.has(e))return{method:e,tables:Ue(t)??[Mh]}},Ot=(e,t,s)=>e===void 0?void 0:{...e,fields:_h(t,e.method,s)},$h=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()===Qt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},Bh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=$h(n);if(i!==void 0)return Ln.has(s)?Ot({method:s,tables:[i]},e,1):void 0;if($(n))return Ot(Kh(s,e.getArguments()[0]),e,2);if(Ln.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Ot({method:s,tables:[n.getName()]},e,1)},Vh=(e,t)=>O(e,t,(s,n)=>{const i=Bh(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}))}),Uh=(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"}),Wh=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||W(s,"args")===void 0)return!1}return is(e,t).opaque},qh=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=te(a);c!==void 0&&Wh(a,c.receiver)&&s.push(Uh(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},jh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...qh(i,w(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Hh=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),nr=e=>!e.isAny(),ir=e=>{const t=e.getType();if(!nr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Hh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Gh=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},rr={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."},Yh=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.`}),Qh={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)."},Xh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Jh={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)."},Zh=(e,t,s)=>{if(!t.some(i=>Kr(i)))return Qh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Xh.has(s.typeName)&&!n&&!t.some(i=>pa(i))?Jh:rr},or=(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:Yh(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},ev=(e,t,s)=>{const n=[];for(const i of J(e)){const o=r.isIdentifier(i.getNameNode())?Rt(i):[i.getName()],c=o.some(u=>Xe(s,t,u))||!Gh(i)?void 0:ir(i),[l=i.getName()]=o;c!==void 0&&n.push(or(t,l,c,i.getStartLineNumber(),Zh(i,o,c)))}return n},tv=(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=ir(i.getExpression());o!==void 0&&n.push(or(t,"default",o,i.getStartLineNumber(),rr))}return n},sv=(e,t,s)=>[...ev(e,t,s),...tv(e,t,s)],nv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Rt(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=Rt(n).find(o=>Xe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),iv=({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"}),rv=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...sv(c,l,s)),i.push(...nv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!nr(a.getType()))&&n.push(iv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},ov=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"},av=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},cv=(e,t)=>O(e,t,(s,n)=>ov(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:av(s)}:void 0),ar=e=>e==="@lunora/workflow",lv=e=>new Set(e.getImportDeclarations().filter(t=>ar(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),dv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),uv=(e,t)=>{const s=Wn(e,"defineWorkflowEvent",ar),n=lv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of x(e,d.CallExpression)){if(!dv(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)?st(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 D("WORKFLOW_EVENT_NOT_LITERAL",ae(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:w(t,e.getFilePath()),type:l.getLiteralValue()})}return i},fv=(e,t)=>{const s=y(t).flatMap(i=>uv(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 D("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))},Te=(e,t)=>{K(e)&&Je(e,"utf8")===t||Nr(e,t,"utf8")},gv=(e,t)=>{if(t===""){Pe(e,{force:!0});return}Te(e,t)},pv=(e,t)=>{const s=E(e,"services");if(Object.keys(t).length===0){Pe(s,{force:!0,recursive:!0});return}if(K(s))for(const n of Dn(s,{recursive:!0,withFileTypes:!0})){const i=E(n.parentPath,n.name);n.isFile()&&t[Gt(e,i)]===void 0&&Pe(i)}for(const[n,i]of Object.entries(t))jt(Ht(E(e,n)),{recursive:!0}),Te(E(e,n),i)},mv=(e,t,s)=>{const n=E(e,t);if(Object.keys(s).length===0){Pe(n,{force:!0,recursive:!0});return}if(K(n))for(const i of Dn(n,{recursive:!0,withFileTypes:!0})){const o=E(i.parentPath,i.name);i.isFile()&&s[Gt(n,o)]===void 0&&Pe(o)}for(const[i,o]of Object.entries(s)){const a=E(n,i);jt(Ht(a),{recursive:!0}),Te(a,o)}},hv=e=>{try{const t=va(E(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)},vv=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Ev=(e,t)=>{K(e)||jt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Te(E(e,n.name),n.content),s.push(n.name);break}case"directory":{mv(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>E(n.name,i)));break}case"services":{pv(e,n.files),s.push(...Object.keys(n.files));break}default:gv(E(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},xv=e=>{const t=hv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Sa({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=ya({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
29
- `,openApiModuleContent:Aa(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
30
- `,openRpcModuleContent:ba(i)}},Sv=".lunora-schema.json",Av=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},yv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new D("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 D("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 D("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})}},bv=8,Nv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:v}=e,B=()=>aa(()=>{const I=Xr(l,a,{lazyFunctions:o}),k=no(l,a);return{functions:I,httpRoutes:ca(l,a),mutators:k}});let{erased:ge,value:{functions:N,httpRoutes:V,mutators:Y}}=B();Qr(y(a).map(I=>l.getSourceFileOrThrow(I)),I=>Gt(a,I.getFilePath())),bn([...N,...Y].map(I=>I.filePath)),bn(V.filter(I=>I.stream).map(I=>I.filePath),"http-stream");for(let I=1;;I+=1){const k=u?N:N.filter(P=>P.channel?.kind!=="room"&&P.lifecycle!=="socket"),R=ka({agents:t,functions:k,httpRoutes:V,mutators:Y,useUmbrella:m,workflows:v}),U={agents:t,functions:k,lazyFunctions:o,migrations:c,mutators:Y,shapes:f,useUmbrella:m,usesSandbox:g},Z=Ba(U),se=Va(U),ne=Ra({functions:N,useUmbrella:m}),ce=E(a,"_generated",ni),_=[[s,R],[i,ne],[n,Z],...Object.entries(se).map(([P,F])=>[E(ce,P),F])];if(I>=bv||_.every(([P,F])=>vv(l,P,F)))return{apiContent:R,erased:ge,functions:N,functionModulesContent:se,functionsContent:Z,httpRoutes:V,internalContent:ne,mutators:Y};for(const[P,F]of _)We(l,P,F);({erased:ge,value:{functions:N,httpRoutes:V,mutators:Y}}=B())}},Pv=e=>{const t=Av(),s=t?St.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=e.lazyFunctions===!0||mo(e.projectRoot),o=E(n,"schema.ts");if(!K(o))throw new D("INTERNAL",`schema.ts not found at ${o}`);const a=e.project??Io(n);Gr(Um);const c=fa(a,o,e.projectRoot);Fh(c.tables,Oh(a,n,ei(e.projectRoot)));const{agents:l,capabilities:u,containers:f,crons:g,dataModelContent:m,dependencies:v,entryCronTriggers:B,env:ge,featureUsage:N,hasFlags:V,hasNotify:Y,identity:I,platformGate:k,queues:R,serverContent:U,services:Z,storageRulesMetadata:se,topics:ne,usesSandbox:ce,useUmbrella:_,workflows:P}=Pm({lunoraDirectory:n,project:a,projectRoot:e.projectRoot,schema:c,target:e.target});Hm(c,c.jurisdiction===void 0?void 0:qm(a,n));const F=E(n,"_generated"),Ce=E(F,"dataModel.ts"),z=E(F,"server.ts"),cr=E(F,"api.ts"),lr=E(F,"internal.ts"),dr=E(F,"functions.ts");We(a,Ce,m),We(a,z,U);const ms=Object.fromEntries(Z.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(ea(p,F))));for(const[p,xt]of Object.entries(ms))We(a,E(F,p),xt);const Oe=da(a,n),le=ga(a,n),lt=k.signals.typedWebSockets!==!1,{apiContent:hs,erased:ur,functions:q,functionModulesContent:vs,functionsContent:Es,httpRoutes:dt,internalContent:xs,mutators:ut}=Nv({agents:l,apiPath:cr,generatedFunctionsPath:dr,internalPath:lr,lazyFunctions:i,roomsSupported:lt,lunoraDirectory:n,migrations:Oe,project:a,shapes:le,useUmbrella:_,usesSandbox:ce,workflows:P}),Ss=vo(a,n),ft=Eo(Ss,c,[...q,...dt].map(p=>p.filePath)),ke=Ss.length>0,ve=e.lint===!1&&!ke?void 0:{callEdges:zm(a,n),inserts:la(a,n),queries:Bs(a,n,q),tableWrites:Vh(a,n),workflowCalls:cv(a,n)},fr=Ea(ve?.queries??Bs(a,n,q)),Re=e.lint===!1||ve===void 0?void 0:Pp(a,n,{callSites:ve,containers:f,crons:g,functions:q,modules:ft,mutators:ut,queues:R,schema:c,shapes:le,workflows:P,wranglerVariables:e.wranglerVariables}),As=Re===void 0?[]:Rp(e.projectRoot,[...Pr(Re,{source:"static"}),...rv(a,n,{byName:new Set([...P,...R,...l,...f].map(p=>p.exportName)),byPath:new Set([...q,...ut,...le,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...jh(a,n),...oa(ur,n),...Na(R,e.wranglerQueueProducers)]),gr=ua(a,n),ys=ch(a,n);yv(le,ys,oh(a,n));const pr=V?Vm(a,n):[],gt=k.signals.vectorStore!==!1,mr=Yo(_e(e.projectRoot,e.target),"deliveryAuthorization"),Ee=Lh(N,{containerCount:f.length,cronCount:g.length,dependencies:v,hasPaymentTables:uh(c.tables),queueCount:R.length,storageColumnCount:Object.keys(ti(c)).length,storageRuleCount:se.rules.length,vectorIndexCount:c.vectorIndexes.length,target:_e(e.projectRoot,e.target),vectorStoreSupported:gt,workflowCount:P.length}),bs=t?St.now():0,pt=xa(c,Oe.map(p=>p.id)),mt=nh(a,n),Ns=Jo({advisories:As.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Re?.procedureProtections??[],agents:l,capabilities:u,containers:f,env:ge,flagKeys:pr,hasFlags:V,hasNotify:Y,hasIpReaders:q.some(p=>p.readsIp===!0)||le.some(p=>p.readsIp===!0),hasRooms:lt&&q.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:l.length>0||q.some(p=>wo(p)),hasSecretValues:k.signals.secretValues===!0,hasSockets:lt&&q.some(p=>p.lifecycle==="socket"),lazyFunctions:i,hasVectors:gt,liveStreamDeclarations:mt,liveStreams:k.signals.liveStreams===!0,maskMetadata:ys,mutators:ut,queues:R,rlsMetadata:gr,schema:c,schemaSnapshot:pt,shapes:le,services:Z,storageRules:se,studioFeatures:Ee,topics:ne,useUmbrella:_,workflowEvents:fv(a,n),workflows:P}),Ps=Ca(le,v.has("@lunora/db"),_),ws=Pa(f,c.jurisdiction),Is=wa(P,{lazy:i}),Ts=Ia(l,{lazy:i}),Cs=Ta(R,e.wranglerQueueProducers),Os=Ua(mt,_),ks=Fa(g),hr=La(Ee.scheduler),Fe=Qo(_e(e.projectRoot,e.target)),vr=Fe.supported?Da(_):"",Er=Ma(c.tables,_,c.jurisdiction),xr=ho(e.projectRoot)?_a(_):"",Rs=za(c.vectorIndexes),Le=$a(c,_),Fs=Oa(v.has("@lunora/seed")),De=e.apiSpec??"openapi",ht=De==="openapi"||De==="both",vt=De==="openrpc"||De==="both",Ls=ma(v.has("@lunora/auth")),Ds=ha({capabilities:u,emailAgents:l.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:v.has("@lunora/cloudflare-access"),hasAuth:v.has("@lunora/auth"),hasFramework:v.has("@lunora/astro")||v.has("@lunora/svelte")||v.has("@lunora/vue")||K(E(e.projectRoot,"src","worker.ts")),hasGlobal:c.tables.some(p=>Jn(p)),hasHyperdriveGlobal:c.tables.some(p=>Zn(p)),hasKvIntrospector:Ee.kv,hasNotify:Y,hasQueue:R.some(p=>p.mode==="push"),liveStreams:k.signals.liveStreams===!0,liveStreamsWithheld:k.liveStreamsWithheld,liveStreamDeclarations:mt,hasAdminRevocations:Fe.supported,hasScheduler:Ee.scheduler,hasSourcedTables:c.tables.some(p=>p.externalSource!==void 0),hasStorage:Ee.storage,hasDeliveryAuthorization:mr,hasVectors:gt,hasWorkflow:P.length>0,identity:I,jurisdiction:c.jurisdiction,jurisdictionPinsAuth:c.jurisdictionPinsAuth===!0,lazyFunctions:i,tables:c.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:_,vectorIndexCount:c.vectorIndexes.length,voiceAgents:l.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:ht,wantsOpenRpc:vt}),{openApiContent:Ms,openApiModuleContent:_s,openRpcContent:zs,openRpcModuleContent:Ks}=xv({functions:q,httpRoutes:dt,modules:ft,projectRoot:e.projectRoot,wantsArchitecture:ke}),xe=ke&&ve!==void 0?Hp({...ve,crons:g,functions:q,httpRoutes:dt,modules:ft,queues:R,schema:c,services:Z,topics:ne,workflows:P}):void 0,Et=E(n,Sv),Sr=K(Et),Ar=e.dryRun?[]:Ev(F,[{content:Ds,kind:"always",name:"app.ts"},{content:m,kind:"always",name:"dataModel.ts"},{content:hs,kind:"always",name:"api.ts"},{content:xs,kind:"always",name:"internal.ts"},{content:U,kind:"always",name:"server.ts"},{content:Es,kind:"always",name:"functions.ts"},{files:vs,kind:"directory",name:ni},{content:Ns,kind:"always",name:"shard.ts"},{content:ks,kind:"always",name:"crons.ts"},{content:Rs,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:ws,kind:"optional",name:"containers.ts"},{content:Is,kind:"optional",name:"workflows.ts"},{content:Ts,kind:"optional",name:"agents.ts"},{content:Cs,kind:"optional",name:"queues.ts"},{content:Os,kind:"optional",name:"live.ts"},{content:hr,kind:"optional",name:"scheduler.ts"},{content:Er,kind:"optional",name:"shardRegistry.ts"},{content:vr,kind:"optional",name:"adminRevocations.ts"},{content:xr,kind:"optional",name:"durableObjects.ts"},{content:Fs,kind:"optional",name:"seed.ts"},{content:Ls,kind:"optional",name:"authModule.ts"},{content:Ps,kind:"optional",name:"collections.ts"},{files:ms,kind:"services"},{content:ht?Ms:"",kind:"optional",name:"openapi.json"},{content:ht?_s:"",kind:"optional",name:"openapi.ts"},{content:vt?zs:"",kind:"optional",name:"openrpc.json"},{content:vt?Ks:"",kind:"optional",name:"openrpc.ts"},{content:xe===void 0?"":`${JSON.stringify(xe,void 0,2)}
31
- `,kind:"optional",name:"architecture.json"},{content:xe===void 0?"":Gp(xe),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!Sr&&Te(Et,wr(pt)),t){const p=St.now(),xt=Math.round(p-s),yr=Math.round(bs-s),br=Math.round(p-bs);console.error(`@lunora/codegen: codegen took ${xt.toString()}ms (discovery ${yr.toString()}ms, emit ${br.toString()}ms)`)}return{advisories:As,advisorContext:Re,agents:l,architecture:xe,containers:f,cronTriggers:[...new Set([...Ka(g),...B])],generated:{agents:Ts,api:hs,app:Ds,authModule:Ls,collections:Ps,containers:ws,crons:ks,dataModel:m,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:vs,functions:Es,internal:xs,live:Os,openApi:Ms,openApiModule:_s,openRpc:zs,openRpcModule:Ks,queues:Cs,seed:Fs,server:U,shard:Ns,vectors:Rs,workflows:Is},migrations:Oe,outputDirectory:F,platformDiagnostics:Fe.diagnostic===void 0?k.diagnostics:[...k.diagnostics,Fe.diagnostic],queues:R,indexReferences:fr,schemaSnapshot:pt,schemaSnapshotPath:Et,schemaTables:c.tables,workflows:P,writtenFiles:Ar}},UE=e=>Lr(()=>Pv(e));export{Sv as SCHEMA_SNAPSHOT_FILENAME,Io as createCodegenProject,jE as findTsconfig,HE as refreshCodegenProject,UE as runCodegen,GE as tsconfigFingerprint};
28
+ Install them with your package manager, then re-run codegen.`)},Jp="env.ts",Zp=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return it(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},em=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&&it(n.getModuleSpecifierValue())}return!1},tm=e=>{if(r.isIdentifier(e))return Zp(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&em(t)}return!1},sm=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!tm(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ce(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=st(s,"member");a!==void 0&&t.push({exportName:a})}return t},nm=(e,t)=>{const s=v(t,Jp);if(!K(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=sm(n);if(i.length!==0){if(i.length>1)throw ce(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},im={defineLiveStream:"liveStreams",defineRoom:"typedWebSockets",defineWebSocket:"socketRoutes"},rm=new Set(["allowedHosts","deniedHosts","interceptHttps"]),om=(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())},am=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),cm=new Set(["durable"]),lm=new Set(["rollback"]),Bi=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},dm="defineApp",Pe="app",Nn=(e,t)=>e.getDescendantsOfKind(d.PropertyAssignment).some(s=>A(s)===Pe&&s.getInitializer()?.getText()===t)||t===Pe&&e.getDescendantsOfKind(d.ShorthandPropertyAssignment).some(s=>A(s)===Pe),um=e=>{if(e===void 0||!zo.includes(e.getSourceFile().getBaseName()))return!1;if(r.isMethodDeclaration(e))return r.isObjectLiteralExpression(e.getParent())&&A(e)===Pe;if(!(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)))return!1;const t=e.getParent();if(r.isPropertyAssignment(t))return A(t)===Pe;if(r.isVariableDeclaration(t))return Nn(e.getSourceFile(),t.getName());const s=r.isFunctionDeclaration(e)?e.getName():void 0;return s!==void 0&&Nn(e.getSourceFile(),s)},fm="AppBuilder",Vi=e=>{const t=e.getSourceFile();return t.getBaseNameWithoutExtension()==="app"&&t.getDirectory().getBaseName()==="_generated"},gm=e=>{const t=e.getType(),s=(t.getConstraint()??t).getSymbol();return s?.getName()===fm&&s.getDeclarations().some(n=>Vi(n))},pm=e=>e.getText()===dm&&(e.getSymbol()?.getDeclarations()??[]).every(t=>r.isImportSpecifier(t)||r.isImportClause(t)||Vi(t)),Ui=(e,t,s=new Set)=>{const n=et(t);if(n===void 0||!r.isIdentifier(n))return!1;if(pm(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 um(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 Ui(e,a.getInitializer(),s)}}return!1},Wi=(e,t)=>{const s=Xt(t.getExpression());return s?.member==="deliveryAuthorization"&&(Ui(e,s.object)||gm(s.object))},mm=new Map([["defineContainer",{keys:rm,signal:"containerEgressPolicy"}],["defineStep",{keys:lm,signal:"workflowRollback"}],["stream",{keys:cm,signal:"durableStreams"}]]),hm=(e,t)=>{const s=mm.get(Bi(t));if(s!==void 0)return t.getArguments().some(n=>am(om(e,n),s.keys))?s.signal:void 0},vm=(e,t)=>im[Bi(t)]??(Wi(e,t)?"deliveryAuthorization":void 0),Em=(e,t,s)=>{const n={containerEgressPolicy:!1,deliveryAuthorization:!1,durableStreams:!1,liveContext:!1,liveStreams:!1,secrets:!1,socketRoutes:!1,typedWebSockets:!1,workflowRollback:!1};for(const i of y(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);if(!n.secrets||!n.liveContext){const c=Lo(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=hm(o,c)??vm(o,c);l!==void 0&&(n[l]=!0)}if(n.liveStreams=n.liveStreams||o.getFullText().includes("defineLiveStream")&&a.some(c=>jn(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 Yt({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(s,Je(s,"utf8"),{overwrite:!0});n.deliveryAuthorization=i.getDescendantsOfKind(d.CallExpression).some(o=>Wi(i,o))}return n},xm=(e,t)=>{const s=Mo();for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(Do(i,s))return!0}return!1},Sm="createWorker",Am="extend",Pn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,wn=e=>{const t=[],s=Pn(D(e,"backupCron"));s!==void 0&&t.push(s);const n=D(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=Pn(i.getNameNode());o!==void 0&&t.push(o)}return t},ym=e=>{const t=C(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Sm)return r.isObjectLiteralExpression(s)?wn(s):[];if(t!==Am||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=Mn(s.getBody());return n===void 0?[]:wn(n)},bm=(e,t)=>{const s=[];for(const{filePath:n}of Ze(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression))s.push(...ym(o))}return[...new Set(s)]},qi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:qi(e.inner)},Nm=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=qi(n);return i!==void 0&&t.has(i)}))},Pm=(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 M("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 M("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})}},wm=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=pd(s,t),a=nm(s,t),c=Ao(s,t),{queues:l,topics:u}=$o(s,t),f=Vo(n),g=ko(s,t);Pm(c,g);const m=Ro(s,t),x=Uo(s,t),N=Fo(s,t,c,g),pe=bm(s,t),P=Em(s,t,Ko(n)),B=Bo(s,t),Y=xm(s,t),w=_o(s,t);w.browser=w.browser||B.usesSandboxBrowser;const W=_e(n,e.target),L=Wo(w,W,{agents:g.length>0,commitOrderedTables:i.tables.some(z=>z.commitOrdered===!0),cronTriggers:N.length>0,crossShardFanout:i.tables.some(z=>Jo(z)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(z=>z.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(z=>z.sandbox===!0),deliveryAuthorization:P.deliveryAuthorization,durableStreams:P.durableStreams,globalTables:i.tables.some(z=>z.shardMode==="global"),liveContext:P.liveContext,liveStreams:P.liveStreams,typedWebSockets:P.typedWebSockets,queues:l.length>0,relationGraph:Nm(i),secretValues:Y,secrets:P.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:B.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(z=>z.schedules!==void 0)}),R=L.usage,Z=Oo(R),ee=L.signals.vectorStore!==!1,ne=L.signals.services===!1?[]:f,ie=ei(n),le=ie??new Set,I=le.has("lunorash");Xp(i,ie,{hasVectors:ee,scheduler:R.scheduler||N.length>0,storage:R.storage||x.rules.length>0||Object.keys(ti(i)).length>0,usage:R});const F=K(v(t,"flags.ts")),V=K(v(t,"notify.ts"));return{agents:g,capabilities:Z,containers:m,crons:N,dataModelContent:sa(i),declaredDependencies:ie,dependencies:le,entryCronTriggers:pe,env:a,featureUsage:R,hasFlags:F,hasNotify:V,identity:o,platformGate:{...L,diagnostics:[...qo(n,e.target),...L.diagnostics,...jo(W,i.vectorIndexes),...P.liveStreams&&P.deliveryAuthorization?[Ho(W)]:[],...P.socketRoutes&&P.deliveryAuthorization?[Go(W)]:[]]},queues:l,serverContent:ea({agents:g,capabilities:Z,containers:m,env:a,hasVectors:ee,hasFlags:F,hasNotify:V,identity:o,queues:l,schema:i,services:ne,storageRuleBuckets:x.rules.map(z=>z.bucket),topics:u,useUmbrella:I,workflows:c}),services:ne,storageRulesMetadata:x,topics:u,usesSandbox:B.usesSandboxBrowser||B.usesSandboxContainer||B.usesSandboxFs,useUmbrella:I,workflows:c}},ji=(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},Im=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},Tm=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Cm=/^[\w$]+:[\w$]+$/u,Om=(e,t)=>{const s=$n(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},In=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 In(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Qt.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?In(s):void 0}}},Rm=(e,t,s)=>({schedule:{argKeys:km(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),Fm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(Kn.has(s))return Om(s,n);if((s==="runAfter"||s==="runAt")&&Im(t)){const l=$n(i)??(r.isStringLiteral(i)&&Cm.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,...Rm(s,n,o)}}const a=Tm.get(s),c=a===void 0?void 0:ji(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},Lm=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),Hi=e=>Cr.isOptionalChain(e.compilerNode),Dm=(e,t)=>r.isIfStatement(t)?!b(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?b(e,t.getStatement()):r.isForStatement(t)?b(e,t.getStatement())||b(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ae(t)?t.getFirstAncestor(ae)!==void 0:r.isConditionalExpression(t)?!b(e,t.getCondition()):r.isBinaryExpression(t)?!b(e,t.getLeft())&&Lm.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&Hi(t)?!b(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Hg(s)),Mm=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&b(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ae);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&b(o.getFirstAncestor(ae),i))===!0},_m=(e,t)=>(r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t))&&b(e,t.getStatement())||r.isForStatement(t)&&(b(e,t.getStatement())||b(t.getIncrementor(),e)),zm=(e,t)=>{if(Hi(e)||t==="schedule"&&Mm(e))return"guard";let s=e,n=!1;for(let i=s.getParent();i!==void 0&&!r.isSourceFile(i);i=i.getParent()){if(Dm(s,i)){if(!_m(s,i))return"guard";n=!0}s=i}return n?"loop":void 0},Tn=(e,t,s)=>{if(s===void 0)return;const n=zm(e,s.kind);return{...s,...n===void 0?{}:{conditional:!0},...n==="loop"?{loopOnly:!0}:{},file:t,line:e.getStartLineNumber(),scope:S(e)}},Km=(e,t)=>[...k(e,t,(s,n)=>Tn(s,n,Fm(s))),...re(e,t,d.PropertyAccessExpression,(s,n)=>{const i=ji(s,"services");return Tn(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],$m=new Set(["boolean","number","object","string"]),Bm=e=>{const t=e.getName();if(!$m.has(t))return;const s=e.getExpression();return Q(s,["flags"])||Q(s,["flags","details"])?t:void 0},Vm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=Bm(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},Um=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of E(i,d.CallExpression)){const a=Vm(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))},Wm=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"||na(o))return;const a=e.getSourceFile().getFilePath();if(ia(i,e,a)){const c=ra(i,e,a,0,new Set);return c===void 0&&oa(o),c}return o},qm=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=Hr(t.getNameNode());return s===void 0||s==="namespace"}),jm=(e,t)=>{for(const{filePath:s}of Ze(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)||qm(a)))return i}}},Hm="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Gm=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ce(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Hm}). 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})},Ym="room:",Qm="__lunora_socket__:",Xm=/^[A-Za-z]\w*$/u,Cn=e=>Xm.test(e),Jm=e=>`${e}:`.startsWith(Ym)||`${e}:`.startsWith(Qm),Gi=e=>e.getProperties().some(t=>r.isSpreadAssignment(t)||r.isComputedPropertyName(t.getNameNode())),Yi=e=>Gi(e)||e.getProperties().some(t=>r.isMethodDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)),On=e=>A(e),us=(e,t)=>e.getProperties().find(s=>(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s))&&A(s)===t),ue=(e,t)=>{const s=ce(e,`defineLiveStream ${t}`);return new M("LIVE_STREAM_NOT_LITERAL",s.message)},Qi=(e,t,s)=>{const n=us(e,t),i=r.isPropertyAssignment(n)?n.getInitializer():void 0;if(i===void 0||!r.isObjectLiteralExpression(i))throw ue(n??e,`needs ${s} so codegen can read its topics`);if(Yi(i))throw ue(i,`cannot spread into or compute the keys of \`${t}\`: codegen must read every name as a literal`);return i},Zm=(e,t)=>{const s=On(t),n=r.isPropertyAssignment(t)?t.getInitializer():void 0;if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(t,`needs an object literal for topic "${s}" ({ key?, payload }), not a reference to one`);if(Yi(n))throw ue(n,`cannot spread into or compute the keys of topic "${s}"`);if(!Cn(s)||Jm(s))throw new M("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(us(n,"key")===void 0)return{fields:[],name:s};const a=Qi(n,"key",`an object literal \`key\` for topic "${s}"`).getProperties().map(l=>On(l)),c=a.find(l=>!Cn(l));if(c!==void 0)throw new M("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}},eh=(e,t,s)=>{const n=e.getArguments()[0];if(n===void 0||!r.isObjectLiteralExpression(n))throw ue(e,"needs an object-literal options argument so codegen can read its `id` and `topics`");if(Gi(n))throw ue(n,"cannot spread its options or use a computed key: codegen must read `id` and `topics` as literals");const i=us(n,"id"),o=r.isPropertyAssignment(i)?i.getInitializer():void 0;if(o===void 0||!r.isStringLiteral(o))throw ue(i??n,'needs a string-literal `id` (e.g. `defineLiveStream({ id: "posts", … })`) so codegen can type its references');const a=o.getLiteralValue(),c=Qi(n,"topics","an object-literal `topics` map");return{exportName:t,filePath:T(s,e.getSourceFile().getFilePath()),id:a,topics:c.getProperties().map(l=>Zm(a,l))}},th=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 M("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)}},sh=e=>{let t=e.getParent();for(;r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isNonNullExpression(t)||r.isParenthesizedExpression(t);)t=t.getParent();return t},nh=(e,t)=>E(e,d.CallExpression).filter(s=>jn(s,"defineLiveStream")).map(s=>{const n=sh(s),i=r.isVariableDeclaration(n)?st(n,"binding"):void 0;if(i===void 0)throw new M("LIVE_STREAM_NOT_EXPORTED",ce(s,"defineLiveStream must be assigned to a named export (`export const posts = defineLiveStream({ … })`), not a default export, a local, or an inline call, so codegen can type its references").message);return eh(s,i,t)}),ih=(e,t)=>{const s=y(t).flatMap(n=>nh(e.getSourceFile(n)??e.addSourceFileAtPath(n),t));return th(s),s},rh=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,oh=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?rh(e):!0,Xi=(e,t=!1)=>{for(const s of e.getProperties()){if(oh(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||Xi(n,!0))return!0}return!1},ah=(e,t)=>{for(const s of y(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of si(n))for(const o of ts(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||Xi(a)))return!0}}return!1},ch=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:Yn(a),table:i})}}return s},lh=(e,t)=>{const s=new Map;for(const n of y(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of si(i))for(const a of ts(o))for(const c of ch(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},dh=["providerSubscriptionId","state"],uh=["providerEventId","processedAt"],kn=(e,t)=>t.every(s=>s in e.shape),fh=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&&kn(t,dh)&&kn(s,uh)},gh=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],ph=(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},mh=(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},hh="@lunora/privacy",Ji="userId",Rn=new Set(["user","users"]),vh=e=>e.replaceAll("\\","/"),Eh="privacy",xh=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),at=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,Te=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",fs=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Sh=(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},ct=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Ah=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Sh(s,"tables"),i=at(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:fs(n).map(a=>Te(a)))t.datasets.set(o,i)},gs=8,ve=(e,t=0)=>{if(t>gs)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return ve(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:ve(i,t+1)},yh=(e,t)=>{const s=e.getArguments()[0],n=s===void 0?void 0:ve(s),i=n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[],o=new Set(i.map(a=>Te(a)));for(const a of gh)o.has(a)||t.datasets.set(a,"authDataset");for(const a of i){const c=r.isPropertyAssignment(a)?at(a.getInitializer()):void 0;c!==void 0&&(t.datasets.set(c,"authDataset"),Te(a)==="user"&&t.userTables.add(c))}},Fn=(e,t,s)=>{t.datasets.set(at(e.getArguments()[0])??s,s)},bh=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[Te(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()]}},Zi=(e,t=0)=>{const s=ve(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>gs)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?Zi(i.getExpression(),t+1):[bh(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},Nh=e=>{const t=e.getArguments()[0];return t===void 0?void 0:Zi(t)},Ph=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:ve(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?fs(n):[])t.excluded.set(Te(i),r.isPropertyAssignment(i)?at(i.getInitializer())??"":"")},wh=(e,t)=>{switch(ct(e)){case"actionCacheDataset":{Fn(e,t,"actionCache");break}case"authDataset":{yh(e,t);break}case"defineDataset":{Ah(e,t);break}case"documentHistoryDataset":{Fn(e,t,"documentHistory");break}}},ps=e=>e!==void 0&&r.isCallExpression(e)&&ct(e)==="defineDataset",er=e=>e!==void 0&&r.isCallExpression(e)&&xh.has(ct(e)??""),Ih=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)&&(ps(i)||er(i))?n:void 0},tr=(e,t,s=0)=>{const n=ve(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>gs)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!tr(i.getExpression(),t,s+1))return!1}else if(!ps(i)&&!er(i)){const o=r.isIdentifier(i)?Ih(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Th=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||tr(t,s)?s:void 0},Ch=(e,t)=>{const s=[];for(const i of E(e,d.CallExpression))if(wh(i,t),ct(i)==="definePrivacy"){const o=Nh(i);Ph(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Th(o)})}return{declared:E(e,d.VariableDeclaration).filter(i=>ps(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Oh=(e,t)=>{const s=v(t,"schema.ts"),n=[...y(t),...K(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>vh(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},kh=(e,t,s)=>{if(s?.has(hh)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[],userTables:Rn};const n={datasets:new Map,excluded:new Map,userTables:new Set(Rn)},i=[],o=[];for(const f of Oh(e,t)){const g=Ch(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:ph(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l,userTables:n.userTables}},sr=(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&&sr(n,t)),Rh=(e,t)=>e.extensionKey!==Eh&&(Ji in e.shape||Object.values(e.shape).some(s=>sr(s,t))),Fh=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 "${Ji}" 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.`,Lh=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Rh(o,t.userTables)).map(o=>o.name),[n]=mh(s,t.classifications);if(n!==void 0)throw new M("PRIVACY_COVERAGE",Fh(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new M("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Dh=(e,t)=>{const s=Yo(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")}},Mh=new Set(["delete","deleteMany","hardDelete","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","replace","restore"]),Ln=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),_h="",zh=(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},Kh=e=>{const t=e.getSymbol()?.getDeclarations()[0];if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getVariableStatement()?.getDeclarationKind()===Qt.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=Kh(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},$h=(e,t)=>{if(Mh.has(e))return{method:e,tables:Ue(t)??[_h]}},Ot=(e,t,s)=>e===void 0?void 0:{...e,fields:zh(t,e.method,s)},Bh=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()===Qt.Const)||s===void 0||!r.isPropertyAccessExpression(s)||!$(s.getExpression())))return s.getName()},Vh=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression(),i=Bh(n);if(i!==void 0)return Ln.has(s)?Ot({method:s,tables:[i]},e,1):void 0;if($(n))return Ot($h(s,e.getArguments()[0]),e,2);if(Ln.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return Ot({method:s,tables:[n.getName()]},e,1)},Uh=(e,t)=>k(e,t,(s,n)=>{const i=Vh(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}))}),Wh=(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"}),qh=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||U(s,"args")===void 0)return!1}return is(e,t).opaque},jh=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=se(a);c!==void 0&&qh(a,c.receiver)&&s.push(Wh(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},Hh=(e,t)=>{const s=[];for(const n of y(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...jh(i,T(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Gh=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),nr=e=>!e.isAny(),ir=e=>{const t=e.getType();if(!nr(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Gh.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Yh=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},rr={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."},Qh=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.`}),Xh={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)."},Jh=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Zh={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)."},ev=(e,t,s)=>{if(!t.some(i=>$r(i)))return Xh;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return Jh.has(s.typeName)&&!n&&!t.some(i=>ma(i))?Zh:rr},or=(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:Qh(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},tv=(e,t,s)=>{const n=[];for(const i of J(e)){const o=r.isIdentifier(i.getNameNode())?Rt(i):[i.getName()],c=o.some(u=>Xe(s,t,u))||!Yh(i)?void 0:ir(i),[l=i.getName()]=o;c!==void 0&&n.push(or(t,l,c,i.getStartLineNumber(),ev(i,o,c)))}return n},sv=(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=ir(i.getExpression());o!==void 0&&n.push(or(t,"default",o,i.getStartLineNumber(),rr))}return n},nv=(e,t,s)=>[...tv(e,t,s),...sv(e,t,s)],iv=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Rt(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=Rt(n).find(o=>Xe(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),rv=({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"}),ov=(e,t,s)=>{const n=[],i=[];for(const a of y(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=T(t,a);n.push(...nv(c,l,s)),i.push(...iv(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!nr(a.getType()))&&n.push(rv(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},av=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"},cv=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},lv=(e,t)=>k(e,t,(s,n)=>av(s)?{file:n,line:s.getStartLineNumber(),scope:S(s),workflow:cv(s)}:void 0),ar=e=>e==="@lunora/workflow",dv=e=>new Set(e.getImportDeclarations().filter(t=>ar(t.getModuleSpecifierValue())).map(t=>t.getNamespaceImport()?.getText()).filter(t=>t!==void 0)),uv=(e,t,s)=>r.isIdentifier(e)?t.has(e.getText()):r.isPropertyAccessExpression(e)&&e.getName()==="defineWorkflowEvent"&&s.has(e.getExpression().getText()),fv=(e,t)=>{const s=Wn(e,"defineWorkflowEvent",ar),n=dv(e);if(s.size===0&&n.size===0)return[];const i=[];for(const o of E(e,d.CallExpression)){if(!uv(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)?st(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 M("WORKFLOW_EVENT_NOT_LITERAL",ce(l??o,`workflow event "${c}": defineWorkflowEvent's \`type\` must be a string literal so codegen can register it for admin sends`).message);i.push({exportName:c,filePath:T(t,e.getFilePath()),type:l.getLiteralValue()})}return i},gv=(e,t)=>{const s=y(t).flatMap(i=>fv(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 M("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))},Ce=(e,t)=>{K(e)&&Je(e,"utf8")===t||Pr(e,t,"utf8")},pv=(e,t)=>{if(t===""){we(e,{force:!0});return}Ce(e,t)},mv=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){we(s,{force:!0,recursive:!0});return}if(K(s))for(const n of Dn(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Gt(e,i)]===void 0&&we(i)}for(const[n,i]of Object.entries(t))jt(Ht(v(e,n)),{recursive:!0}),Ce(v(e,n),i)},hv=(e,t,s)=>{const n=v(e,t);if(Object.keys(s).length===0){we(n,{force:!0,recursive:!0});return}if(K(n))for(const i of Dn(n,{recursive:!0,withFileTypes:!0})){const o=v(i.parentPath,i.name);i.isFile()&&s[Gt(n,o)]===void 0&&we(o)}for(const[i,o]of Object.entries(s)){const a=v(n,i);jt(Ht(a),{recursive:!0}),Ce(a,o)}},vv=e=>{try{const t=Ea(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)},Ev=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,xv=(e,t)=>{K(e)||jt(e,{recursive:!0});const s=[];for(const n of t)switch(n.kind){case"always":{Ce(v(e,n.name),n.content),s.push(n.name);break}case"directory":{hv(e,n.name,n.files),s.push(...Object.keys(n.files).map(i=>v(n.name,i)));break}case"services":{mv(e,n.files),s.push(...Object.keys(n.files));break}default:pv(v(e,n.name),n.content),n.content!==""&&s.push(n.name)}return s},Sv=e=>{const t=vv(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=Aa({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=ba({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
29
+ `,openApiModuleContent:ya(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
30
+ `,openRpcModuleContent:Na(i)}},Av=".lunora-schema.json",yv=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},bv=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new M("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 M("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 M("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})}},Nv=8,Pv=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lazyFunctions:o,lunoraDirectory:a,migrations:c,project:l,roomsSupported:u,shapes:f,usesSandbox:g,useUmbrella:m,workflows:x}=e,N=()=>ca(()=>{const w=Jr(l,a,{lazyFunctions:o}),W=io(l,a);return{functions:w,httpRoutes:la(l,a),mutators:W}});let{erased:pe,value:{functions:P,httpRoutes:B,mutators:Y}}=N();Xr(y(a).map(w=>l.getSourceFileOrThrow(w)),w=>Gt(a,w.getFilePath())),bn([...P,...Y].map(w=>w.filePath)),bn(B.filter(w=>w.stream).map(w=>w.filePath),"http-stream");for(let w=1;;w+=1){const W=u?P:P.filter(I=>I.channel?.kind!=="room"&&I.lifecycle!=="socket"),L=Ra({agents:t,functions:W,httpRoutes:B,mutators:Y,useUmbrella:m,workflows:x}),R={agents:t,functions:W,lazyFunctions:o,migrations:c,mutators:Y,shapes:f,useUmbrella:m,usesSandbox:g},Z=Va(R),ee=Ua(R),ne=Fa({functions:P,useUmbrella:m}),ie=v(a,"_generated",ni),le=[[s,L],[i,ne],[n,Z],...Object.entries(ee).map(([I,F])=>[v(ie,I),F])];if(w>=Nv||le.every(([I,F])=>Ev(l,I,F)))return{apiContent:L,erased:pe,functions:P,functionModulesContent:ee,functionsContent:Z,httpRoutes:B,internalContent:ne,mutators:Y};for(const[I,F]of le)We(l,I,F);({erased:pe,value:{functions:P,httpRoutes:B,mutators:Y}}=N())}},wv=e=>{const t=yv(),s=t?St.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=ho(n),o=e.lazyFunctions===!0||i,a=v(n,"schema.ts");if(!K(a))throw new M("INTERNAL",`schema.ts not found at ${a}`);const c=e.project??To(n);Yr(Wm);const l=ga(c,a,e.projectRoot);Lh(l.tables,kh(c,n,ei(e.projectRoot)));const{agents:u,capabilities:f,containers:g,crons:m,dataModelContent:x,dependencies:N,entryCronTriggers:pe,env:P,featureUsage:B,hasFlags:Y,hasNotify:w,identity:W,platformGate:L,queues:R,serverContent:Z,services:ee,storageRulesMetadata:ne,topics:ie,usesSandbox:le,useUmbrella:I,workflows:F}=wm({lunoraDirectory:n,project:c,projectRoot:e.projectRoot,schema:l,target:e.target});Gm(l,l.jurisdiction===void 0?void 0:jm(c,n));const V=v(n,"_generated"),z=v(V,"dataModel.ts"),cr=v(V,"server.ts"),lr=v(V,"api.ts"),dr=v(V,"internal.ts"),ur=v(V,"functions.ts");We(c,z,x),We(c,cr,Z);const ms=Object.fromEntries(ee.filter(p=>p.rpcEntrypoint!==void 0).flatMap(p=>Object.entries(ta(p,V))));for(const[p,xt]of Object.entries(ms))We(c,v(V,p),xt);const Oe=ua(c,n),de=pa(c,n),lt=L.signals.typedWebSockets!==!1,{apiContent:hs,erased:fr,functions:q,functionModulesContent:vs,functionsContent:Es,httpRoutes:dt,internalContent:xs,mutators:ut}=Pv({agents:u,apiPath:lr,generatedFunctionsPath:ur,internalPath:dr,lazyFunctions:o,roomsSupported:lt,lunoraDirectory:n,migrations:Oe,project:c,shapes:de,useUmbrella:I,usesSandbox:le,workflows:F}),Ss=Eo(c,n),ft=xo(Ss,l,[...q,...dt].map(p=>p.filePath)),ke=Ss.length>0,Ee=e.lint===!1&&!ke?void 0:{callEdges:Km(c,n),inserts:da(c,n),queries:Bs(c,n,q),tableWrites:Uh(c,n),workflowCalls:lv(c,n)},gr=xa(Ee?.queries??Bs(c,n,q)),Re=e.lint===!1||Ee===void 0?void 0:wp(c,n,{callSites:Ee,containers:g,crons:m,functions:q,modules:ft,mutators:ut,queues:R,schema:l,shapes:de,workflows:F,wranglerVariables:e.wranglerVariables}),As=Re===void 0?[]:Fp(e.projectRoot,[...wr(Re,{source:"static"}),...ov(c,n,{byName:new Set([...F,...R,...u,...g].map(p=>p.exportName)),byPath:new Set([...q,...ut,...de,...Oe].map(p=>`${p.filePath}:${p.exportName}`))}),...Hh(c,n),...aa(fr,n),...Pa(R,e.wranglerQueueProducers)]),pr=fa(c,n),ys=lh(c,n);bv(de,ys,ah(c,n));const mr=Y?Um(c,n):[],gt=L.signals.vectorStore!==!1,hr=Qo(_e(e.projectRoot,e.target),"deliveryAuthorization"),xe=Dh(B,{containerCount:g.length,cronCount:m.length,dependencies:N,hasPaymentTables:fh(l.tables),queueCount:R.length,storageColumnCount:Object.keys(ti(l)).length,storageRuleCount:ne.rules.length,vectorIndexCount:l.vectorIndexes.length,target:_e(e.projectRoot,e.target),vectorStoreSupported:gt,workflowCount:F.length}),bs=t?St.now():0,pt=Sa(l,Oe.map(p=>p.id)),mt=ih(c,n),Ns=Zo({advisories:As.filter(p=>p.name!=="procedure_type_check_unavailable"),advisorProcedures:Re?.procedureProtections??[],agents:u,capabilities:f,containers:g,env:P,flagKeys:mr,hasFlags:Y,hasNotify:w,hasIpReaders:q.some(p=>p.readsIp===!0)||de.some(p=>p.readsIp===!0),hasRooms:lt&&q.some(p=>p.channel?.kind==="room"),hasSensitiveArgs:u.length>0||q.some(p=>Io(p)),hasSecretValues:L.signals.secretValues===!0,hasSockets:lt&&q.some(p=>p.lifecycle==="socket"),lazyFunctions:o,hasVectors:gt,liveStreamDeclarations:mt,liveStreams:L.signals.liveStreams===!0,maskMetadata:ys,mutators:ut,queues:R,rlsMetadata:pr,schema:l,schemaSnapshot:pt,shapes:de,services:ee,storageRules:ne,studioFeatures:xe,topics:ie,useUmbrella:I,workflowEvents:gv(c,n),workflows:F}),Ps=Oa(de,N.has("@lunora/db"),I),ws=wa(g,l.jurisdiction),Is=Ia(F,{lazy:o}),Ts=Ta(u,{lazy:o}),Cs=Ca(R,e.wranglerQueueProducers),Os=Wa(mt,I),ks=La(m),vr=Da(xe.scheduler),Fe=Xo(_e(e.projectRoot,e.target)),Er=Fe.supported?Ma(I):"",xr=_a(l.tables,I,l.jurisdiction),Sr=vo(e.projectRoot)?za(I):"",Rs=Ka(l.vectorIndexes),Le=Ba(l,I),Fs=ka(N.has("@lunora/seed")),De=e.apiSpec??"openapi",ht=De==="openapi"||De==="both",vt=De==="openrpc"||De==="both",Ls=ha(N.has("@lunora/auth")),Ds=va({capabilities:f,emailAgents:u.filter(p=>p.onEmail===!0).map(p=>({className:p.className,exportName:p.exportName})),hasAccess:N.has("@lunora/cloudflare-access"),hasAuth:N.has("@lunora/auth"),hasFramework:N.has("@lunora/astro")||N.has("@lunora/svelte")||N.has("@lunora/vue")||K(v(e.projectRoot,"src","worker.ts")),hasGlobal:l.tables.some(p=>Jn(p)),hasHyperdriveGlobal:l.tables.some(p=>Zn(p)),hasKvIntrospector:xe.kv,hasNotify:w,hasQueue:R.some(p=>p.mode==="push"),liveStreams:L.signals.liveStreams===!0,liveStreamsWithheld:L.liveStreamsWithheld,liveStreamDeclarations:mt,hasAdminRevocations:Fe.supported,hasScheduler:xe.scheduler,hasSourcedTables:l.tables.some(p=>p.externalSource!==void 0),hasStorage:xe.storage,hasDeliveryAuthorization:hr,hasVectors:gt,hasWorkflow:F.length>0,identity:W,jurisdiction:l.jurisdiction,jurisdictionPinsAuth:l.jurisdictionPinsAuth===!0,lazyFunctions:o,tables:l.tables.map(p=>({name:p.name,shardMode:p.shardMode})),useUmbrella:I,vectorIndexCount:l.vectorIndexes.length,voiceAgents:u.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsArchitecture:ke,wantsOpenApi:ht,wantsOpenRpc:vt}),{openApiContent:Ms,openApiModuleContent:_s,openRpcContent:zs,openRpcModuleContent:Ks}=Sv({functions:q,httpRoutes:dt,modules:ft,projectRoot:e.projectRoot,wantsArchitecture:ke}),Se=ke&&Ee!==void 0?Gp({...Ee,crons:m,functions:q,httpRoutes:dt,modules:ft,queues:R,schema:l,services:ee,topics:ie,workflows:F}):void 0,Et=v(n,Av),Ar=K(Et),yr=e.dryRun?[]:xv(V,[{content:Ds,kind:"always",name:"app.ts"},{content:x,kind:"always",name:"dataModel.ts"},{content:hs,kind:"always",name:"api.ts"},{content:xs,kind:"always",name:"internal.ts"},{content:Z,kind:"always",name:"server.ts"},{content:Es,kind:"always",name:"functions.ts"},{files:vs,kind:"directory",name:ni},{content:Ns,kind:"always",name:"shard.ts"},{content:ks,kind:"always",name:"crons.ts"},{content:Rs,kind:"always",name:"vectors.ts"},{content:Le.global,kind:"always",name:"drizzle.global.ts"},{content:Le.shard,kind:"always",name:"drizzle.shard.ts"},{content:ws,kind:"optional",name:"containers.ts"},{content:Is,kind:"optional",name:"workflows.ts"},{content:Ts,kind:"optional",name:"agents.ts"},{content:Cs,kind:"optional",name:"queues.ts"},{content:Os,kind:"optional",name:"live.ts"},{content:vr,kind:"optional",name:"scheduler.ts"},{content:xr,kind:"optional",name:"shardRegistry.ts"},{content:Er,kind:"optional",name:"adminRevocations.ts"},{content:Sr,kind:"optional",name:"durableObjects.ts"},{content:Fs,kind:"optional",name:"seed.ts"},{content:Ls,kind:"optional",name:"authModule.ts"},{content:Ps,kind:"optional",name:"collections.ts"},{files:ms,kind:"services"},{content:ht?Ms:"",kind:"optional",name:"openapi.json"},{content:ht?_s:"",kind:"optional",name:"openapi.ts"},{content:vt?zs:"",kind:"optional",name:"openrpc.json"},{content:vt?Ks:"",kind:"optional",name:"openrpc.ts"},{content:Se===void 0?"":`${JSON.stringify(Se,void 0,2)}
31
+ `,kind:"optional",name:"architecture.json"},{content:Se===void 0?"":Yp(Se),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&!Ar&&Ce(Et,Ir(pt)),t){const p=St.now(),xt=Math.round(p-s),br=Math.round(bs-s),Nr=Math.round(p-bs);console.error(`@lunora/codegen: codegen took ${xt.toString()}ms (discovery ${br.toString()}ms, emit ${Nr.toString()}ms)`)}return{advisories:As,advisorContext:Re,agents:u,architecture:Se,containers:g,cronTriggers:[...new Set([...$a(m),...pe])],generated:{agents:Ts,api:hs,app:Ds,authModule:Ls,collections:Ps,containers:ws,crons:ks,dataModel:x,drizzleGlobal:Le.global,drizzleShard:Le.shard,functionModules:vs,functions:Es,internal:xs,live:Os,openApi:Ms,openApiModule:_s,openRpc:zs,openRpcModule:Ks,queues:Cs,seed:Fs,server:Z,shard:Ns,vectors:Rs,workflows:Is},migrations:Oe,outputDirectory:V,platformDiagnostics:Fe.diagnostic===void 0?L.diagnostics:[...L.diagnostics,Fe.diagnostic],queues:R,indexReferences:gr,schemaSnapshot:pt,schemaSnapshotPath:Et,schemaTables:l.tables,workflows:F,writtenFiles:yr}},WE=e=>Dr(()=>wv(e));export{Av as SCHEMA_SNAPSHOT_FILENAME,To as createCodegenProject,HE as findTsconfig,GE as refreshCodegenProject,WE as runCodegen,YE as tsconfigFingerprint};