@lunora/codegen 1.0.0-alpha.273 → 1.0.0-alpha.274
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -3
- package/dist/index.d.ts +1 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-UlgFl8hS.mjs +11 -0
- package/dist/packem_shared/emitServer-CYjqZ3W8.mjs +1 -0
- package/dist/packem_shared/{emitServer-BSMUAt0o.mjs → server-dr22ile6.mjs} +56 -56
- package/package.json +3 -3
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DHYzuzTc.mjs +0 -11
package/dist/index.d.mts
CHANGED
|
@@ -3657,8 +3657,6 @@ interface EmitServerOptions {
|
|
|
3657
3657
|
* the base optional binding record — byte-identical to today.
|
|
3658
3658
|
*/
|
|
3659
3659
|
env?: EnvIR;
|
|
3660
|
-
/** Absolute `_generated/` directory, so an RPC service's entry module is imported by a path relative to it. Required with `services`. */
|
|
3661
|
-
generatedDirectory?: string;
|
|
3662
3660
|
/** The project declares `lunora/flags.ts` — wires `ctx.flags` (OpenFeature) onto every ctx. */
|
|
3663
3661
|
hasFlags?: boolean;
|
|
3664
3662
|
/** The project declares `lunora/notify.ts` — wires `ctx.notify` + its `ctx.push` alias (`@lunora/notify`) onto every ctx. */
|
|
@@ -3686,7 +3684,7 @@ interface EmitServerOptions {
|
|
|
3686
3684
|
useUmbrella?: boolean;
|
|
3687
3685
|
workflows?: ReadonlyArray<WorkflowIR>;
|
|
3688
3686
|
}
|
|
3689
|
-
declare const emitServer: ({ agents, capabilities, containers, env, hasVectors, hasFlags, hasNotify, identity, queues, schema,
|
|
3687
|
+
declare const emitServer: ({ agents, capabilities, containers, env, hasVectors, hasFlags, hasNotify, identity, queues, schema, services, storageRuleBuckets, topics, useUmbrella, workflows }?: EmitServerOptions) => string;
|
|
3690
3688
|
interface EmitShardOptions {
|
|
3691
3689
|
advisories?: ReadonlyArray<Finding>;
|
|
3692
3690
|
/** Every declared procedure — the health map's denominator, served via `getAdvisorProcedures`. */
|
package/dist/index.d.ts
CHANGED
|
@@ -3657,8 +3657,6 @@ interface EmitServerOptions {
|
|
|
3657
3657
|
* the base optional binding record — byte-identical to today.
|
|
3658
3658
|
*/
|
|
3659
3659
|
env?: EnvIR;
|
|
3660
|
-
/** Absolute `_generated/` directory, so an RPC service's entry module is imported by a path relative to it. Required with `services`. */
|
|
3661
|
-
generatedDirectory?: string;
|
|
3662
3660
|
/** The project declares `lunora/flags.ts` — wires `ctx.flags` (OpenFeature) onto every ctx. */
|
|
3663
3661
|
hasFlags?: boolean;
|
|
3664
3662
|
/** The project declares `lunora/notify.ts` — wires `ctx.notify` + its `ctx.push` alias (`@lunora/notify`) onto every ctx. */
|
|
@@ -3686,7 +3684,7 @@ interface EmitServerOptions {
|
|
|
3686
3684
|
useUmbrella?: boolean;
|
|
3687
3685
|
workflows?: ReadonlyArray<WorkflowIR>;
|
|
3688
3686
|
}
|
|
3689
|
-
declare const emitServer: ({ agents, capabilities, containers, env, hasVectors, hasFlags, hasNotify, identity, queues, schema,
|
|
3687
|
+
declare const emitServer: ({ agents, capabilities, containers, env, hasVectors, hasFlags, hasNotify, identity, queues, schema, services, storageRuleBuckets, topics, useUmbrella, workflows }?: EmitServerOptions) => string;
|
|
3690
3688
|
interface EmitShardOptions {
|
|
3691
3689
|
advisories?: ReadonlyArray<Finding>;
|
|
3692
3690
|
/** Every declared procedure — the health map's denominator, served via `getAdvisorProcedures`. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as f,toAdvisorContext as d}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as l,errorAdvisoryNames as n,errorPlatformDiagnosticNames as c,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as C,discoverAgents as N}from"./packem_shared/AGENTS_FILENAME-lBe4g_sU.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-DCyIyPa7.mjs";import{default as h}from"./packem_shared/discoverAuthApiCalls-TA2a8bZI.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-CY43AXXN.mjs";import{default as P}from"./packem_shared/discoverCrons-PQeDYVPc.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as U,mayReadCapabilityContext as y,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-DARbl-4Z.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-DXltN9DD.mjs";import{default as W}from"./packem_shared/discoverFunctions-4sef11AC.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-CLGXL19M.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-imtma-ic.mjs";import{default as w}from"./packem_shared/discoverInserts-CKEO1mZZ.mjs";import{d as Y}from"./packem_shared/index-CRO3TRxd.mjs";import{default as Z}from"./packem_shared/discoverMigrations-DYQbnqow.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-BxRrG_s-.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-BfdM93-8.mjs";import{NOTIFY_FILENAME as ae,discoverNotifyCalls as ie,discoverNotifyConfig as me}from"./packem_shared/NOTIFY_FILENAME-J5MGAkca.mjs";import{default as de}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-DEkIMaBP.mjs";import{QUEUES_FILENAME as ce,discoverQueues as xe}from"./packem_shared/QUEUES_FILENAME-DeJw5eqU.mjs";import{default as Ee}from"./packem_shared/discoverR2sqlCalls-BRIyb8Cl.mjs";import{default as Ae}from"./packem_shared/discoverRlsProcedures-BtT8-r93.mjs";import{default as ge}from"./packem_shared/discoverRlsMetadata-rpiO4wSi.mjs";import{discoverSandboxUsage as Ne}from"./packem_shared/discoverSandboxUsage-B8P9QjWZ.mjs";import{default as Re}from"./packem_shared/discoverSchema-BdmC-kO2.mjs";import{readServiceBindings as _e,resolveServiceBindings as he}from"./packem_shared/readServiceBindings-DuE9xlvV.mjs";import{SHAPES_FILENAME as Le,discoverShapes as Me}from"./packem_shared/SHAPES_FILENAME-CeBFuc8M.mjs";import{default as Pe}from"./packem_shared/discoverStorageRulesMetadata-C2hYksmI.mjs";import{WORKFLOWS_FILENAME as be,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-B47AB5pc.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-BdVXkH7A.mjs";import{isD1GlobalTable as je,isHyperdriveGlobalTable as Be}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as We,emitOpenApi as Ke,emitOpenApiModule as Ve}from"./packem_shared/buildOpenApiDocument-6VJGU6fU.mjs";import{OPENRPC_VERSION as Qe,buildOpenRpcDocument as qe,emitOpenRpc as we,emitOpenRpcModule as Je}from"./packem_shared/OPENRPC_VERSION-B8RT1JYn.mjs";import{DEFAULT_TARGET as Xe,platformMatrixIds as Ze,readProjectTarget as $e,resolveCodegenTarget as er}from"./packem_shared/DEFAULT_TARGET-rlz3WdHe.mjs";import{l as or,r as tr}from"./packem_shared/project-config-file-Bv2l-Kmm.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ar,createCodegenProject as ir,findTsconfig as mr,refreshCodegenProject as fr,runCodegen as dr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-UlgFl8hS.mjs";import{SchemaSnapshotParseError as lr,buildSchemaSnapshot as nr,evaluateSchemaDrift as cr,parseSchemaSnapshot as xr}from"./packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs";import{default as Er}from"./packem_shared/fingerprintSchemaSources-ChYfrghz.mjs";import{schemaFromIr as Ar}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as gr,validatorIrToJsonSchema as Cr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Or,SDK_TARGETS as Rr,generateSdk as Tr}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as hr,secretKindOf as Ir}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as Mr}from"./packem_shared/emitDrizzleSchema-DohtnI8c.mjs";import{default as Pr}from"./packem_shared/emitFunctions-evl8Mx1a.mjs";import{e as br}from"./packem_shared/server-dr22ile6.mjs";import{e as yr}from"./packem_shared/shard-C1ZGdOG1.mjs";import{G as Hr}from"./packem_shared/shared-BXUKWh7t.mjs";import{MESSAGE_SOLUTIONS as Br,findSolutionByMessage as kr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as Kr,findProjectConfigFile as Vr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{s as Qr,t as qr,u as wr}from"./packem_shared/shard-runtime-DGrBvQWg.mjs";import{emitApi as Yr,emitCollections as Xr}from"./packem_shared/emitApi-xDIHPRPH.mjs";import{emitCrons as $r,emitScheduler as eo,emitVectors as ro,emitWranglerCronTriggers as oo}from"./packem_shared/emitCrons-DKeoaeqU.mjs";import{emitDataModel as so}from"./packem_shared/emitDataModel-DSk9AkJe.mjs";import{isTypedSchema as io}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{C as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Xe as DEFAULT_TARGET,j as FLAGS_FILENAME,Hr as GENERATED_HEADER,gr as LUNORA_ERROR_CODES,Br as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,ae as NOTIFY_FILENAME,Qe as OPENRPC_VERSION,Kr as PROJECT_CONFIG_FILENAMES,ce as QUEUES_FILENAME,ar as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Or as SDK_LANGUAGES,Rr as SDK_TARGETS,Le as SHAPES_FILENAME,lr as SchemaSnapshotParseError,e as VERSION,be as WORKFLOWS_FILENAME,We as buildOpenApiDocument,qe as buildOpenRpcDocument,nr as buildSchemaSnapshot,b as capabilitiesUsedBy,ir as createCodegenProject,l as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,N as discoverAgents,h as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyConfig,le as discoverQueries,xe as discoverQueues,Ee as discoverR2sqlCalls,ge as discoverRlsMetadata,Ae as discoverRlsProcedures,Ne as discoverSandboxUsage,Re as discoverSchema,Me as discoverShapes,Pe as discoverStorageRulesMetadata,Ue as discoverWorkflows,Qr as emitAgents,Yr as emitApi,Ge as emitApp,Xr as emitCollections,qr as emitContainers,$r as emitCrons,so as emitDataModel,Mr as emitDrizzleSchema,Pr as emitFunctions,Ke as emitOpenApi,Ve as emitOpenApiModule,we as emitOpenRpc,Je as emitOpenRpcModule,eo as emitScheduler,br as emitServer,yr as emitShard,ro as emitVectors,wr as emitWorkflows,oo as emitWranglerCronTriggers,n as errorAdvisoryNames,c as errorPlatformDiagnosticNames,cr as evaluateSchemaDrift,kr as findLunoraSolution,Vr as findProjectConfigFile,mr as findTsconfig,Er as fingerprintSchemaSources,U as foldCapabilitySignals,m as formatAdvisories,Tr as generateSdk,je as isD1GlobalTable,Be as isHyperdriveGlobalTable,R as isTestPath,io as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,or as loadProjectConfig,y as mayReadCapabilityContext,xr as parseSchemaSnapshot,Ze as platformMatrixIds,de as readPackageDependencies,tr as readProjectConfigLiterals,$e as readProjectTarget,_e as readServiceBindings,hr as redact,fr as refreshCodegenProject,er as resolveCodegenTarget,he as resolveServiceBindings,dr as runCodegen,Ar as schemaFromIr,Ir as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,d as toAdvisorContext,Cr as validatorIrToJsonSchema};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{existsSync as T,mkdirSync as Us,rmSync as lt,readdirSync as Zn,readFileSync as er,writeFileSync as tr}from"node:fs";import{join as h,dirname as de,relative as sr}from"node:path";import{performance as tt}from"node:perf_hooks";import{runAdvisor as nr}from"@lunora/advisor";import{LunoraError as Y}from"@lunora/errors";import{readJsonSync as rr}from"@visulima/fs";import{SyntaxKind as d,Node as i,Project as es}from"ts-morph";import{serializeSchemaSnapshot as ir}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as or}from"./formatAdvisories-DwmUKYuc.mjs";import{r as ar,a as y,s as cr,b as lr}from"./project-config-file-Bv2l-Kmm.mjs";import{a as Ce,d as dr,r as ur}from"./modules-6EEBTEDo.mjs";import{WORKFLOWS_FILENAME as fr,discoverWorkflows as gr}from"./WORKFLOWS_FILENAME-B47AB5pc.mjs";import{r as pr}from"./json-data-Chfs2Cz5.mjs";import{s as Be}from"./paths-C-9fwEgQ.mjs";import{G as mr}from"./shared-BXUKWh7t.mjs";import{CAPABILITIES as hr,usedCapabilities as vr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as js,isHyperdriveGlobalTable as Vs}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Er}from"./AGENTS_FILENAME-lBe4g_sU.mjs";import{discoverContainers as xr}from"./CONTAINERS_FILENAME-CY43AXXN.mjs";import Sr from"./discoverCrons-PQeDYVPc.mjs";import{diagnosticAt as ve}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as $e}from"./module-specifiers-WF8iAydP.mjs";import{a as qs,b as j,d as K,f as k,g as At,c as v,w as bt,k as yr,l as Ar,h as br,j as dt,i as Nr}from"./attribution-NRssTEkk.mjs";import{contextPropertiesRead as Pr,discoverFeatureUsage as wr}from"./capabilitiesUsedBy-DARbl-4Z.mjs";import Ir from"./readPackageDependencies-RHhGiz0k.mjs";import{listLunoraSourceFiles as x,unwrapExpression as E,listSecurityScanFiles as Ue,objectLiteralFromCallbackBody as Ws,propertyInitializer as w,lunoraRelativePath as I,bindingKeyName as Ee,collectCallRows as C,findObjectProperty as L,collectSecurityCallRows as Cr,collectNodeRows as ut,RUN_METHODS as Hs,functionReferenceSegments as Gs,limitNameOf as Ys,optionsObjectLiteral as Qs,handlerOf as Tr,chainRootOf as Nt,outermostValueWrapper as N,isWriteTarget as je,isSameNode as pe,isConstDeclaration as Z,returningFunctionOf as ft,walkChain as Or,memberAccessOf as Rr,isTestPath as kr}from"./isTestPath-DCyIyPa7.mjs";import{discoverQueueDeclarations as Fr}from"./QUEUES_FILENAME-DeJw5eqU.mjs";import{discoverSandboxUsage as Dr}from"./discoverSandboxUsage-B8P9QjWZ.mjs";import{resolveServiceBindings as Lr}from"./readServiceBindings-DuE9xlvV.mjs";import Mr from"./discoverStorageRulesMetadata-C2hYksmI.mjs";import{a as A,c as W,d as Xs,e as _r}from"./classify-procedure-call-BBKuBvKg.mjs";import{i as Kr}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as zr,resolveCodegenTarget as Js,readTargetDiagnostics as Br,studioPlatformFor as $r}from"./DEFAULT_TARGET-rlz3WdHe.mjs";import{b as Zs,e as Ur}from"./shard-C1ZGdOG1.mjs";import{e as jr,a as Vr}from"./server-dr22ile6.mjs";import{emitDataModel as qr}from"./emitDataModel-DSk9AkJe.mjs";import{a as ts,r as st,i as $,b as Wr,m as en,c as Ve,e as tn,E as sn,C as nn,d as Hr,f as Gr,g as Yr}from"./context-root-IuI71QkK.mjs";import{r as qe,s as Qr}from"./parse-validator-DYdT7Hyf.mjs";import Xr from"./discoverAuthApiCalls-TA2a8bZI.mjs";import{i as Jr,a as Zr,e as ei,b as ti,d as si,c as ni}from"./unwrap-handler-return-Dy8h5-I6.mjs";import ri from"./discoverFunctions-4sef11AC.mjs";import ii from"./discoverHttpRoutes-CLGXL19M.mjs";import oi from"./discoverHyperdriveCalls-imtma-ic.mjs";import ai from"./discoverInserts-CKEO1mZZ.mjs";import{m as Pt,a as Fe,s as rn,d as ci}from"./index-CRO3TRxd.mjs";import{e as on}from"./exported-procedure-chains-DqU-ZCbG.mjs";import li from"./discoverMigrations-DYQbnqow.mjs";import{i as _,r as an}from"./database-calls-BFY_pIUf.mjs";import{MUTATORS_FILENAME as di,isDefineMutatorCallee as ui,mutatorServerImplOf as fi,discoverMutators as gi}from"./MUTATORS_FILENAME-BxRrG_s-.mjs";import pi from"./discoverNondeterministicCalls-BfdM93-8.mjs";import{discoverNotifyConfig as mi,discoverNotifyCalls as hi}from"./NOTIFY_FILENAME-J5MGAkca.mjs";import vi from"./discoverQueries-DEkIMaBP.mjs";import Ei from"./discoverR2sqlCalls-BRIyb8Cl.mjs";import xi from"./discoverRlsProcedures-BtT8-r93.mjs";import Si from"./discoverRlsMetadata-rpiO4wSi.mjs";import yi from"./discoverSchema-BdmC-kO2.mjs";import{secretKindOf as Ai,redact as bi,isHeuristicSecretKind as Ni,isSecretishName as Pi}from"./redact-Cy14LEnc.mjs";import{discoverShapes as wi}from"./SHAPES_FILENAME-CeBFuc8M.mjs";import{i as Ii}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as Ci}from"./emitApp-BdVXkH7A.mjs";import{buildOpenApiDocument as Ti,emitOpenApiModule as Oi}from"./buildOpenApiDocument-6VJGU6fU.mjs";import{buildOpenRpcDocument as Ri,emitOpenRpcModule as ki}from"./OPENRPC_VERSION-B8RT1JYn.mjs";import{buildSchemaSnapshot as Fi}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Di,emitSeed as Li,emitApi as Mi}from"./emitApi-xDIHPRPH.mjs";import{t as _i,u as Ki,s as zi,v as Bi}from"./shard-runtime-DGrBvQWg.mjs";import{emitCrons as $i,emitScheduler as Ui,emitShardRegistry as ji,emitDurableObjects as Vi,emitVectors as qi,emitWranglerCronTriggers as Wi}from"./emitCrons-DKeoaeqU.mjs";import Hi from"./emitDrizzleSchema-DohtnI8c.mjs";import Gi from"./emitFunctions-evl8Mx1a.mjs";const ss={error:"ERROR",info:"INFO",warn:"WARN"},ns={ERROR:2,INFO:0,WARN:1},Yi=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"}),Qi=(e,t)=>{const{advisor:s}=ar(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,r=n!==void 0&&Object.hasOwn(ss,n)?ss[n]:void 0;return r===void 0?[...t,Yi(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=>ns[o.level]>=ns[r])},Xi={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Ji="crons",Zi=fr.replace(/\.ts$/u,""),oe=(e,t)=>`${Be(e)}:${t}`,nt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},eo=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Xi[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,...nt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...nt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...nt("workflow",t.workflow,"workflow name")}))],to=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",so=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:to(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},no=e=>eo(e).flatMap(t=>so(t)),ro=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}`,r=s??n;return{file:Ji,from:`cron:${t.name}`,kind:"trigger",line:0,...r===void 0?{reason:"the cron has no target"}:{to:r}}})],io=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),le=(e,t)=>t===void 0?e:{...e,module:t},oo=e=>{const t=new Map,s=new Map,n=io(e.modules),r=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&r(l,c.id)},a=(c,l)=>{c!==void 0&&r(oe(c.file,c.exportName),l)};for(const c of e.functions){const l=oe(c.filePath,c.exportName),u=`${Be(c.filePath)}.${c.exportName}`;o(le({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Ce(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=oe(c.filePath,c.exportName);o(le({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Ce(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(le({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(le({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Ce(e.modules,c.filePath)),oe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(le({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Ce(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},oe(Zi,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}},ao=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,co=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(oe(e.file,e.exportName))??{reason:ao(e.exportName)},lo=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=co(e,t);if("reason"in n)return n;const{to:r}=e;return s.has(r)?{drawn:n.map(o=>({from:o,kind:e.kind,to:r}))}:{reason:`${r} is not declared`}},rt=e=>`${e.from}|${e.kind}|${e.to}`,uo=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,fo=e=>{const{nodes:t,sites:s}=oo(e),n=new Map,r=new Map;for(const o of[...ro(e),...no(e)]){const a=lo(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(rt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};r.set(uo(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>rt(o).localeCompare(rt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...r.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},go=e=>`${mr}export const architecture = ${pr(e,"Record<string, unknown>")};
|
|
2
|
+
`,rs=(e,t="api")=>{const s=new Map;for(const n of e){const r=Be(n),o=s.get(r);if(o===void 0){s.set(r,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${r}" twice and the dispatch key "${r}:<fn>" would be ambiguous`:`the generated api.ts would declare "${r}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new Y("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${r}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},po=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:r=!1,usage:o}=t,a=[];e.tables.some(c=>js(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=>Vs(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),r&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:hr)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)},mo=(e,t,s={})=>{if(t===void 0)return;const n=po(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const r=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
3
|
+
`);throw new Y("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
4
|
+
${r}
|
|
5
|
+
|
|
6
|
+
Install them with your package manager, then re-run codegen.`)},ho="env.ts",vo=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return $e(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Eo=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&$e(n.getModuleSpecifierValue())}return!1},xo=e=>{if(i.isIdentifier(e))return vo(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&Eo(t)}return!1},So=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!xo(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ve(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=qs(s,"member");a!==void 0&&t.push({exportName:a})}return t},yo=(e,t)=>{const s=h(t,ho);if(!T(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=So(n);if(r.length!==0){if(r.length>1)throw ve(n,`lunora/env.ts declares ${r.length.toString()} defineEnv() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},cn="identity.ts",Ao=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return $e(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},bo=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&$e(n.getModuleSpecifierValue())}return!1},No=e=>{if(i.isIdentifier(e))return Ao(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&bo(t)}return!1},Po=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!No(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw ve(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=qs(s,"member");a!==void 0&&t.push({exportName:a})}return t},wo=(e,t)=>{const s=h(t,cn);if(!T(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=Po(n);if(r.length!==0){if(r.length>1)throw ve(n,`lunora/identity.ts declares ${r.length.toString()} defineIdentity() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},Io=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Co=(e,t)=>{const s=E(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return E(e.getDescendantsOfKind(d.VariableDeclaration).find(r=>r.getName()===n)?.getInitializer())},To=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(y(s));if(!i.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=E(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Oo=new Set(["durable"]),Ro=new Set(["rollback"]),ko=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},Fo=new Map([["defineContainer",{keys:Io,signal:"containerEgressPolicy"}],["defineStep",{keys:Ro,signal:"workflowRollback"}],["stream",{keys:Oo,signal:"durableStreams"}]]),Do=(e,t)=>{const s=Fo.get(ko(t));if(s!==void 0)return t.getArguments().some(n=>To(Co(e,n),s.keys))?s.signal:void 0},Lo=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Pr(r).has("secrets"));for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=Do(r,o);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},Mo="createWorker",_o="extend",is=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,os=e=>{const t=[],s=is(w(e,"backupCron"));s!==void 0&&t.push(s);const n=w(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)&&!i.isMethodDeclaration(r))continue;const o=is(r.getNameNode());o!==void 0&&t.push(o)}return t},Ko=e=>{const t=A(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Mo)return i.isObjectLiteralExpression(s)?os(s):[];if(t!==_o||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=Ws(s.getBody());return n===void 0?[]:os(n)},zo=(e,t)=>{const s=[];for(const{filePath:n}of Ue(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression))s.push(...Ko(o))}return[...new Set(s)]},ln=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:ln(e.inner)},Bo=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const r=ln(n);return r!==void 0&&t.has(r)}))},$o=(e,t)=>{const s=new Map,n=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const o=s.get(r.name);if(o!==void 0)throw new Y("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${o} and agent "${r.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(r.className);if(a!==void 0)throw new Y("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${a} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Uo=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:r}=e,o=wo(s,t),a=yo(s,t),c=gr(s,t),{queues:l,topics:u}=Fr(s,t),p=Lr(n),f=Er(s,t);$o(c,f);const m=xr(s,t),S=Mr(s,t),z=Sr(s,t,c,f),V=zo(s,t),P=Lo(s,t),F=Dr(s,t),q=wr(s,t);q.browser=q.browser||F.usesSandboxBrowser;const H=zr(q,Js(n,e.target),{agents:f.length>0,commitOrderedTables:r.tables.some(R=>R.commitOrdered===!0),cronTriggers:z.length>0,crossShardFanout:r.tables.some(R=>Kr(R)),containerEgressPolicy:P.containerEgressPolicy,containerRuntimeScheduling:m.some(R=>R.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(R=>R.sandbox===!0),durableStreams:P.durableStreams,globalTables:r.tables.some(R=>R.shardMode==="global"),queues:l.length>0,relationGraph:Bo(r),secrets:P.secrets,services:p.length>0,topics:u.length>0,vectorStore:r.vectorIndexes.length>0,workerLoaders:F.usesSandboxLoader,workflowRollback:P.workflowRollback,workflowSchedules:c.some(R=>R.schedules!==void 0)}),D=H.usage,te=vr(D),se=H.signals.vectorStore!==!1,ae=H.signals.services===!1?[]:p,ne=Ir(n),xe=ne??new Set,B=xe.has("lunorash");mo(r,ne,{hasVectors:se,scheduler:D.scheduler||z.length>0,storage:D.storage||S.rules.length>0||Object.keys(Zs(r)).length>0,usage:D});const M=T(h(t,"flags.ts")),O=T(h(t,"notify.ts"));return{agents:f,capabilities:te,containers:m,crons:z,dataModelContent:qr(r),declaredDependencies:ne,dependencies:xe,entryCronTriggers:V,env:a,featureUsage:D,hasFlags:M,hasNotify:O,identity:o,platformGate:{...H,diagnostics:[...Br(n,e.target),...H.diagnostics]},queues:l,serverContent:jr({agents:f,capabilities:te,containers:m,env:a,hasVectors:se,hasFlags:M,hasNotify:O,identity:o,queues:l,schema:r,services:ae,storageRuleBuckets:S.rules.map(R=>R.bucket),topics:u,useUmbrella:B,workflows:c}),services:ae,storageRulesMetadata:S,topics:u,usesSandbox:F.usesSandboxBrowser||F.usesSandboxContainer||F.usesSandboxFs,useUmbrella:B,workflows:c}},dn=new Set(["delete","get","head","options","patch","post","put"]),jo=new Set(["handler","stream"]),Vo=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,as=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),qo=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!dn.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Wo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||dn.has(n.getName()))break;s=n.getExpression()}return qo(s)},Ho=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(as.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&as.has(s.getText()))return!0}return!1},Go=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!jo.has(n.getName()))return;const r=Wo(s);if(!r||!Vo.test(r.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&Ho(o);return{exportName:K(e)??e.getName(),file:t,method:r.method,path:r.path,usesGuard:a}},Yo=(e,t)=>{const s=[];for(const n of j(e)){const r=Go(n,t);r&&s.push(r)}return s},Qo=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Yo(r,I(t,n)))}return s},Xo=e=>{const t=e.getText(),s=n=>{const r=n.getNameNode();return i.isIdentifier(r)&&r.getText()===t};for(const n of e.getAncestors())if(!(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)&&!i.isFunctionDeclaration(n)))for(const r of n.getParameters()){const o=r.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Jo=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isObjectBindingPattern(s))return;const n=s.getParent();if(i.isBindingElement(n)){t=n;continue}return i.isParameterDeclaration(n)?Ee(t):void 0}},Zo=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=i.isFunctionLikeDeclaration(o)||i.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(i.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&ts(a)}))return!1;const n=k(e),r=i.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return r!==void 0&&(i.isParameterDeclaration(n)||i.isBindingElement(n))&&ts(r)},cs=(e,t)=>{const s=e.getParent();if(i.isPropertyAccessExpression(s)&&s.getNameNode()===e||i.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Xo(e);return n!==void 0&&Jo(n)===t?!0:t==="args"&&Zo(e)},un=(e,t)=>i.isIdentifier(e)?cs(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>cs(s,t)),ea=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},ls=e=>{const t=i.isIdentifier(e)?k(e):void 0;return i.isVariableDeclaration(t)&&i.isIdentifier(t.getNameNode())&&!At(t)?t.getInitializer():void 0},gt=e=>un(e,"args"),Q=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let r,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(r=c,o=l)}return r},U=e=>{if(gt(e))return!0;const t=Q(e);return t!==void 0&>(t)},ta=e=>{if(i.isCallExpression(e)||i.isNewExpression(e))return!1;const t=Q(e);return t===void 0||!(i.isCallExpression(t)||i.isNewExpression(t))},ee=e=>{if(st(e))return!0;const t=ls(e);if(t!==void 0&&st(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(r=>{const o=ls(r);return o!==void 0&&st(o)})},Te=(e,t)=>un(e,t),sa=(e,t)=>{if(Te(e,t))return!0;const s=Q(e);if(s!==void 0&&Te(s,t))return!0;const n=ea(e);if(n!==void 0){const r=Q(n);return r!==void 0&&Te(r,t)}return!1},na=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:$(e.getExpression(),["ai"]),ra=(e,t)=>{if(!na(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!U(s)||ee(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},ia=(e,t)=>C(e,t,ra),oa=new Set(["generateText","streamText"]),aa=new Set(["messages","prompt","system"]),ca=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],la=(e,t)=>ca.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),da=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Wr(t.getExpression()),t.getExpression().getText()].find(r=>r!==void 0&&la(r,s));return n===void 0?void 0:`${n}.${s}`},ua=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=da(t);if(s!==void 0)return s}},fa=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],r=n?.getNameNode();if(r===void 0||!i.isObjectBindingPattern(r))return t;for(const o of r.getElements()){const a=Ee(o),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},ga=e=>{if(gt(e))return!0;const t=fa(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},pa=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!aa.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&ga(s))return!0}return!1},ma=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=A(n.getExpression());if(r===void 0||!oa.has(r))continue;const[o]=n.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(A(c.getExpression())==="tool"&&(a=ua(c),a!==void 0))break;a!==void 0&&s.push({scope:v(n),file:t,line:n.getStartLineNumber(),method:r,sideEffect:a,userInputDerived:pa(o)})}return s},ha=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ma(r,I(t,n)))}return s},va=e=>$(e,["fetch"]),Ea=(e,t)=>{if(!va(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!U(s)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},xa=(e,t)=>C(e,t,Ea),wt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=qe(s.getExpression());return n===void 0||wt(n,t)})}finally{t.delete(e)}},Sa=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=L(t,"args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),r=n===void 0?void 0:qe(n);return r===void 0?{objects:[],opaque:!0}:{objects:[r],opaque:wt(r)}},ya=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const r=n.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&i.isExpression(o)?qe(o):void 0;a===void 0?s=!0:(t.push(a),s||=wt(a))}n=r.getExpression()}return{objects:t,opaque:s}},It=(e,t)=>t?ya(t):Sa(e),fn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=qe(s.getExpression());return n===void 0?[]:fn(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Aa=e=>e.flatMap(t=>fn(t,new Set)),ba=new Set(["check","length","max"]),pt=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Na=e=>[e,...e.getDescendants()].filter(t=>pt(t)!==void 0),Pa=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(ba.has(s.getName()))return!0;t=n}},wa=e=>{const t=[],s=[];for(const n of e)for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=Na(o),c=y(r);a.some(l=>pt(l)==="any")?t.push(c):a.some(l=>pt(l)==="string"&&!Pa(l))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Ia=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=W(s);if(n?.visibility!=="public")return;const{objects:r}=It(s,n.receiver),{anyArgs:o,unboundedStringArgs:a}=wa(r);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:K(e)??e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Ca=(e,t)=>{const s=[];for(const n of j(e)){const r=Ia(n,t);r&&s.push(r)}return s},Ta=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ca(r,I(t,n)))}return s},it=e=>e?.getKind()===d.TrueKeyword,Oa=e=>e?.getKind()===d.FalseKeyword,Ra=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,ka=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Fa=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&A(t.getExpression())==="scim"),Da=e=>e!==void 0&&i.isCallExpression(e)&&ka.has(A(e.getExpression())??""),La=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Ma=e=>{const t=w(e,"advanced"),s=w(e,"emailAndPassword"),n=w(e,"session");return{analyzable:!0,disableCsrfCheck:it(w(t,"disableCSRFCheck")),emailPasswordEnabled:it(w(s,"enabled")),requireEmailVerification:it(w(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Fa(w(e,"plugins"))&&Da(w(e,"database")),secureCookiesDisabled:Oa(w(t,"useSecureCookies")),sessionFreshAgeZero:Ra(w(n,"freshAge")),trustedOriginsWildcard:La(w(e,"trustedOrigins"))}},_a=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Ka=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),r=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?Ma(s):_a();return{scope:v(e),file:t,line:e.getStartLineNumber(),...r}},za=(e,t)=>Cr(e,t,Ka),Ba=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return en(e.getExpression(),t.matchReceiver)?s:void 0},$a=(e,t,s)=>{const n=Ba(e.getExpression(),s);if(n===void 0)return;const r=e.getArguments()[s.argIndex];if(!(!r||!U(r)||ee(r))&&!(s.requireUnmodifiedReach===!0&&!ta(r)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:n}},We=(e,t,s)=>C(e,t,(n,r)=>$a(n,r,s)),Ua=new Set(["content","pdf","scrape","screenshot"]),ja=(e,t)=>We(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ua}),gn=e=>{const t=Gs(e);return t===void 0?void 0:`${Be(t.slice(0,-1).join("/"))}:${String(t.at(-1))}`},pn=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Va=e=>{if(!i.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||i.isIdentifier(t)&&t.getText()==="scheduler"},qa=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Wa=(e,t)=>{const s=gn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:"the function reference is not a static api.* / internal.* chain"}:void 0},Ha=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),[n,r]=e.getArguments();if(Hs.has(s))return Wa(s,n);if((s==="runAfter"||s==="runAt")&&Va(t)){const c=gn(r);return c===void 0?{kind:"schedule",reason:"the scheduled function is not a static api.* / internal.* chain"}:{kind:"schedule",target:c}}const o=qa.get(s),a=o===void 0?void 0:pn(t,o.surface);return o===void 0||a===void 0?void 0:{kind:o.kind,target:a}},ds=(e,t,s)=>s===void 0?void 0:{...s,file:t,line:e.getStartLineNumber(),scope:v(e)},Ga=(e,t)=>[...C(e,t,(s,n)=>ds(s,n,Ha(s))),...ut(e,t,d.PropertyAccessExpression,(s,n)=>{const r=pn(s,"services");return ds(s,n,r===void 0?void 0:{kind:"invoke",target:r})})],Ya=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Qa=new Set(["RateLimiter"]),Xa=new Set(["extend"]),us="lunora",Ja=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],mn=e=>{const t=[],s=[];let n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=y(r);t.push(o),r.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,presentKeys:t,trueKeys:s}},mt=e=>e&&i.isObjectLiteralExpression(e)?mn(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Za=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Ws(t.getBody());return s?mn(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},ec=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=A(n.getExpression());r!==void 0&&(Ya.has(r)?s.push({callee:r,file:t,line:n.getStartLineNumber(),...mt(n.getArguments()[0])}):Xa.has(r)&&s.push({callee:r,file:t,line:n.getStartLineNumber(),...Za(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const r=A(n.getExpression());r===void 0||!Qa.has(r)||s.push({callee:r,file:t,line:n.getStartLineNumber(),...mt(n.getArguments()[0])})}return s},tc=(e,t)=>{for(const s of Ja){const n=h(t,s);if(!T(n))continue;const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of r.getDescendantsOfKind(d.CallExpression))A(a.getExpression())===us&&o.push({callee:us,file:s,line:a.getStartLineNumber(),...mt(a.getArguments()[0])});return o}return[]},sc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Ue(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ec(o,n))}return s.push(...tc(e,de(t))),s},fs="ctx.containers.",nc=e=>{if(!e.startsWith(fs))return!1;const t=e.slice(fs.length);return t.length>0&&!t.includes(".")},rc=(e,t)=>We(e,t,{argIndex:0,matchReceiver:nc,methods:new Set(["get"])}),ic=new Set(["allow","deny","setAllowed"]),oc=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=L(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},ac=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!oc(e)))return{detail:"enableInternet: true",scope:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},cc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!ic.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},lc=(e,t)=>ac(e,t)??cc(e,t),dc=(e,t)=>C(e,t,lc),uc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),fc=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return uc.has(s)?s:void 0},gc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const r=y(n);t.push(r);const o=n.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(r);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},pc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Ue(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=fc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&i.isObjectLiteralExpression(l)?gc(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},mc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),hc=new Set(["dbRateLimit","rateLimit"]),vc=e=>{const t=Qs(e);if(!t)return!1;const s=L(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},Ec=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const n=mc.get(s);if(n!==void 0)return{callee:s,scope:v(e),failOpen:vc(e.getArguments()[n]),file:t,limitName:hc.has(s)?Ys(e):"",line:e.getStartLineNumber()}},xc=(e,t)=>C(e,t,Ec),Sc=new Set(["boolean","number","object","string"]),yc=e=>{const t=e.getName();if(!Sc.has(t))return;const s=e.getExpression();return $(s,["flags"])||$(s,["flags","details"])?t:void 0},Ac=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=yc(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const r=n.getLiteralValue();return r.length>0?{key:r,type:s}:void 0},bc=(e,t)=>{const s=new Map;for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=Ac(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,r])=>({key:n,type:r})).toSorted((n,r)=>n.key.localeCompare(r.key))},Nc=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=W(t);if(s?.kind!=="query")return;const n=Tr(t,s.receiver);return n?{exportName:K(e)??e.getName(),handler:n}:void 0},gs=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Pc=e=>{const t=gs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=gs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},wc=(e,t)=>{const s=[];for(const n of Ve(e.handler,"flags"))s.push({callee:Pc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Ic=(e,t)=>{const s=[];for(const n of j(e)){const r=Nc(n);r&&s.push(...wc(r,t))}return s},Cc=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ic(r,I(t,n)))}return s},Tc=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:$(e.getExpression(),["flags"]),Oc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Rc=(e,t)=>{if(!Tc(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const r=s.getLiteralValue(),o=Oc(n);if(!(r.length===0||o===void 0))return{defaultValue:o,scope:v(e),file:t,key:r,line:e.getStartLineNumber()}},kc=(e,t)=>C(e,t,Rc),Fc=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const r=n.getTypeAtLocation(e),o=r.getText(e);if(!o||o==="any"||o==="never"||Jr(o))return;const a=e.getSourceFile().getFilePath();if(Zr(r,e,a)){const c=ei(r,e,a,0,new Set);return c===void 0&&ti(o),c}return o},Dc=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Lc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Mc=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of r.getDescendantsOfKind(d.CallExpression))Dc(a)&&s.push({file:o,indexName:Lc(a),line:a.getStartLineNumber()})}return s},me=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,hn=e=>{const t=e.getArguments()[0],s=me(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=L(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?me(n.getInitializer()):void 0},_c=new Set(["delete","get","head","options","patch","post","put"]),Kc=new Set(["handler","stream"]),zc=new Set(["runAction","runMutation"]),Bc=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),he=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,vn=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(Ee(s)===t){const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0}}},ps=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:vn(s,"ctx")},ms=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:vn(s,"request")},hs=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const r of n){const o=r.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(zc.has(a)&&he(c,t))return a;if(Bc.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&he(c.getExpression(),t))return`db.${a}`}},vs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&he(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const r=n.getNameNode();if(!(!i.isObjectBindingPattern(r)||!he(n.getInitializer(),t))){for(const o of r.getElements())if(Ee(o)==="auth")return!0}}return!1},$c=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Uc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&he(n.getExpression(),t)},jc=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],En=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:jc(s)},Vc=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const r=n.getParent();if(!i.isCallExpression(r))return[];const o=r.getExpression();if(!i.isPropertyAccessExpression(o))return[];const a=o.getExpression();return i.isIdentifier(a)?En(t,a.getText()):[]}return[]},qc=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=En(s,t.getText());return n.length>0?n:Vc(t,s)},Es=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(r=>Uc(r,t)&&qc(r).some(o=>$c.test(o)))},Wc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Kc.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const r=n.getName();if(_c.has(r)){const o=n.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?r.toUpperCase():void 0}s=n.getExpression()}},Hc=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=me(e.getArguments()[0]),l=c&&ps(c,!0);if(!c||l===void 0||Es(c,ms(c,!0)))return;const u=hs(c,l);return u===void 0?void 0:{scope:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:vs(c,l),sideEffect:u}}const n=Wc(e);if(n===void 0)return;const r=me(e.getArguments()[0]),o=r&&ps(r,!1);if(!r||o===void 0||Es(r,ms(r,!1)))return;const a=hs(r,o);return a===void 0?void 0:{scope:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:vs(r,o),sideEffect:a}},Gc=(e,t)=>C(e,t,Hc),Yc=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Qc=new Set(["append","set"]),xn=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",xs=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>Yc.has(A(n.getExpression())??"")&&Te(n,t)),Xc=(e,t)=>{if(xs(e,t))return!0;const s=Q(e);return s!==void 0&&xs(s,t)},ht=(e,t)=>sa(e,t)&&!Xc(e,t),Jc=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&i.isNewExpression(t)&&A(t.getExpression())==="Headers"},De=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Ct=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const r=n.getInitializer();r!==void 0&&ht(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:xn(n.getNameNode()),line:r.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const r=n.getNameNode();ht(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:r.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const r=De(n.getExpression());r!==void 0&&Ct(r,t,s)}},Sn=(e,t)=>{const s=De(e);if(s===void 0)return;const n=L(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const r=De(n.getInitializer());r!==void 0&&Ct(r,"response-init",t)},Zc=(e,t)=>{const s=A(e.getExpression());if(s==="Response")Sn(e.getArguments()[1],t);else if(s==="Headers"){const n=De(e.getArguments()[0]);n!==void 0&&Ct(n,"headers-ctor",t)}},el=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),r=s.getExpression();if(n==="json"&&i.isIdentifier(r)&&r.getText()==="Response"){Sn(e.getArguments()[1],t);return}if(Qc.has(n)&&Jc(r)){const o=e.getArguments()[1];o!==void 0&&ht(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:xn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},tl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Zc(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))el(s,t)},sl=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=me(e.getArguments()[0]);if(n===void 0)return[];const r=n.getParameters()[1];if(r===void 0)return[];const o=r.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return tl(n,{scope:v(e),relativePath:t,requestName:o.getText(),rows:a}),a},nl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...sl(n,t));return s},rl=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...nl(r,I(t,n)))}return s},il=new Set(["auth","context.auth"]),ol="userId",al=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(y(s))}return t},cl=(e,t)=>{const s=h(t,cn);if(!T(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){if(A(r.getExpression())!=="defineIdentity")continue;const[o]=r.getArguments();return o&&i.isObjectLiteralExpression(o)?al(o):void 0}},Ss=e=>{if(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return il.has(t.getText())||$(t,["auth"])?e:void 0},ll=e=>{if(i.isPropertyAccessExpression(e)&&Ss(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Ss(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},ys=(e,t,s)=>{const n=ll(e);return n===void 0?void 0:{declared:n===ol||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:v(e)}},dl=(e,t)=>{const s=cl(e,t);return s===void 0?[]:[...ut(e,t,d.PropertyAccessExpression,(n,r)=>ys(n,r,s)),...ut(e,t,d.ElementAccessExpression,(n,r)=>ys(n,r,s))]},ul=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=w(s,"key");if(!(!n||!U(n)||ee(n)))return{scope:v(e),file:t,line:e.getStartLineNumber()}},fl=(e,t)=>C(e,t,ul),gl=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=cr(t.getNameNode());return s===void 0||s==="namespace"}),pl=(e,t)=>{for(const{filePath:s}of Ue(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){const o=r.getExpression(),[a]=r.getArguments();if(!(!i.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!i.isObjectLiteralExpression(a)||gl(a)))return r}}},ml="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",hl=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ve(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 (${ml}). 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})},vl=new Set(["delete","get","getRaw","getWithMetadata","put"]),El=(e,t,s=[])=>{const n=We(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:vl});return bt(n,s)},xl=new Set(["queue","send"]),As=new Set(["bcc","cc","to"]),Sl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!xl.has(t))return;const s=e.getExpression();return $(s,["mail"])||$(s,["email"])?t:void 0},yl=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return As.has(y(t))&&U(n)&&!ee(n)}if(!i.isPropertyAssignment(t)||!As.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&U(s)&&!ee(s)}):!1,Al=(e,t)=>{const s=Sl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!yl(n)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},bl=(e,t)=>C(e,t,Al),Nl=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,Pl=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?Nl(e):!0,yn=(e,t=!1)=>{for(const s of e.getProperties()){if(Pl(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||yn(n,!0))return!0}return!1},wl=(e,t)=>{for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:r}of on(n))for(const o of Pt(r)){const a=o.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||yn(a)))return!0}}return!1},Il=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const r=Fe(n);if(r===void 0||!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!i.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Fe(a);c!==void 0&&s.push({column:c,strategy:rn(a),table:r})}}return s},Cl=(e,t)=>{const s=new Map;for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of on(r))for(const a of Pt(o))for(const c of Il(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Tl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){const a=Fe(o);if(a===void 0||!i.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Fe(l);if(u===void 0)continue;const p=rn(l);p!=="custom"&&r.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:p,table:a})}}return r},Ol=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?W(s):void 0;return n?.receiver?Pt(n.receiver).flatMap(r=>Tl(r,K(e)??e.getName(),t)):[]},Rl=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(r))s.push(...Ol(a,o))}return s},kl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Fl=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=L(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},Dl=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ui(s.getExpression())?s:void 0},Ll=e=>{const t=Dl(e),s=t===void 0?void 0:Fl(t);if(s===void 0)return[];const n=e.getNameNode(),r=i.isIdentifier(n)?K(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>kl(o)).map(o=>({exportName:r,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Ml=e=>e.getVariableDeclarations().flatMap(t=>Ll(t)),_l=(e,t)=>{const s=h(t,di);if(!T(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Ml(n)},Kl=new Set(["delete","get","patch"]),zl=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Bl=new Set(["auth","identity","session","user"]),$l=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Ul=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},jl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},Vl=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),ql=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Wl=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Vl(s.getExpression(),t)&&ql(s.getThenStatement())),Hl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const r=n.getName();if(!Kl.has(r))continue;const o=n.getExpression();if(!(_(o)||i.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return r}},Gl=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>tn(Nt(s))!==void 0)),Yl=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>$l.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Ql=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(zl.has(t.getText()))return!0;return[...Bl].some(t=>Ve(e,t).length>0)?!0:Gl(e)||Yl(e)},Xl=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=W(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const r=hn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&Xs(n.receiver,"use","rls"),a=Ql(r),c=new Set,l=[];for(const u of r.getDescendantsOfKind(d.CallExpression)){const p=Ul(u);if(p===void 0)continue;const f=jl(u);if(f===void 0||c.has(f)||!Wl(r,f))continue;const m=Hl(r,f);m!==void 0&&(c.add(f),l.push({exportName:K(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:p,usesRls:o,visibility:n.visibility}))}return l},Jl=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(r))s.push(...Xl(a,o))}return s},An=(e,t)=>{const s=i.isIdentifier(e)&&t!==void 0?k(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?i.isIdentifier(t.getNameNode()):i.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Zl=e=>{const t=N(e),s=t.getParent();return(i.isPropertyAccessExpression(s)||i.isElementAccessExpression(s))&&s.getExpression()===t&&!je(s)},ed=e=>{const t=N(e).getParent();return i.isVariableDeclaration(t)&&i.isObjectBindingPattern(t.getNameNode())},td=e=>{const s=N(e).getParent();if(i.isSpreadAssignment(s)||i.isSpreadElement(s)){const n=s.getParent();return(i.isObjectLiteralExpression(n)||i.isArrayLiteralExpression(n))&&!je(n)}return i.isTemplateSpan(s)&&!i.isTaggedTemplateExpression(s.getParent().getParent())},Le=e=>{const t=k(e);return t===void 0||Ar(t.getSourceFile())},vt=(e,t)=>{const s=N(e),n=s.getParent();if(!i.isCallExpression(n))return!1;const r=n.getArguments().indexOf(s),o=E(n.getExpression());if(r===-1||o===void 0)return!1;if(i.isIdentifier(o))return o.getText()==="structuredClone"&&Le(o);if(An(Nt(o),t))return!(i.isPropertyAccessExpression(o)&&sn.has(o.getName()))||i.isExpressionStatement(N(i.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!i.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!i.isIdentifier(a)||!Le(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&r>0;default:return!1}},Oe={kind:"opaque"},sd={kind:"unreached"},nd=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>i.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>i.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&i.isFunctionDeclaration(n)?n:void 0},Et=e=>{const t=E(e);if(i.isArrowFunction(t)||i.isFunctionExpression(t))return t;const s=i.isIdentifier(t)?k(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(i.isFunctionDeclaration(s)){const r=nd(s);return r===void 0||At(r)?void 0:r}const n=Z(s)?E(s.getInitializer()):void 0;return i.isArrowFunction(n)||i.isFunctionExpression(n)?n:void 0},bn=(e,t,s)=>{const n=t.getArguments(),r=n.indexOf(s),o=r===-1||n.slice(0,r+1).some(l=>i.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[r];return o?Oe:c===void 0?a.some(l=>l.isRestParameter())?Oe:sd:c.isRestParameter()?Oe:{kind:"parameter",parameter:c}},rd=e=>{const t=N(e),s=t.getParent();if(!i.isCallExpression(s)||s.getExpression()===t)return;const n=Et(s.getExpression());return n===void 0?Oe:bn(n,s,t)},id=new Set(["__defineGetter__","__defineSetter__","__proto__"]),od=e=>i.isForInStatement(e)?e.getExpression():i.isConditionalExpression(e)?e.getCondition():i.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Nn=e=>{const t=N(e),s=t.getParent();if(i.isIfStatement(s)||i.isWhileStatement(s)||i.isDoStatement(s)||i.isSwitchStatement(s)||i.isCaseClause(s)||i.isTypeOfExpression(s)||i.isVoidExpression(s)||i.isComputedPropertyName(s))return!0;if(i.isTemplateSpan(s))return!i.isTaggedTemplateExpression(s.getParent().getParent());const n=od(s);if(n!==void 0)return pe(n,t);if(i.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!i.isBinaryExpression(s))return!1;const r=s.getOperatorToken().getKind(),o=r>=d.FirstAssignment&&r<=d.LastAssignment,a=r===d.QuestionQuestionToken||r===d.BarBarToken||r===d.AmpersandAmpersandToken;return!o&&!a},ad=4,Pn=(e,t,s=0)=>{if(yr(e))return!0;if(Zl(e)){const r=N(e).getParent(),o=i.isElementAccessExpression(r)?r.getArgumentExpression():void 0,a=i.isStringLiteral(o)?o.getLiteralValue():void 0,c=i.isPropertyAccessExpression(r)?r.getName():a;return c===void 0||!id.has(c)}if(ed(e)||td(e)||Nn(e)||vt(e,t))return!0;const n=rd(e);return n?.kind==="unreached"||n?.kind==="parameter"&&cd(n.parameter,s+1)},bs=new WeakMap,cd=(e,t=0)=>{const s=e.getNameNode();if(!i.isIdentifier(s))return!0;const n=bs.get(e.compilerNode);if(n!==void 0)return n;if(t>ad)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||k(a)?.compilerNode!==e.compilerNode||Pn(a,void 0,t));return(o||t===0)&&bs.set(e.compilerNode,o),o},Ns=new WeakMap,ld=(e,t)=>{const s=i.isFunctionExpression(e)?e.getNameNode():void 0;if(!i.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(r=>{if(r===s||!n.has(r.getText()))return!1;const o=k(r)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},dd=(e,t,s)=>{const{context:n,impl:r}=e,o=Ns.get(r.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=i.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(f=>{const m=f.getNameNode();return i.isIdentifier(m)?[m]:[]}),l=new Map(c.map(f=>[f.getText(),f.getParentOrThrow().compilerNode])),u=f=>i.isIdentifier(a)?Pn(f,n):!je(f),p=!ld(r,s)&&c.every(f=>(f.getSymbol()?.getDeclarations().length??0)===1)&&r.getDescendantsOfKind(d.Identifier).every(f=>{const m=f.getText();if(m==="arguments")return!1;const S=l.get(m);return S===void 0||c.includes(f)||k(f)?.compilerNode!==S?!0:u(f)});return Ns.set(r.compilerNode,p),p},Ps=new WeakMap,ud=e=>{let t=Ps.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=fi(s);return n===void 0?[]:[[n.compilerNode,s]]})),Ps.set(e.compilerNode,t)),t},fd=e=>{const t=ud(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[r,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:r,impl:s,mutatorName:K(n)??n.getName()};return a!==void 0&&dd(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},gd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),pd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),xt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),wn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>i.isIdentifier(t.getNameNode())),md=e=>{const t=N(e),s=t.getParent();if(i.isVariableDeclaration(s))return pe(s.getInitializer(),t)?s:void 0;const n=i.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return i.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},hd=e=>{const t=md(e);return t===void 0?void 0:i.isIdentifier(t.getNameNode())?i.isForOfStatement(t.getParent().getParent())||Z(t)?[t]:void 0:wn(t)},ue=e=>e.isUnion()?e.getUnionTypes().every(t=>ue(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>ue(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Me=(e,t,s)=>{const n=i.isCallExpression(e)?E(e.getExpression()):void 0;return i.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Re=e=>{const t=E(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=t.getBody();return i.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(r=>i.isFunctionLikeDeclaration(r))===t).map(n=>n.getExpression()):[s]},vd=e=>{const t=i.isCallExpression(e)?E(e.getExpression()):void 0,s=i.isPropertyAccessExpression(t)?t.getExpression():void 0;return i.isPropertyAccessExpression(t)&&i.isIdentifier(s)&&pd.get(s.getText())?.has(t.getName())===!0&&Le(s)},Ed=e=>{const t=ft(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=N(t),n=s.getParent();return i.isCallExpression(n)&&n.getArguments().includes(s)&&Me(n,nn)?n:void 0},xd=(e,t)=>{if(!(i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=N(e),n=s.getParent();return!i.isCallExpression(n)||n.getExpression()!==s?e:Me(n,gd,t)?n:void 0},Sd=(e,t)=>{if(i.isAwaitExpression(e))return e;if(i.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=i.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},yd=(e,t)=>{if(i.isArrayLiteralExpression(e))return e;const n=i.isSpreadElement(e)||i.isSpreadAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isPropertyAssignment(e)&&pe(e.getInitializer(),t)?e.getParent():void 0;return i.isArrayLiteralExpression(n)||i.isObjectLiteralExpression(n)?n:void 0},ws=e=>{const t=N(e),s=t.getParent();if(s===void 0)return;const n=i.isCallExpression(s)&&s.getArguments().includes(t)&&vd(s);return xd(s,t)??Sd(s,t)??yd(s,t)??(n?s:Ed(t))},Ad=5e4,In=()=>({inProgress:new Set,verdicts:new Map});class bd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Ad&&this.cut()}memoized(t,s,n){const r=n.verdicts.get(t);if(r!==void 0)return r;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Nd=8,Pd=8;class wd{budget;scope;taint;verdicts=In();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!ue(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],r=new Set,o=(c,l)=>{r.has(c.compilerNode)||(r.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of r)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,r){const o=t.getNameNode();if(!i.isIdentifier(o)){for(const l of i.isParameterDeclaration(t)?wn(t):[])r(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Nd?this.budget.cut():(r(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(N(l),!0,a,0))&&(t===n||!ue(t.getType()))}valueCompromises(t,s,n,r){let o=t;for(let m=ws(o);m!==void 0;m=ws(o)){if(i.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=N(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&ue(o.getType());if(je(o))return!c&&(!i.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=hd(o);if(u!==void 0)return u.some(m=>n(m,!0));const p=i.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(i.isCallExpression(p)&&p.getExpression()===a)return this.methodCallCompromises(p,n);const f=this.nestedReturningFunctionOf(o);return f!==void 0?this.resultCompromises(f,n,r)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const r=N(t).getParent();if(n>=Pd)return this.budget.cut();if(i.isCallExpression(r))return r.getExpression()===N(t)?this.valueCompromises(r,!1,s,n+1):!Me(r,xt);const o=i.isFunctionDeclaration(t)?t:r,a=i.isFunctionDeclaration(o)||Z(o)?o.getNameNode():void 0;return o===void 0||!i.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=N(c),u=l.getParent();return!i.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(r=>Re(r)===void 0).some(r=>this.taint.isTaintedValue(r,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Me(t,xt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const r=Et(n);return r!==void 0&&this.taint.isInImpl(r)?r.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(i.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const r=i.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&i.isCallExpression(r))return!vt(n,this.scope.context)&&this.isOpaqueCallTainted(r.getExpression(),r.getArguments(),n);if(i.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(i.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return i.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(vt(s,this.scope.context))return!1;const r=Et(t.getExpression()),o=r===void 0?void 0:bn(r,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&r!==void 0&&this.taint.isInImpl(r)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||i.isExpressionStatement(s)||i.isForStatement(s)||i.isElementAccessExpression(s)||Nn(t)||pe(ft(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const r=!i.isIdentifier(E(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||r)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=ft(t);return pe(s,this.scope.impl)?void 0:s}}const Id=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Cd=e=>{const t=E(e);if(!i.isIdentifier(t))return i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t);const s=k(t),n=i.isVariableDeclaration(s)?E(s.getInitializer()):void 0;return s===void 0||i.isFunctionDeclaration(s)||i.isParameterDeclaration(s)||i.isArrowFunction(n)||i.isFunctionExpression(n)},Td=new Set(["all","allSettled","any","race"]),Is=e=>i.isParameterDeclaration(e)?e:i.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,ot=8;class Od{budget=new bd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=In();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new wd(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,ot)?!1:(i.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(r=>br(r)&&this.isIdentifierTainted(r))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const r of this.referencesByName.get(s)??[]){const o=k(r)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],r])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(r=>r.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(f=>f.getInitializer())].some(f=>f!==void 0&&this.isTaintedValue(f,!1)))return!0;const n=t.getParentOrThrow(),r=i.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(f=>f.compilerNode===t.compilerNode):-1,o=N(n),a=o.getParent();if(r===-1)return!0;if(i.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,r,t.isRestParameter());const f=E(a.getExpression());if(!i.isPropertyAccessExpression(f)||!xt.has(f.getName()))return!0;const m=a.getArguments().filter(S=>S!==o);return this.isTaintedValue(f.getExpression(),!0)||m.some(S=>this.isTaintedValue(S,!1))}const c=i.isVariableDeclaration(a)&&Z(a)?a:void 0,l=i.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!i.isIdentifier(u))return!0;const p=this.referencesTo(l,u.getText());return p.length===0||p.some(f=>{const m=N(f),S=m.getParent();return!i.isCallExpression(S)||S.getExpression()!==m||this.isCallSiteTainted(S,r,t.isRestParameter())})}isCallSiteTainted(t,s,n){const r=t.getArguments(),o=r.findIndex(c=>i.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return r.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=E(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getExpression():void 0,a=i.isPropertyAccessExpression(n)&&i.isIdentifier(r)&&r.getText()==="Promise"&&Le(r)&&Td.has(n.getName())?E(t.getArguments()[0]):void 0;if(i.isArrayLiteralExpression(a)){const p=a.getElements();return p.length>0&&p.every(f=>!i.isSpreadElement(f)&&this.isRootedInContext(f,s))}const c=i.isCallExpression(a)?E(a.getExpression()):void 0,l=i.isCallExpression(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="map"?E(a.getArguments()[0]):void 0,u=l===void 0?void 0:Re(l);return u!==void 0&&u.length>0&&u.every(p=>p!==void 0&&this.isRootedInContext(p,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=k(t),r=Is(n);if(r!==void 0)return this.isSource(r);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(i.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(i.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=i.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return i.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=E(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getName():void 0;return r!==void 0&&sn.has(r)?!1:r!==void 0&&nn.has(r)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Re(a)!==void 0)&&(r===void 0||!Id.has(r))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(r,o=[])=>{const a=Nt(r),c=i.isIdentifier(a)?Is(k(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(r,s)||!this.isTaintedValue(r,!1)};return t.getArguments().every(r=>{const o=Re(r);if(o===void 0)return!Cd(r)&&n(r);const a=E(r),c=i.isArrowFunction(a)||i.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Or(t,u=>this.callChainVerdict(u,s)),r=n.root;if(n.verdict!==void 0)return n.verdict;if(An(r,this.scope.context))return!0;const o=i.isIdentifier(r)?k(r):void 0,a=i.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=Z(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=i.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(i.isBindingElement(l)||i.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(i.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(i.isForOfStatement(s)||i.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),r=At(t);if(n===void 0||r)return!0;if(this.isRootedInContext(n,ot))return!1;if(this.variableDepth>=ot)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Cs=new WeakMap,Rd=e=>{const t=Cs.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Od(e);return Cs.set(e.impl.compilerNode,s),s},kd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Fd=new Set(["insert","insertManyUnsafe","patch","replace"]),Dd=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();return Fd.has(t)&&Hr(e.getExpression())?t:void 0},Ld=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},Md=(e,t)=>{const s=Rr(e);return s?.member===t?E(s.object):void 0},Ts=(e,t)=>i.isIdentifier(e)&&k(e)?.compilerNode===t.compilerNode,Cn=(e,t,s,n=1)=>{const r=Md(e,s);if(r!==void 0)return Ts(r,t);const o=i.isIdentifier(e)?k(e):void 0;if(i.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&Ee(o)===s&&i.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||Z(l)&&Ts(E(l.getInitializer()),t))}const a=Z(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Cn(a,t,s,n-1)},St=e=>{const t=E(e)??e;return i.isConditionalExpression(t)?[...St(t.getWhenTrue()),...St(t.getWhenFalse())]:[t]},_d=(e,t,s)=>{const n=[],r=s===void 0?void 0:Rd(s);for(const o of e.getProperties()){let a,c;if(i.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!kd.has(a))continue;if(St(c).some(u=>r===void 0?U(u)&&!Gr(u):r.isTaintedValue(u,!0))){const u=t.ownerField===a&&s?.pristine===!0&&Cn(c,s.parameter,a);n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...u&&{ownerScoped:!0}})}}return n},Kd=(e,t,s)=>{const n=Dd(e.getExpression()),r=n===void 0?void 0:e.getArguments()[1];if(n===void 0||r===void 0)return[];const o=Ld(r,n);if(o.length===0)return[];const a=v(e),c=fd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>_d(u,l,c))},zd=(e,t,s=[],n=[])=>{const r=new Map(n.map(a=>[`${a.filePath}:${a.exportName}`,a.owner])),o=C(e,t,(a,c)=>Kd(a,c,l=>r.get(`${c}:${l}`)));return bt(o,s)},Bd=["providerSubscriptionId","state"],$d=["providerEventId","processedAt"],Os=(e,t)=>t.every(s=>s in e.shape),Ud=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&&Os(t,Bd)&&Os(s,$d)},jd=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Vd=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,qd=e=>{const t=L(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Vd(t.getInitializer()):void 0},Wd=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!jd.has(s))return;const[n]=e.getArguments(),r=n&&i.isObjectLiteralExpression(n)?qd(n):void 0;return{callee:s,scope:v(e),file:t,line:e.getStartLineNumber(),...r===void 0?{}:{toleranceSeconds:r}}},Hd=(e,t)=>C(e,t,Wd),Gd=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Yd=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Qd=(e,t)=>{const s=e.getArguments()[t];if(!s||!i.isObjectLiteralExpression(s))return;const n=L(s,"handler");if(n===void 0||!i.isPropertyAssignment(n))return;const r=n.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Tn=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},On=(e,t)=>e===t||e.startsWith(`${t}.`),Rn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Rs=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},kn=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Rs(s));return i.isIdentifier(e)&&Rs(e)&&t.push(e),t},Xd=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Jd=e=>{const t=Tn(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const r=n.getInitializer(),o=i.isVariableDeclarationList(r)?r.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Zd=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Jd(e),r=new Set,o=a=>Rn(a).some(c=>n.some(l=>On(c.getText(),l)))?!0:kn(a).some(c=>r.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Xd(a))r.add(l)}return{names:r,prefixes:n}},eu=(e,t)=>Rn(e).some(s=>t.prefixes.some(n=>On(s.getText(),n)))?!0:kn(e).some(s=>t.names.has(s.getText())),tu=e=>{const t=Gs(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},su=(e,t,s)=>{const n=Tn(e,0);if(n===void 0)return[];const r=Zd(e,t,n),o=new Set([n,...r.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!i.isPropertyAccessExpression(l)||!Hs.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!eu(u,r))continue;const p=tu(c.getArguments()[0]);p!==void 0&&a.push({dispatchKind:t,file:s,scope:v(c),line:c.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return a},nu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=Yd(n),o=r===void 0?void 0:Gd.get(r);if(o===void 0)continue;const a=Qd(n,o);a!==void 0&&s.push(...su(a,r==="defineWorkflow"?"workflow":"queue",t))}return s},ru=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...nu(r,I(t,n)))}return s},ks={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Fs=new Set(["account","credential","member","passkey","session","user"]),iu=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ou=e=>{const s=iu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Fs.has(s)||Fs.has(n)},au=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},cu=(e,t)=>{const{objects:s,opaque:n}=It(e,t);return Aa(s).some(r=>au(r))?!0:n?void 0:!1},lu=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!L(t,"captcha"),usesRateLimit:!!L(t,"rateLimit")}},du=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},ke={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},uu=e=>{const t=du(e),s=t?A(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=lu(t);return{...ke,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in ks?{...ke,[ks[s]]:!0}:ke},fu=e=>{const t={...ke};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const r=n.getName()==="use"?s.getArguments()[0]:void 0;if(r){const o=uu(r);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},gu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),pu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!gu.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const r=e.getArguments()[0];return!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?!1:ou(r.getLiteralText())},mu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Ds=new Set(["queues","scheduler","topics","workflows"]),hu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!mu.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Ds.has(s.getName())&&Yr(s.getExpression()))return!0;s=s.getExpression()}const n=tn(s);return n?.length===1&&Ds.has(n[0]??"")},vu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},Fn=new Set(["generateObject","generateText","streamObject","streamText"]),Eu=e=>{const t=A(e.getExpression());return t!==void 0&&Fn.has(t)},xu=e=>{const t=A(e.getExpression());if(t===void 0||!Fn.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!L(s,"maxOutputTokens")},Su=new Set(["log","span","trace"]),yu=new Set(["ai"]),Au=new Set(["email","mail"]),bu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),at=(e,t)=>[...t].some(s=>Ve(e,s).length>0),Nu=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),Pu=new Set(["every","filter","flatMap","forEach","map","some"]),wu=new Set(["all","allSettled","race"]),Iu=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Pu.has(n))return t;const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="Promise"&&wu.has(n))return t},Cu=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Nu.has(t.getKind())){const s=Iu(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Tu=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Ou=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ru=e=>{let t=!1,s=!0;for(const n of[...bu].flatMap(r=>Ve(e,r))){const r=Ou(n);r&&(t=!0,!Cu(r)&&!Tu(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},ku=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Ls="lunora-advisor-exempt",Fu=/^[\s*/]+/u,Du=/[\w-]/u,Lu=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
7
|
+
`);for(const n of s.split(`
|
|
8
|
+
`)){const r=n.replace(Fu,"");if(!r.startsWith(Ls))continue;const o=r.slice(Ls.length);if(Du.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:""}},Mu=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=L(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},_u=(e,t)=>{const s=Mu(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),r=s.getText(),o=n.getVariableDeclaration(r)?.getInitializer();return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:n.getFunction(r)},Ku=e=>{let t=!1,s=!1,n=!1,r=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(pu(l)&&(o=!0),hu(l)&&(t=!0),vu(l)&&(r=!0),Eu(l)&&(s=!0),xu(l)&&(n=!0),o&&t&&r&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ru(e);return{callsMail:at(e,Au),emitsEvent:at(e,Su),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||at(e,yu),throwsBareError:ku(e),unboundedAiGeneration:n,usesInsertManyUnsafe:r,writesUserTable:o}},zu=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=W(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const r=n.receiver?fu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=_u(e,s);return{...o?Ku(o):{},...Lu(e),...r,analyzableBody:o!==void 0,exportName:K(e)??e.getName(),file:t,hasEmailArg:cu(s,n.receiver),kind:n.kind,visibility:n.visibility}},Bu=(e,t)=>{const s=[];for(const n of j(e)){const r=zu(n,t);r&&s.push(r)}return s},$u=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Bu(r,I(t,n)))}return s},Uu=new Set(["dbRateLimit","rateLimit"]),ju=e=>i.isArrowFunction(e)?e.getBody():e,Vu=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},Dn=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Ln=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const r=n.getParent();return!(i.isPropertyAccessExpression(r)&&r.getNameNode()===n)})},qu=(e,t)=>U(e)||t!==void 0&&Ln(e,t).some(s=>Dn(s)),Wu=(e,t)=>t===void 0?ee(e):Ln(e,t).some(s=>!Dn(s)),Hu=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Uu.has(s))return;const n=w(Qs(e.getArguments()[2]),"key");if(!n)return;const r=ju(n),o=Vu(n);if(!(!qu(r,o)||Wu(r,o)))return{callee:s,scope:v(e),file:t,limitName:Ys(e),line:e.getStartLineNumber()}},Gu=(e,t)=>C(e,t,Hu),Yu=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Qu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Yu.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},Xu=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Ju=e=>{let t=E(e)??e;for(;i.isAwaitExpression(t);)t=E(t.getExpression())??t.getExpression();return t},Mn=(e,t=!1)=>{const s=Ju(e);if(i.isIdentifier(s)){if(t)return;const n=Q(s);return n===void 0?void 0:Mn(n,!0)}if(i.isCallExpression(s))return Qu(s)??Xu(s)},Zu=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const r=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=n.getExpression();r===e&&o!==void 0&&s.push(o)}return s},ef=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=W(s);if(n?.kind!=="query")return[];const r=hn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&_r(n.receiver,"output"),a=n.receiver!==void 0&&Xs(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Zu(r)){const p=Mn(u);p===void 0||c.has(p)||(c.add(p),l.push({exportName:K(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:p,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},tf=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(r))s.push(...ef(a,o))}return s},sf=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(y(s));return t},nf=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?W(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=an(o);if(a===void 0)continue;const c=sf(w(a.options,"with"));c.length!==0&&r.push({exportName:K(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return r},rf=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(r))s.push(...nf(a,o))}return s},_e=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=_e(e.getLeft()),s=_e(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},of=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&_e(t)!==void 0},af=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return y(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},cf=(e,t,s)=>Ni(e)?!kr(s)&&Pi(af(t)):!0,lf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],r=new Set;for(const o of n){if(of(o))continue;const a=_e(o);if(a===void 0)continue;const c=Ai(a);if(c===void 0||!cf(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;r.has(u)||(r.add(u),s.push({file:t,kind:c,line:l,preview:bi(a)}))}return s},df=(e,t)=>{const s=[];for(const n of x(t,{includeSkipped:!0})){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lf(r,I(t,n)))}return s},uf=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?W(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=an(o);if(a===void 0)continue;const c=w(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),u=!l&&U(c);!l&&!u||r.push({exportName:K(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return r},ff=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(r))s.push(...uf(a,o))}return s},gf=new Set(["query","unsafe"]),pf=e=>!i.isPropertyAccessExpression(e)||!gf.has(e.getName())?!1:$(e.getExpression(),["sql"]),mf=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),hf=(e,t)=>{if(!pf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!mf(s)))return{file:t,line:s.getStartLineNumber(),scope:v(e)}},vf=(e,t)=>C(e,t,hf),Ef=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],xf=e=>{for(const[t,s]of Ef)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Sf=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=xf(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},yf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Af=(e,t,s=[])=>{const n=We(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:yf,requireUnmodifiedReach:!0});return bt(n,s)},bf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Nf=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Pf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=y(r);t.push(o),o==="expiresInSeconds"&&(s=Nf(r.getInitializer()));continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},wf=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=bf.get(t);return s===void 0?void 0:en(e.getExpression(),r=>r==="ctx.storage"||r.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},If=(e,t)=>{const s=wf(e.getExpression());if(s!==void 0)return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...Pf(e.getArguments()[s.optionsIndex])}},Cf=(e,t)=>C(e,t,If),Tf=(e,t)=>{const s=$r(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Of=new Set(["delete","hardDelete","patch","replace","restore"]),Rf=new Set(["insertMany","insertManyUnsafe","patchWhere"]),kf=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Ms=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],r=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return r.length===n.length?r:[]},Ff=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const r=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return r===void 0?[]:Ms(r,e)}return Ms(s,e)},_s="",Df=(e,t)=>{if(Rf.has(e))return{method:e,tables:[t!==void 0&&i.isStringLiteral(t)?t.getLiteralText():_s]};if(Of.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:Ff(t,e);return{method:e,tables:s.length===0?[_s]:s}}},Lf=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(_(n))return Df(s,e.getArguments()[0]);if(kf.has(s)&&i.isPropertyAccessExpression(n)&&_(n.getExpression()))return{method:s,tables:[n.getName()]}},Mf=(e,t)=>C(e,t,(s,n)=>{const r=Lf(s);if(r===void 0)return;const o=v(s),a=s.getStartLineNumber();return r.tables.map(c=>({file:n,line:a,method:r.method,scope:o,table:c}))}),_f=(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"}),Kf=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||L(s,"args")===void 0)return!1}return It(e,t).opaque},zf=(e,t)=>{const s=[],n=(r,o)=>{const a=r.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=W(a);c!==void 0&&Kf(a,c.receiver)&&s.push(_f(t,o,a.getStartLineNumber()))};for(const r of e.getVariableStatements().filter(o=>o.isExported()))for(const o of r.getDeclarations())n(o,o.getName());return s},Bf=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n);r!==void 0&&s.push(...zf(r,I(t,n)))}return s.toSorted((n,r)=>n.cacheKey.localeCompare(r.cacheKey))},$f=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ke=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),_n=e=>!e.isAny(),Kn=e=>{const t=e.getType();if(!_n(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:$f.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Uf=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},zn={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."},jf=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.`}),Vf={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)."},qf=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Wf={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)."},Hf=(e,t,s)=>{if(!t.some(r=>Nr(r)))return Vf;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return qf.has(s.typeName)&&!n&&!t.some(r=>Ii(r))?Wf:zn},Bn=(e,t,s,n,r)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,p=u===void 0?r:jf(u),f=c===void 0?p.remediation:`${c} ${p.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${p.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${f}`:f,title:"Procedure exists at runtime but is missing from the generated API"}},Gf=(e,t,s)=>{const n=[];for(const r of j(e)){const o=i.isIdentifier(r.getNameNode())?dt(r):[r.getName()],c=o.some(u=>Ke(s,t,u))||!Uf(r)?void 0:Kn(r),[l=r.getName()]=o;c!==void 0&&n.push(Bn(t,l,c,r.getStartLineNumber(),Hf(r,o,c)))}return n},Yf=(e,t,s)=>{if(Ke(s,t,"default"))return[];const n=[];for(const r of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!i.isIdentifier(o.getExpression()))){const o=Kn(r.getExpression());o!==void 0&&n.push(Bn(t,"default",o,r.getStartLineNumber(),zn))}return n},Qf=(e,t,s)=>[...Gf(e,t,s),...Yf(e,t,s)],Xf=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>i.isIdentifier(n.getNameNode())).filter(n=>dt(n).some(r=>Ke(s,t,r))).filter(n=>{const r=n.getInitializer();return r!==void 0&&i.isCallExpression(r)&&i.isPropertyAccessExpression(r.getExpression())}).map(n=>{const r=dt(n).find(o=>Ke(s,t,o))??n.getName();return{declaration:n,exportName:r,relativePath:t}}),Jf=({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"}),Zf=(e,t,s)=>{const n=[],r=[];for(const a of x(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...Qf(c,l,s)),r.push(...Xf(c,l,s))}const[o]=r;return o!==void 0&&r.every(({declaration:a})=>!_n(a.getType()))&&n.push(Jf(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},eg=new Set(["when","where"]),ct=new Set(["definePolicy","defineShape"]),tg=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return ct.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const r=n.getNameNode().getText();return ct.has(r)?r:void 0}const s=t.getText();return ct.has(s)?s:void 0},sg=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,$n=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(sg(e))return"empty-object";if(i.isParenthesizedExpression(e))return $n(e.getExpression())}},Tt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),ng=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>Tt(t)===e),Un=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>Tt(t)===e),rg=e=>{const t=ng(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||Un(e).length>0},ig=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>Tt(t)===e),yt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",og=(e,t)=>yt(e)||yt(t),ag=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Ks=e=>!yt(e)&&(i.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),cg=(e,t,s)=>{const n=ag.get(e);if(n!==void 0)return og(t,s)?n==="positive"?"negative":"positive":Ks(t)||Ks(s)?void 0:n},fe=e=>{if(i.isParenthesizedExpression(e))return fe(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=cg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=fe(e.getLeft()),r=fe(e.getRight());return n===r?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},zs=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},lg=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},dg=e=>i.isReturnStatement(e)?e.getExpression()??e:e,ug=e=>{const t=[];for(const s of Un(e)){const n=fe(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of ig(e)){const n=fe(s.getExpression());if(n==="indeterminate")continue;const r=n==="negative"?zs(s.getThenStatement()):zs(s.getElseStatement())??lg(s);r!==void 0&&t.push(dg(r))}return t},fg=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},gg=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)||!eg.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&rg(a))for(const c of ug(a)){const l=$n(c);l!==void 0&&r.push({exportName:fg(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return r},pg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=tg(n);r!==void 0&&s.push(...gg(n,r,t))}return s},mg=(e,t)=>{const s=[];for(const n of x(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pg(r,I(t,n)))}return s},hg=new Set(["query","upsert","upsertNow"]),vg=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(hg.has(t))return $(e.getExpression(),["vectors"])?t:void 0},Eg=(e,t)=>{const s=vg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const r=w(n,"namespace");if(!(!r||!U(r)||ee(r)))return{scope:v(e),file:t,line:e.getStartLineNumber(),method:s}},xg=(e,t)=>C(e,t,Eg),Sg=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},yg=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Ag=(e,t)=>C(e,t,(s,n)=>Sg(s)?{file:n,line:s.getStartLineNumber(),scope:v(s),workflow:yg(s)}:void 0),bg=".lunora-schema.json",ze=(e,t)=>{T(e)&&er(e,"utf8")===t||tr(e,t,"utf8")},Ng=(e,t)=>{if(t===""){lt(e,{force:!0});return}ze(e,t)},Pg=(e,t)=>{const s=h(e,"services");if(Object.keys(t).length===0){lt(s,{force:!0,recursive:!0});return}if(T(s))for(const n of Zn(s,{recursive:!0,withFileTypes:!0})){const r=h(n.parentPath,n.name);n.isFile()&&t[sr(e,r)]===void 0&<(r)}for(const[n,r]of Object.entries(t))Us(de(h(e,n)),{recursive:!0}),ze(h(e,n),r)},wg=e=>{try{const t=rr(h(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Ig=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Cg=e=>{let t=T(e)?e:de(e);for(;t&&t!==de(t);){const s=h(t,"tsconfig.json");if(T(s))return s;t=de(t)}},Bs=e=>e.replaceAll("\\","/"),Tg=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new Y("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const r=t.columns.length>0;for(const o of e){if(o.table===void 0){if(r)throw new Y("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 Y("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})}},ge=(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)},$s=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Og=8,Rg=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:r,migrations:o,project:a,shapes:c,usesSandbox:l,useUmbrella:u,workflows:p}=e,f=()=>ni(()=>{const P=ri(a,r),F=gi(a,r);return{functions:P,httpRoutes:ii(a,r),mutators:F}});let{erased:m,value:{functions:S,httpRoutes:z,mutators:V}}=f();rs([...S,...V].map(P=>P.filePath)),rs(z.filter(P=>P.stream).map(P=>P.filePath),"http-stream");for(let P=1;;P+=1){const F=Mi({agents:t,functions:S,httpRoutes:z,mutators:V,useUmbrella:u,workflows:p}),q=Gi({agents:t,functions:S,migrations:o,mutators:V,shapes:c,useUmbrella:u,usesSandbox:l});if(P>=Og||$s(a,s,F)&&$s(a,n,q))return{apiContent:F,erased:m,functions:S,functionsContent:q,httpRoutes:z,mutators:V};ge(a,s,F),ge(a,n,q),{erased:m,value:{functions:S,httpRoutes:z,mutators:V}}=f()}},kg=e=>{const t=Cg(e);return t?new es({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new es({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Hp=(e,t)=>{const s=x(t),n=h(t,"schema.ts");T(n)&&s.push(n);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const r=new Set(s.map(c=>Bs(c))),o=Bs(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!r.has(l)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const l=c.getFilePath();if(!(l===o||l.startsWith(a)||l.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Gp=e=>{const t=Ig(),s=t?tt.now():0,n=h(e.projectRoot,e.lunoraDirectory??"lunora"),r=h(n,"schema.ts");if(!T(r))throw new Y("INTERNAL",`schema.ts not found at ${r}`);const o=e.project??kg(n);Qr(Fc);const a=yi(o,r,e.projectRoot),{agents:c,capabilities:l,containers:u,crons:p,dataModelContent:f,dependencies:m,entryCronTriggers:S,env:z,featureUsage:V,hasFlags:P,hasNotify:F,identity:q,platformGate:H,queues:D,serverContent:te,services:se,storageRulesMetadata:ae,topics:ne,usesSandbox:xe,useUmbrella:B,workflows:M}=Uo({lunoraDirectory:n,project:o,projectRoot:e.projectRoot,schema:a,target:e.target});hl(a,a.jurisdiction===void 0?void 0:pl(o,n));const O=h(n,"_generated"),R=h(O,"dataModel.ts"),jn=h(O,"server.ts"),Vn=h(O,"api.ts"),qn=h(O,"functions.ts");ge(o,R,f),ge(o,jn,te);const He=Object.fromEntries(se.filter(g=>g.rpcEntrypoint!==void 0).flatMap(g=>Object.entries(Vr(g,O))));for(const[g,b]of Object.entries(He))ge(o,h(O,g),b);const Se=li(o,n),re=wi(o,n),{apiContent:Ot,erased:Wn,functions:G,functionsContent:Rt,httpRoutes:Ge,mutators:ye}=Rg({agents:c,apiPath:Vn,generatedFunctionsPath:qn,lunoraDirectory:n,migrations:Se,project:o,shapes:re,useUmbrella:B,usesSandbox:xe,workflows:M}),kt=dr(o,n),Ye=ur(kt,a,[...G,...Ge].map(g=>g.filePath)),Ae=kt.length>0,X=e.lint===!1&&!Ae?void 0:{inserts:ai(o,n),queries:vi(o,n),tableWrites:Mf(o,n),workflowCalls:Ag(o,n)},be=e.lint===!1||X===void 0?void 0:or({adminRoutes:Qo(o,n),aiRawRuns:ia(o,n),aiToolSideEffects:ha(o,n),argumentDerivedFetches:xa(o,n),argumentValidators:Ta(o,n),authApiCalls:Xr(o,n),authConfigs:za(o,n),browserUrlAccesses:ja(o,n),configCalls:sc(o,n),containerKeyAccesses:rc(o,n),containerOverrides:dc(o,n),containers:u,exportSinks:pc(o,n),staleMigrationImports:Sf(o,n),failOpenGuards:xc(o,n),flagReads:Cc(o,n),flagSecurityDefaults:kc(o,n),geoIndexUsages:Mc(o,n),httpActionGuards:Gc(o,n),httpHeaderWrites:rl(o,n),hyperdriveCalls:oi(o,n),identityClaimReads:dl(o,n),imageDeliveryUrlAccesses:fl(o,n),inserts:X.inserts,kvKeyAccesses:El(o,n,G),mailRecipientAccesses:bl(o,n),maskProcedures:ci(o,n),maskStrategies:Rl(o,n),mutatorWrites:_l(o,n),nondeterministicCalls:pi(o,n),normalizeIdAuthorizations:Jl(o,n),notifyCalls:hi(o,n),notifyConfig:mi(o,n),mutators:ye,ownerFieldWrites:zd(o,n,G,ye),unrestrictedWhereBranches:mg(o,n),paymentWebhooks:Hd(o,n),privilegedDispatches:ru(o,n),procedureProtections:$u(o,n),queries:X.queries,queues:D,r2sqlCalls:Ei(o,n),ratelimitKeySelectors:Gu(o,n),rawRowReturns:tf(o,n),relationLoads:rf(o,n),rlsProcedures:xi(o,n),schema:a,secretLiterals:df(o,n),modules:Ye,shapes:re,softDeleteReads:ff(o,n),sqlInterpolations:vf(o,n),storageKeyAccesses:Af(o,n,G),storageUploads:Cf(o,n),tableWrites:X.tableWrites,vectorNamespaceAccesses:xg(o,n),workflowCalls:X.workflowCalls,workflows:M,wranglerVariables:e.wranglerVariables}),Ft=be===void 0?[]:Qi(e.projectRoot,[...nr(be,{source:"static"}),...Zf(o,n,{byName:new Set([...M,...D,...c,...u].map(g=>g.exportName)),byPath:new Set([...G,...ye,...re,...Se].map(g=>`${g.filePath}:${g.exportName}`))}),...Bf(o,n),...si(Wn,n)]),Hn=Si(o,n),Dt=Cl(o,n);Tg(re,Dt,wl(o,n));const Gn=P?bc(o,n):[],Qe=H.signals.vectorStore!==!1,ce=Tf(V,{containerCount:u.length,cronCount:p.length,dependencies:m,hasPaymentTables:Ud(a.tables),queueCount:D.length,storageColumnCount:Object.keys(Zs(a)).length,storageRuleCount:ae.rules.length,vectorIndexCount:a.vectorIndexes.length,target:Js(e.projectRoot,e.target),vectorStoreSupported:Qe,workflowCount:M.length}),Lt=t?tt.now():0,Xe=Fi(a,Se.map(g=>g.id)),Mt=Ur({advisories:Ft.filter(g=>g.name!=="procedure_type_check_unavailable"),advisorProcedures:be?.procedureProtections??[],agents:c,capabilities:l,containers:u,env:z,flagKeys:Gn,hasFlags:P,hasNotify:F,hasVectors:Qe,maskMetadata:Dt,mutators:ye,queues:D,rlsMetadata:Hn,schema:a,schemaSnapshot:Xe,shapes:re,services:se,storageRules:ae,studioFeatures:ce,topics:ne,useUmbrella:B,workflows:M}),_t=Di(re,m.has("@lunora/db"),B),Kt=_i(u,a.jurisdiction),zt=Ki(M),Bt=zi(c),$t=Bi(D),Ut=$i(p),Yn=Ui(ce.scheduler),Qn=ji(a.tables,B),Xn=lr(e.projectRoot)?Vi(B):"",jt=qi(a.vectorIndexes),Ne=Hi(a,B),Vt=Li(m.has("@lunora/seed")),Pe=e.apiSpec??"openapi",Je=Pe==="openapi"||Pe==="both",Ze=Pe==="openrpc"||Pe==="both",qt=Ci({capabilities:l,emailAgents:c.filter(g=>g.onEmail===!0).map(g=>({className:g.className,exportName:g.exportName})),hasAccess:m.has("@lunora/cloudflare-access"),hasAuth:m.has("@lunora/auth"),hasFramework:m.has("@lunora/astro")||m.has("@lunora/svelte")||m.has("@lunora/vue")||T(h(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(g=>js(g)),hasHyperdriveGlobal:a.tables.some(g=>Vs(g)),hasKvIntrospector:ce.kv,hasNotify:F,hasQueue:D.some(g=>g.mode==="push"),hasScheduler:ce.scheduler,hasSourcedTables:a.tables.some(g=>g.externalSource!==void 0),hasStorage:ce.storage,hasVectors:Qe,hasWorkflow:M.length>0,identity:q,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(g=>({name:g.name,shardMode:g.shardMode})),useUmbrella:B,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(g=>g.voice===!0&&g.voiceBindingName!==void 0).map(g=>({bindingName:g.voiceBindingName,exportName:g.exportName})),wantsArchitecture:Ae,wantsOpenApi:Je,wantsOpenRpc:Ze}),Wt=wg(e.projectRoot),Ht=Ae?Ye:[],Gt=Ti({functions:G,httpRoutes:Ge,modules:Ht,version:Wt}),Yt=Ri({functions:G,modules:Ht,version:Wt}),Qt=`${JSON.stringify(Gt,void 0,2)}
|
|
9
|
+
`,Xt=`${JSON.stringify(Yt,void 0,2)}
|
|
10
|
+
`,we=Ae&&X!==void 0?fo({...X,callEdges:Ga(o,n),crons:p,functions:G,httpRoutes:Ge,modules:Ye,queues:D,schema:a,services:se,topics:ne,workflows:M}):void 0,Jt=Oi(Gt),Zt=ki(Yt),et=h(n,bg),Jn=T(et),Ie=[];if(!e.dryRun){T(O)||Us(O,{recursive:!0});const g=(J,ie)=>{ze(h(O,J),ie),Ie.push(J)},b=(J,ie)=>{Ng(h(O,J),ie),ie!==""&&Ie.push(J)};g("app.ts",qt),g("dataModel.ts",f),g("api.ts",Ot),g("server.ts",te),g("functions.ts",Rt),g("shard.ts",Mt),g("crons.ts",Ut),g("vectors.ts",jt),g("drizzle.global.ts",Ne.global),g("drizzle.shard.ts",Ne.shard),b("containers.ts",Kt),b("workflows.ts",zt),b("agents.ts",Bt),b("queues.ts",$t),b("scheduler.ts",Yn),b("shardRegistry.ts",Qn),b("durableObjects.ts",Xn),b("seed.ts",Vt),b("collections.ts",_t),Pg(O,He),Ie.push(...Object.keys(He)),b("openapi.json",Je?Qt:""),b("openapi.ts",Je?Jt:""),b("openrpc.json",Ze?Xt:""),b("openrpc.ts",Ze?Zt:""),b("architecture.json",we===void 0?"":`${JSON.stringify(we,void 0,2)}
|
|
11
|
+
`),b("architecture.ts",we===void 0?"":go(we)),(!Jn||e.updateSchemaBaseline===!0)&&ze(et,ir(Xe))}if(t){const g=tt.now(),b=Math.round(g-s),J=Math.round(Lt-s),ie=Math.round(g-Lt);console.error(`@lunora/codegen: codegen took ${b.toString()}ms (discovery ${J.toString()}ms, emit ${ie.toString()}ms)`)}return{advisories:Ft,advisorContext:be,agents:c,containers:u,cronTriggers:[...new Set([...Wi(p),...S])],generated:{agents:Bt,api:Ot,app:qt,collections:_t,containers:Kt,crons:Ut,dataModel:f,drizzleGlobal:Ne.global,drizzleShard:Ne.shard,functions:Rt,openApi:Qt,openApiModule:Jt,openRpc:Xt,openRpcModule:Zt,queues:$t,seed:Vt,server:te,shard:Mt,vectors:jt,workflows:zt},migrations:Se,outputDirectory:O,platformDiagnostics:H.diagnostics,queues:D,schemaSnapshot:Xe,schemaSnapshotPath:et,workflows:M,writtenFiles:Ie}};export{bg as SCHEMA_SNAPSHOT_FILENAME,kg as createCodegenProject,Cg as findTsconfig,Hp as refreshCodegenProject,Gp as runCodegen};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./CAPABILITY_PROBES-brcmKenl.mjs";import"./ir-DBSvhNa-.mjs";import{e}from"./server-dr22ile6.mjs";import"./shared-BXUKWh7t.mjs";export{e as default};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`:"",
|
|
3
|
-
readonly containers: {${
|
|
4
|
-
readonly ${e.exportName}: ${
|
|
5
|
-
};`:"",
|
|
6
|
-
readonly ${e.bindingName}?: unknown;`)),...
|
|
1
|
+
import{CAPABILITIES as Re}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{p as Se}from"./ir-DBSvhNa-.mjs";import{join as q,relative as m,dirname as Q,isAbsolute as De,sep as Me}from"node:path";import{ts as i,Project as Ce}from"ts-morph";import{G as Z,a as $,u as Ne,d as Ae}from"./shared-BXUKWh7t.mjs";const ee=/(?:\.d)?\.([cm]?)tsx?$/u,Fe=t=>t.replace(ee,".d.$1ts"),te=(t,n)=>{const a=m(t,n).split(Me).join("/").replace(ee,".$1js");return a.startsWith(".")?a:`./${a}`},ae=t=>t.replaceAll("\\","/"),E=(t,n,a)=>ae(q(t,Fe(m(n,a)))),Pe=t=>te(".",q("services",t.name,m(Q(t.wranglerPath),t.main))),We=t=>{const n=[],a=r=>{(i.isImportDeclaration(r)||i.isExportDeclaration(r))&&r.moduleSpecifier!==void 0&&i.isStringLiteral(r.moduleSpecifier)?n.push(r.moduleSpecifier):i.isImportTypeNode(r)&&i.isLiteralTypeNode(r.argument)&&i.isStringLiteral(r.argument.literal)&&n.push(r.argument.literal),i.forEachChild(r,a)};return a(t),n},Ge=(t,n)=>{const a=Q(t.wranglerPath),r=m(a,t.main);if(r.startsWith("..")||De(r))throw new Error(`@lunora/codegen: service "${t.name}": its entry module (${t.main}) must be inside ${a} to be typed as RPC`);const d=q(n,"services",t.name),c=i.findConfigFile(a,o=>i.sys.fileExists(o)),p=new Ce({compilerOptions:{composite:!1,declaration:!0,declarationMap:!1,emitDeclarationOnly:!0,incremental:!1,noEmit:!1,noEmitOnError:!1,outDir:d,rootDir:a},skipAddingFilesFromTsConfig:!0,...c===void 0?{}:{tsConfigFilePath:c}});p.addSourceFileAtPath(t.main),p.resolveSourceFileDependencies();const u={...p.getCompilerOptions(),preserveSymlinks:!0},x=new Map(p.getSourceFiles().map(o=>o.getFilePath()).filter(o=>!o.endsWith(".d.ts")&&!m(a,o).startsWith("..")).map(o=>[E(d,a,o),o])),y={};for(const o of p.emitToMemory({emitOnlyDtsFiles:!0}).getFiles()){const g=x.get(ae(o.filePath));if(g===void 0)continue;const h=i.createSourceFile(o.filePath,o.text,i.ScriptTarget.Latest,!1);let{text:f}=o;for(const b of We(h).toReversed()){const s=i.resolveModuleName(b.text,g,u,i.sys).resolvedModule?.resolvedFileName;if(s===void 0)continue;const T=E(d,a,s),v=x.has(T)?T:s;f=`${f.slice(0,b.getStart(h))}${JSON.stringify(te(Q(o.filePath),v))}${f.slice(b.getEnd())}`}y[m(n,o.filePath)]=`${Z}${f}`}if(y[m(n,E(d,a,t.main))]===void 0)throw new Error(`@lunora/codegen: service "${t.name}": TypeScript emitted no declaration for its entry module ${t.main}`);return y},je=(t,n=[])=>{const a=new Set;for(const r of t.tables)for(const d of Object.values(r.shape)){const c=Ne(d);c.kind==="storage"&&typeof c.bucket=="string"&&c.bucket!==""&&a.add(c.bucket)}for(const r of n)r!==""&&r!=="default"&&a.add(r);return["default",...[...a].toSorted((r,d)=>r.localeCompare(d))]},He=({agents:t=[],capabilities:n=new Set,containers:a=[],env:r,hasVectors:d=!0,hasFlags:c=!1,hasNotify:p=!1,identity:u,queues:x=[],schema:y,services:o=[],storageRuleBuckets:g=[],topics:h=[],useUmbrella:f=!1,workflows:b=[]}={})=>{const s=Ae(f),T=je(y??{tables:[]},g).map(e=>JSON.stringify(e)).join(" | "),v=e=>e.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",re=[...new Set(a.map(e=>v(e)))].toSorted((e,l)=>e.localeCompare(l)),oe=a.length>0?`import type { ${re.join(", ")} } from "@lunora/container";
|
|
2
|
+
`:"",ne=a.length>0?`
|
|
3
|
+
readonly containers: {${a.map(e=>`
|
|
4
|
+
readonly ${e.exportName}: ${v(e)};`).join("")}
|
|
5
|
+
};`:"",L=[...n.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...a.map(e=>($(e.bindingName,`container binding "${e.bindingName}"`),` /** Durable Object namespace for the \`${e.exportName}\` container. */
|
|
6
|
+
readonly ${e.bindingName}?: unknown;`)),...x.map(e=>($(e.bindingName,`queue binding "${e.bindingName}"`),` /** Queue producer binding for the \`${e.exportName}\` queue. */
|
|
7
7
|
readonly ${e.bindingName}?: unknown;`))].join(`
|
|
8
|
-
`),
|
|
8
|
+
`),se=`
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* This project's Cloudflare bindings, as far as codegen can discover them from
|
|
@@ -18,24 +18,24 @@ import{relative as we,isAbsolute as Ie,sep as $e}from"node:path";import{LunoraEr
|
|
|
18
18
|
* surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
|
|
19
19
|
*/
|
|
20
20
|
export interface CloudflareBindings {
|
|
21
|
-
readonly [binding: string]: unknown;${
|
|
22
|
-
${
|
|
21
|
+
readonly [binding: string]: unknown;${L?`
|
|
22
|
+
${L}`:""}
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
26
|
-
export type Env = CloudflareBindings;`,
|
|
27
|
-
readonly vectors: VectorSearch<VectorIndexName>;`:"",
|
|
28
|
-
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",
|
|
26
|
+
export type Env = CloudflareBindings;`,V=e=>Re.map(l=>l.tier!==void 0&&e.includes(l.tier)&&n.has(l.key)?l.serverCtxField:"").join(""),_=V(["every"]),ie=V(["every","action"]),k=d&&(y?.vectorIndexes.length??0)>0,I=k?' | "vectors"':"",G=k?`
|
|
27
|
+
readonly vectors: VectorSearch<VectorIndexName>;`:"",le=k?`
|
|
28
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",de=k?`import type { VectorSearch, VectorSearchReader } from "${s.server}";
|
|
29
29
|
import type { VectorIndexName } from "./dataModel.js";
|
|
30
|
-
`:"",
|
|
30
|
+
`:"",O=c?`
|
|
31
31
|
/** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
|
|
32
|
-
readonly flags: import("${
|
|
32
|
+
readonly flags: import("${s.flags}").LunoraFlags;`:"",B=p?`
|
|
33
33
|
/** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
|
|
34
34
|
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
35
35
|
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
36
|
-
readonly push: import("@lunora/notify").LunoraPush;`:"",
|
|
36
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",w=b.length>0,ce=w?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
37
37
|
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
38
|
-
`:"",
|
|
38
|
+
`:"",ue=w?`
|
|
39
39
|
|
|
40
40
|
/** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
|
|
41
41
|
type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
|
|
@@ -46,56 +46,56 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
46
46
|
|
|
47
47
|
/** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
|
|
48
48
|
export interface LunoraWorkflows {
|
|
49
|
-
${
|
|
49
|
+
${b.map(e=>` get(name: ${JSON.stringify(e.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${e.exportName}>>;`).join(`
|
|
50
50
|
`)}
|
|
51
|
-
}`:"",
|
|
52
|
-
readonly workflows: LunoraWorkflows;`:"",
|
|
53
|
-
${
|
|
54
|
-
`).join("")}`:"",
|
|
51
|
+
}`:"",H=w?' | "workflows"':"",U=w?`
|
|
52
|
+
readonly workflows: LunoraWorkflows;`:"",R=Se(x),S=R.length>0,D=h.length>0,M=[...S?["QueueProducer"]:[],...D?["TopicPublisher"]:[]],z=[...new Set([...R,...h].map(e=>e.filePath))].toSorted((e,l)=>+(l==="queues")-+(e==="queues")||e.localeCompare(l)),C=e=>e==="queues"?"lunoraQueueDefinitions":`lunoraQueueDefinitions${String(z.indexOf(e))}`,pe=M.length>0?`import type { ${M.join(", ")} } from "@lunora/queue";
|
|
53
|
+
${z.map(e=>`import type * as ${C(e)} from "../${e}.js";
|
|
54
|
+
`).join("")}`:"",me=M.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",ye=S?`
|
|
55
55
|
|
|
56
56
|
/** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
|
|
57
57
|
export interface LunoraQueues {
|
|
58
|
-
${
|
|
58
|
+
${R.map(e=>` readonly ${e.exportName}: QueueProducer<QueueBodyOf<typeof ${C(e.filePath)}.${e.exportName}>>;`).join(`
|
|
59
59
|
`)}
|
|
60
|
-
}`:"",
|
|
60
|
+
}`:"",he=D?`
|
|
61
61
|
|
|
62
62
|
/** This project's declared topics, addressable from \`ctx.topics\` by their \`lunora/queues.ts\` export name. */
|
|
63
63
|
export interface LunoraTopics {
|
|
64
|
-
${
|
|
64
|
+
${h.map(e=>` readonly ${e.exportName}: TopicPublisher<QueueBodyOf<typeof ${C(e.filePath)}.${e.exportName}>>;`).join(`
|
|
65
65
|
`)}
|
|
66
|
-
}`:"",
|
|
67
|
-
readonly queues: LunoraQueues;`:"",
|
|
68
|
-
readonly topics: LunoraTopics;`:"",
|
|
69
|
-
${
|
|
70
|
-
`).join("")}`:"",
|
|
66
|
+
}`:"",fe=`${me}${ye}${he}`,J=S?`
|
|
67
|
+
readonly queues: LunoraQueues;`:"",K=D?`
|
|
68
|
+
readonly topics: LunoraTopics;`:"",N=o.length>0,Y=o.filter(e=>e.rpcEntrypoint!==void 0),be=Y.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",xe=N?`import type { ${be} } from "${s.server}";
|
|
69
|
+
${Y.map(e=>`import type * as lunoraService_${e.name} from ${JSON.stringify(Pe(e))};
|
|
70
|
+
`).join("")}`:"",ge=N?`
|
|
71
71
|
|
|
72
72
|
/** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
|
|
73
73
|
export interface LunoraServices {
|
|
74
|
-
${
|
|
74
|
+
${o.map(e=>{$(e.name,`service "${e.name}"`);const l=e.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${e.name}.${e.rpcEntrypoint}>`;return` readonly ${e.name}: ${l};`}).join(`
|
|
75
75
|
`)}
|
|
76
|
-
}`:"",
|
|
77
|
-
readonly services: LunoraServices;`:"",
|
|
78
|
-
`:"",
|
|
76
|
+
}`:"",Te=N?`
|
|
77
|
+
readonly services: LunoraServices;`:"",A=t.length>0,ve=A?`import type { AgentHandle } from "@lunora/agent";
|
|
78
|
+
`:"",ke=A?`
|
|
79
79
|
|
|
80
80
|
/** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
|
|
81
81
|
export interface LunoraAgents {
|
|
82
|
-
${
|
|
82
|
+
${t.map(e=>($(e.exportName,`agent export "${e.exportName}"`),` readonly ${e.exportName}: AgentHandle;`)).join(`
|
|
83
83
|
`)}
|
|
84
|
-
}`:"",
|
|
85
|
-
readonly agents: LunoraAgents;`:"",
|
|
84
|
+
}`:"",X=A?`
|
|
85
|
+
readonly agents: LunoraAgents;`:"",we=u?`import type { InferIdentity } from "${s.server}";
|
|
86
86
|
import type * as lunoraIdentityContract from "../identity.js";
|
|
87
|
-
`:""
|
|
87
|
+
`:"",$e=u?`
|
|
88
88
|
|
|
89
89
|
/** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
|
|
90
|
-
export type Identity = InferIdentity<typeof lunoraIdentityContract.${
|
|
90
|
+
export type Identity = InferIdentity<typeof lunoraIdentityContract.${u.exportName}>;
|
|
91
91
|
|
|
92
92
|
/** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
|
|
93
|
-
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:""
|
|
94
|
-
readonly auth: NarrowedAuth;`:"",
|
|
95
|
-
`:"",
|
|
93
|
+
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",F=u?' | "auth"':"",P=u?`
|
|
94
|
+
readonly auth: NarrowedAuth;`:"",Ie=u?", Identity":"",Oe=r?`import type * as lunoraEnvContract from "../env.js";
|
|
95
|
+
`:"",Be=r?`
|
|
96
96
|
|
|
97
97
|
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
98
|
-
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${
|
|
98
|
+
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${r.exportName}>;`:"",W=r?' | "env"':"",j=r?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${Z}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${s.server}";
|
|
99
99
|
import type {
|
|
100
100
|
ActionBuilder,
|
|
101
101
|
ActionCtx as ActionCtxBase,
|
|
@@ -117,7 +117,7 @@ import type {
|
|
|
117
117
|
Storage as StorageBase,
|
|
118
118
|
TableReader,
|
|
119
119
|
Validator,
|
|
120
|
-
} from "${
|
|
120
|
+
} from "${s.server}";
|
|
121
121
|
|
|
122
122
|
import type {
|
|
123
123
|
DatabaseReaderFacade as DatabaseReaderFacadeOf,
|
|
@@ -126,7 +126,7 @@ import type {
|
|
|
126
126
|
TableReaderFacade as TableReaderFacadeOf,
|
|
127
127
|
TableWriterFacade as TableWriterFacadeOf,
|
|
128
128
|
WithArg as WithArgOf,
|
|
129
|
-
} from "${
|
|
129
|
+
} from "${s.serverDataModel}";
|
|
130
130
|
|
|
131
131
|
export type {
|
|
132
132
|
AggregateOp,
|
|
@@ -149,10 +149,10 @@ export type {
|
|
|
149
149
|
Where,
|
|
150
150
|
WhereOf,
|
|
151
151
|
WhereOperators,
|
|
152
|
-
} from "${
|
|
152
|
+
} from "${s.serverDataModel}";
|
|
153
153
|
|
|
154
154
|
import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
|
|
155
|
-
${
|
|
155
|
+
${de}${oe}${ce}${pe}${xe}${ve}${we}${Oe}
|
|
156
156
|
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
157
157
|
|
|
158
158
|
/**
|
|
@@ -212,7 +212,7 @@ export interface OrmWriter extends OrmReader {
|
|
|
212
212
|
}
|
|
213
213
|
|
|
214
214
|
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
215
|
-
export type StorageBucketName = ${
|
|
215
|
+
export type StorageBucketName = ${T};${se}${ue}${fe}${ge}${ke}${$e}${Be}
|
|
216
216
|
|
|
217
217
|
/**
|
|
218
218
|
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
@@ -275,22 +275,22 @@ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ?
|
|
|
275
275
|
*/
|
|
276
276
|
type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
|
|
277
277
|
|
|
278
|
-
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${
|
|
278
|
+
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${I}${F}${W}> {
|
|
279
279
|
readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
280
280
|
readonly orm: OrmReader;
|
|
281
|
-
readonly storage: ReadOnlyStorage<StorageBucketName>;${
|
|
281
|
+
readonly storage: ReadOnlyStorage<StorageBucketName>;${le}${_}${O}${B}${j}${P}
|
|
282
282
|
}
|
|
283
283
|
|
|
284
|
-
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${
|
|
284
|
+
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${I}${H}${F}${W}> {
|
|
285
285
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
286
286
|
readonly orm: OrmWriter;
|
|
287
|
-
readonly storage: MutationStorage<StorageBucketName>;${
|
|
287
|
+
readonly storage: MutationStorage<StorageBucketName>;${G}${_}${O}${B}${j}${U}${J}${K}${X}${P}
|
|
288
288
|
}
|
|
289
289
|
|
|
290
|
-
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${
|
|
290
|
+
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${I}${H}${F}${W}> {
|
|
291
291
|
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
292
292
|
readonly orm: OrmWriter;
|
|
293
|
-
readonly storage: StorageBase<StorageBucketName>;${
|
|
293
|
+
readonly storage: StorageBase<StorageBucketName>;${G}${ie}${ne}${O}${B}${Te}${j}${U}${J}${K}${X}${P}
|
|
294
294
|
}
|
|
295
295
|
|
|
296
296
|
/**
|
|
@@ -323,7 +323,7 @@ export const internalAction = lunoraBuilders.internalAction as unknown as Intern
|
|
|
323
323
|
/**
|
|
324
324
|
* \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
|
|
325
325
|
* custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
|
|
326
|
-
* \`${
|
|
326
|
+
* \`${s.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
|
|
327
327
|
* schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
|
|
328
328
|
* \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
|
|
329
329
|
* no \`as unknown as\` cast. Runtime-identical to the package export; only the
|
|
@@ -348,7 +348,7 @@ export const defineMutator = defineMutatorBase as unknown as <Args extends Recor
|
|
|
348
348
|
* Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
|
|
349
349
|
* so the \`rls()\` chain discovers a policy authored either way the same.
|
|
350
350
|
*/
|
|
351
|
-
export const definePolicy = createPolicyDsl<DataModel, Relations${
|
|
351
|
+
export const definePolicy = createPolicyDsl<DataModel, Relations${Ie}>();
|
|
352
352
|
|
|
353
353
|
/**
|
|
354
354
|
* The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
|
|
@@ -365,4 +365,4 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Te}>();
|
|
|
365
365
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
366
366
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
367
367
|
};
|
|
368
|
-
`};export{
|
|
368
|
+
`};export{Ge as a,He as e};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.274",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.197",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.185",
|
|
51
51
|
"@lunora/container": "1.0.0-alpha.69",
|
|
52
52
|
"@lunora/errors": "1.0.0-alpha.50",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.57",
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{existsSync as O,mkdirSync as Qn,readFileSync as Xn,writeFileSync as Jn,rmSync as Zn}from"node:fs";import{join as S,dirname as we}from"node:path";import{performance as Ze}from"node:perf_hooks";import{runAdvisor as er}from"@lunora/advisor";import{LunoraError as Y}from"@lunora/errors";import{readJsonSync as tr}from"@visulima/fs";import{SyntaxKind as d,Node as i,Project as Jt}from"ts-morph";import{serializeSchemaSnapshot as sr}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as nr}from"./formatAdvisories-DwmUKYuc.mjs";import{r as rr,a as y,s as ir,b as or}from"./project-config-file-Bv2l-Kmm.mjs";import{a as Pe,d as ar,r as cr}from"./modules-6EEBTEDo.mjs";import{WORKFLOWS_FILENAME as lr,discoverWorkflows as dr}from"./WORKFLOWS_FILENAME-B47AB5pc.mjs";import{r as ur}from"./json-data-Chfs2Cz5.mjs";import{s as Ke}from"./paths-C-9fwEgQ.mjs";import{G as fr}from"./shared-BXUKWh7t.mjs";import{CAPABILITIES as gr,usedCapabilities as pr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Bs,isHyperdriveGlobalTable as $s}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as mr}from"./AGENTS_FILENAME-lBe4g_sU.mjs";import{discoverContainers as hr}from"./CONTAINERS_FILENAME-CY43AXXN.mjs";import vr from"./discoverCrons-PQeDYVPc.mjs";import{diagnosticAt as me}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ze}from"./module-specifiers-WF8iAydP.mjs";import{a as Us,b as V,d as K,f as R,g as St,c as h,w as yt,k as Er,l as xr,h as Sr,j as at,i as yr}from"./attribution-NRssTEkk.mjs";import{contextPropertiesRead as Ar,discoverFeatureUsage as br}from"./capabilitiesUsedBy-DARbl-4Z.mjs";import Nr from"./readPackageDependencies-RHhGiz0k.mjs";import{listLunoraSourceFiles as E,unwrapExpression as v,listSecurityScanFiles as Be,objectLiteralFromCallbackBody as Vs,propertyInitializer as P,lunoraRelativePath as w,bindingKeyName as he,collectCallRows as I,findObjectProperty as D,collectSecurityCallRows as Pr,collectNodeRows as ct,RUN_METHODS as js,functionReferenceSegments as qs,limitNameOf as Ws,optionsObjectLiteral as Hs,handlerOf as wr,chainRootOf as At,outermostValueWrapper as b,isWriteTarget as $e,isSameNode as fe,isConstDeclaration as Z,returningFunctionOf as lt,walkChain as Ir,memberAccessOf as Cr,isTestPath as Tr}from"./isTestPath-DCyIyPa7.mjs";import{discoverQueueDeclarations as Or}from"./QUEUES_FILENAME-DeJw5eqU.mjs";import{discoverSandboxUsage as Rr}from"./discoverSandboxUsage-B8P9QjWZ.mjs";import{resolveServiceBindings as kr}from"./readServiceBindings-DuE9xlvV.mjs";import Fr from"./discoverStorageRulesMetadata-C2hYksmI.mjs";import{a as A,c as W,d as Gs,e as Dr}from"./classify-procedure-call-BBKuBvKg.mjs";import{i as Lr}from"./ir-DBSvhNa-.mjs";import{gatePlatformFeatures as Mr,resolveCodegenTarget as Ys,readTargetDiagnostics as _r,studioPlatformFor as Kr}from"./DEFAULT_TARGET-rlz3WdHe.mjs";import{b as Qs,e as zr}from"./shard-C1ZGdOG1.mjs";import Br from"./emitServer-BSMUAt0o.mjs";import{emitDataModel as $r}from"./emitDataModel-DSk9AkJe.mjs";import{a as Zt,r as et,i as $,b as Ur,m as Xs,c as Ue,e as Js,E as Zs,C as en,d as Vr,f as jr,g as qr}from"./context-root-IuI71QkK.mjs";import{r as Ve,s as Wr}from"./parse-validator-DYdT7Hyf.mjs";import Hr from"./discoverAuthApiCalls-TA2a8bZI.mjs";import{i as Gr,a as Yr,e as Qr,b as Xr,d as Jr,c as Zr}from"./unwrap-handler-return-Dy8h5-I6.mjs";import ei from"./discoverFunctions-4sef11AC.mjs";import ti from"./discoverHttpRoutes-CLGXL19M.mjs";import si from"./discoverHyperdriveCalls-imtma-ic.mjs";import ni from"./discoverInserts-CKEO1mZZ.mjs";import{m as bt,a as Re,s as tn,d as ri}from"./index-CRO3TRxd.mjs";import{e as sn}from"./exported-procedure-chains-DqU-ZCbG.mjs";import ii from"./discoverMigrations-DYQbnqow.mjs";import{i as _,r as nn}from"./database-calls-BFY_pIUf.mjs";import{MUTATORS_FILENAME as oi,isDefineMutatorCallee as ai,mutatorServerImplOf as ci,discoverMutators as li}from"./MUTATORS_FILENAME-BxRrG_s-.mjs";import di from"./discoverNondeterministicCalls-BfdM93-8.mjs";import{discoverNotifyConfig as ui,discoverNotifyCalls as fi}from"./NOTIFY_FILENAME-J5MGAkca.mjs";import gi from"./discoverQueries-DEkIMaBP.mjs";import pi from"./discoverR2sqlCalls-BRIyb8Cl.mjs";import mi from"./discoverRlsProcedures-BtT8-r93.mjs";import hi from"./discoverRlsMetadata-rpiO4wSi.mjs";import vi from"./discoverSchema-BdmC-kO2.mjs";import{secretKindOf as Ei,redact as xi,isHeuristicSecretKind as Si,isSecretishName as yi}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Ai}from"./SHAPES_FILENAME-CeBFuc8M.mjs";import{i as bi}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as Ni}from"./emitApp-BdVXkH7A.mjs";import{buildOpenApiDocument as Pi,emitOpenApiModule as wi}from"./buildOpenApiDocument-6VJGU6fU.mjs";import{buildOpenRpcDocument as Ii,emitOpenRpcModule as Ci}from"./OPENRPC_VERSION-B8RT1JYn.mjs";import{buildSchemaSnapshot as Ti}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Oi,emitSeed as Ri,emitApi as ki}from"./emitApi-xDIHPRPH.mjs";import{t as Fi,u as Di,s as Li,v as Mi}from"./shard-runtime-DGrBvQWg.mjs";import{emitCrons as _i,emitScheduler as Ki,emitShardRegistry as zi,emitDurableObjects as Bi,emitVectors as $i,emitWranglerCronTriggers as Ui}from"./emitCrons-DKeoaeqU.mjs";import Vi from"./emitDrizzleSchema-DohtnI8c.mjs";import ji from"./emitFunctions-evl8Mx1a.mjs";const es={error:"ERROR",info:"INFO",warn:"WARN"},ts={ERROR:2,INFO:0,WARN:1},qi=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"}),Wi=(e,t)=>{const{advisor:s}=rr(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,r=n!==void 0&&Object.hasOwn(es,n)?es[n]:void 0;return r===void 0?[...t,qi(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>ts[o.level]>=ts[r])},Hi={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},Gi="crons",Yi=lr.replace(/\.ts$/u,""),ie=(e,t)=>`${Ke(e)}:${t}`,tt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Qi=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${Hi[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")}))],Xi=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Ji=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Xi(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Zi=e=>Qi(e).flatMap(t=>Ji(t)),eo=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}`,r=s??n;return{file:Gi,from:`cron:${t.name}`,kind:"trigger",line:0,...r===void 0?{reason:"the cron has no target"}:{to:r}}})],to=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),le=(e,t)=>t===void 0?e:{...e,module:t},so=e=>{const t=new Map,s=new Map,n=to(e.modules),r=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&r(l,c.id)},a=(c,l)=>{c!==void 0&&r(ie(c.file,c.exportName),l)};for(const c of e.functions){const l=ie(c.filePath,c.exportName),u=`${Ke(c.filePath)}.${c.exportName}`;o(le({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Pe(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ie(c.filePath,c.exportName);o(le({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Pe(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(le({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(le({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Pe(e.modules,c.filePath)),ie(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(le({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Pe(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ie(Yi,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}},no=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,ro=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ie(e.file,e.exportName))??{reason:no(e.exportName)},io=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=ro(e,t);if("reason"in n)return n;const{to:r}=e;return s.has(r)?{drawn:n.map(o=>({from:o,kind:e.kind,to:r}))}:{reason:`${r} is not declared`}},st=e=>`${e.from}|${e.kind}|${e.to}`,oo=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,ao=e=>{const{nodes:t,sites:s}=so(e),n=new Map,r=new Map;for(const o of[...eo(e),...Zi(e)]){const a=io(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(st(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};r.set(oo(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>st(o).localeCompare(st(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...r.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},co=e=>`${fr}export const architecture = ${ur(e,"Record<string, unknown>")};
|
|
2
|
-
`,ss=(e,t="api")=>{const s=new Map;for(const n of e){const r=Ke(n),o=s.get(r);if(o===void 0){s.set(r,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${r}" twice and the dispatch key "${r}:<fn>" would be ambiguous`:`the generated api.ts would declare "${r}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new Y("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${r}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},lo=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:r=!1,usage:o}=t,a=[];e.tables.some(c=>Bs(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>$s(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),r&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:gr)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)},uo=(e,t,s={})=>{if(t===void 0)return;const n=lo(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const r=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
3
|
-
`);throw new Y("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
4
|
-
${r}
|
|
5
|
-
|
|
6
|
-
Install them with your package manager, then re-run codegen.`)},fo="env.ts",go=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ze(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},po=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&ze(n.getModuleSpecifierValue())}return!1},mo=e=>{if(i.isIdentifier(e))return go(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&po(t)}return!1},ho=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!mo(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw me(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=Us(s,"member");a!==void 0&&t.push({exportName:a})}return t},vo=(e,t)=>{const s=S(t,fo);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=ho(n);if(r.length!==0){if(r.length>1)throw me(n,`lunora/env.ts declares ${r.length.toString()} defineEnv() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},rn="identity.ts",Eo=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ze(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},xo=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&ze(n.getModuleSpecifierValue())}return!1},So=e=>{if(i.isIdentifier(e))return Eo(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&xo(t)}return!1},yo=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!So(n.getExpression()))continue;const o=s.getNameNode();if(!i.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw me(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=Us(s,"member");a!==void 0&&t.push({exportName:a})}return t},Ao=(e,t)=>{const s=S(t,rn);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),r=yo(n);if(r.length!==0){if(r.length>1)throw me(n,`lunora/identity.ts declares ${r.length.toString()} defineIdentity() contracts (${r.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return r[0]}},bo=new Set(["allowedHosts","deniedHosts","interceptHttps"]),No=(e,t)=>{const s=v(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return v(e.getDescendantsOfKind(d.VariableDeclaration).find(r=>r.getName()===n)?.getInitializer())},Po=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(y(s));if(!i.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=v(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),wo=new Set(["durable"]),Io=new Set(["rollback"]),Co=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},To=new Map([["defineContainer",{keys:bo,signal:"containerEgressPolicy"}],["defineStep",{keys:Io,signal:"workflowRollback"}],["stream",{keys:wo,signal:"durableStreams"}]]),Oo=(e,t)=>{const s=To.get(Co(t));if(s!==void 0)return t.getArguments().some(n=>Po(No(e,n),s.keys))?s.signal:void 0},Ro=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Ar(r).has("secrets"));for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=Oo(r,o);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},ko="createWorker",Fo="extend",ns=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,rs=e=>{const t=[],s=ns(P(e,"backupCron"));s!==void 0&&t.push(s);const n=P(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)&&!i.isMethodDeclaration(r))continue;const o=ns(r.getNameNode());o!==void 0&&t.push(o)}return t},Do=e=>{const t=A(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===ko)return i.isObjectLiteralExpression(s)?rs(s):[];if(t!==Fo||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=Vs(s.getBody());return n===void 0?[]:rs(n)},Lo=(e,t)=>{const s=[];for(const{filePath:n}of Be(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression))s.push(...Do(o))}return[...new Set(s)]},on=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:on(e.inner)},Mo=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const r=on(n);return r!==void 0&&t.has(r)}))},_o=(e,t)=>{const s=new Map,n=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const o=s.get(r.name);if(o!==void 0)throw new Y("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${o} and agent "${r.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(r.className);if(a!==void 0)throw new Y("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${a} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Ko=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:r}=e,o=Ao(s,t),a=vo(s,t),c=dr(s,t),{queues:l,topics:u}=Or(s,t),p=kr(n),f=mr(s,t);_o(c,f);const m=hr(s,t),x=Fr(s,t),z=vr(s,t,c,f),j=Lo(s,t),N=Ro(s,t),k=Rr(s,t),q=br(s,t);q.browser=q.browser||k.usesSandboxBrowser;const H=Mr(q,Ys(n,e.target),{agents:f.length>0,commitOrderedTables:r.tables.some(T=>T.commitOrdered===!0),cronTriggers:z.length>0,crossShardFanout:r.tables.some(T=>Lr(T)),containerEgressPolicy:N.containerEgressPolicy,containerRuntimeScheduling:m.some(T=>T.schedulingPolicy==="durable_object"),containerSandboxTools:m.some(T=>T.sandbox===!0),durableStreams:N.durableStreams,globalTables:r.tables.some(T=>T.shardMode==="global"),queues:l.length>0,relationGraph:Mo(r),secrets:N.secrets,services:p.length>0,topics:u.length>0,vectorStore:r.vectorIndexes.length>0,workerLoaders:k.usesSandboxLoader,workflowRollback:N.workflowRollback,workflowSchedules:c.some(T=>T.schedules!==void 0)}),F=H.usage,te=pr(F),oe=H.signals.vectorStore!==!1,ae=H.signals.services===!1?[]:p,se=Nr(n),ve=se??new Set,B=ve.has("lunorash");uo(r,se,{hasVectors:oe,scheduler:F.scheduler||z.length>0,storage:F.storage||x.rules.length>0||Object.keys(Qs(r)).length>0,usage:F});const L=O(S(t,"flags.ts")),M=O(S(t,"notify.ts"));return{agents:f,capabilities:te,containers:m,crons:z,dataModelContent:$r(r),declaredDependencies:se,dependencies:ve,entryCronTriggers:j,env:a,featureUsage:F,hasFlags:L,hasNotify:M,identity:o,platformGate:{...H,diagnostics:[..._r(n,e.target),...H.diagnostics]},queues:l,serverContent:Br({agents:f,capabilities:te,containers:m,env:a,hasVectors:oe,hasFlags:L,hasNotify:M,identity:o,queues:l,schema:r,generatedDirectory:S(t,"_generated"),services:ae,storageRuleBuckets:x.rules.map(T=>T.bucket),topics:u,useUmbrella:B,workflows:c}),services:ae,storageRulesMetadata:x,topics:u,usesSandbox:k.usesSandboxBrowser||k.usesSandboxContainer||k.usesSandboxFs,useUmbrella:B,workflows:c}},an=new Set(["delete","get","head","options","patch","post","put"]),zo=new Set(["handler","stream"]),Bo=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,is=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),$o=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!an.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Uo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||an.has(n.getName()))break;s=n.getExpression()}return $o(s)},Vo=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(is.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&is.has(s.getText()))return!0}return!1},jo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!zo.has(n.getName()))return;const r=Uo(s);if(!r||!Bo.test(r.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&Vo(o);return{exportName:K(e)??e.getName(),file:t,method:r.method,path:r.path,usesGuard:a}},qo=(e,t)=>{const s=[];for(const n of V(e)){const r=jo(n,t);r&&s.push(r)}return s},Wo=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...qo(r,w(t,n)))}return s},Ho=e=>{const t=e.getText(),s=n=>{const r=n.getNameNode();return i.isIdentifier(r)&&r.getText()===t};for(const n of e.getAncestors())if(!(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)&&!i.isFunctionDeclaration(n)))for(const r of n.getParameters()){const o=r.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Go=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isObjectBindingPattern(s))return;const n=s.getParent();if(i.isBindingElement(n)){t=n;continue}return i.isParameterDeclaration(n)?he(t):void 0}},Yo=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=i.isFunctionLikeDeclaration(o)||i.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(i.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&Zt(a)}))return!1;const n=R(e),r=i.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return r!==void 0&&(i.isParameterDeclaration(n)||i.isBindingElement(n))&&Zt(r)},os=(e,t)=>{const s=e.getParent();if(i.isPropertyAccessExpression(s)&&s.getNameNode()===e||i.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Ho(e);return n!==void 0&&Go(n)===t?!0:t==="args"&&Yo(e)},cn=(e,t)=>i.isIdentifier(e)?os(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>os(s,t)),Qo=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},as=e=>{const t=i.isIdentifier(e)?R(e):void 0;return i.isVariableDeclaration(t)&&i.isIdentifier(t.getNameNode())&&!St(t)?t.getInitializer():void 0},dt=e=>cn(e,"args"),Q=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let r,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(r=c,o=l)}return r},U=e=>{if(dt(e))return!0;const t=Q(e);return t!==void 0&&dt(t)},Xo=e=>{if(i.isCallExpression(e)||i.isNewExpression(e))return!1;const t=Q(e);return t===void 0||!(i.isCallExpression(t)||i.isNewExpression(t))},ee=e=>{if(et(e))return!0;const t=as(e);if(t!==void 0&&et(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(r=>{const o=as(r);return o!==void 0&&et(o)})},Ie=(e,t)=>cn(e,t),Jo=(e,t)=>{if(Ie(e,t))return!0;const s=Q(e);if(s!==void 0&&Ie(s,t))return!0;const n=Qo(e);if(n!==void 0){const r=Q(n);return r!==void 0&&Ie(r,t)}return!1},Zo=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:$(e.getExpression(),["ai"]),ea=(e,t)=>{if(!Zo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!U(s)||ee(s)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},ta=(e,t)=>I(e,t,ea),sa=new Set(["generateText","streamText"]),na=new Set(["messages","prompt","system"]),ra=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],ia=(e,t)=>ra.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),oa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Ur(t.getExpression()),t.getExpression().getText()].find(r=>r!==void 0&&ia(r,s));return n===void 0?void 0:`${n}.${s}`},aa=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=oa(t);if(s!==void 0)return s}},ca=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],r=n?.getNameNode();if(r===void 0||!i.isObjectBindingPattern(r))return t;for(const o of r.getElements()){const a=he(o),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},la=e=>{if(dt(e))return!0;const t=ca(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},da=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!na.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&la(s))return!0}return!1},ua=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=A(n.getExpression());if(r===void 0||!sa.has(r))continue;const[o]=n.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(A(c.getExpression())==="tool"&&(a=aa(c),a!==void 0))break;a!==void 0&&s.push({scope:h(n),file:t,line:n.getStartLineNumber(),method:r,sideEffect:a,userInputDerived:da(o)})}return s},fa=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ua(r,w(t,n)))}return s},ga=e=>$(e,["fetch"]),pa=(e,t)=>{if(!ga(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!U(s)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},ma=(e,t)=>I(e,t,pa),Nt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=Ve(s.getExpression());return n===void 0||Nt(n,t)})}finally{t.delete(e)}},ha=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=D(t,"args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),r=n===void 0?void 0:Ve(n);return r===void 0?{objects:[],opaque:!0}:{objects:[r],opaque:Nt(r)}},va=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const r=n.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&i.isExpression(o)?Ve(o):void 0;a===void 0?s=!0:(t.push(a),s||=Nt(a))}n=r.getExpression()}return{objects:t,opaque:s}},Pt=(e,t)=>t?va(t):ha(e),ln=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=Ve(s.getExpression());return n===void 0?[]:ln(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},Ea=e=>e.flatMap(t=>ln(t,new Set)),xa=new Set(["check","length","max"]),ut=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Sa=e=>[e,...e.getDescendants()].filter(t=>ut(t)!==void 0),ya=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(xa.has(s.getName()))return!0;t=n}},Aa=e=>{const t=[],s=[];for(const n of e)for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=Sa(o),c=y(r);a.some(l=>ut(l)==="any")?t.push(c):a.some(l=>ut(l)==="string"&&!ya(l))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},ba=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=W(s);if(n?.visibility!=="public")return;const{objects:r}=Pt(s,n.receiver),{anyArgs:o,unboundedStringArgs:a}=Aa(r);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:K(e)??e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Na=(e,t)=>{const s=[];for(const n of V(e)){const r=ba(n,t);r&&s.push(r)}return s},Pa=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Na(r,w(t,n)))}return s},nt=e=>e?.getKind()===d.TrueKeyword,wa=e=>e?.getKind()===d.FalseKeyword,Ia=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Ca=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Ta=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&A(t.getExpression())==="scim"),Oa=e=>e!==void 0&&i.isCallExpression(e)&&Ca.has(A(e.getExpression())??""),Ra=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),ka=e=>{const t=P(e,"advanced"),s=P(e,"emailAndPassword"),n=P(e,"session");return{analyzable:!0,disableCsrfCheck:nt(P(t,"disableCSRFCheck")),emailPasswordEnabled:nt(P(s,"enabled")),requireEmailVerification:nt(P(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Ta(P(e,"plugins"))&&Oa(P(e,"database")),secureCookiesDisabled:wa(P(t,"useSecureCookies")),sessionFreshAgeZero:Ia(P(n,"freshAge")),trustedOriginsWildcard:Ra(P(e,"trustedOrigins"))}},Fa=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Da=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),r=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?ka(s):Fa();return{scope:h(e),file:t,line:e.getStartLineNumber(),...r}},La=(e,t)=>Pr(e,t,Da),Ma=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return Xs(e.getExpression(),t.matchReceiver)?s:void 0},_a=(e,t,s)=>{const n=Ma(e.getExpression(),s);if(n===void 0)return;const r=e.getArguments()[s.argIndex];if(!(!r||!U(r)||ee(r))&&!(s.requireUnmodifiedReach===!0&&!Xo(r)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:n}},je=(e,t,s)=>I(e,t,(n,r)=>_a(n,r,s)),Ka=new Set(["content","pdf","scrape","screenshot"]),za=(e,t)=>je(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ka}),dn=e=>{const t=qs(e);return t===void 0?void 0:`${Ke(t.slice(0,-1).join("/"))}:${String(t.at(-1))}`},un=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},Ba=e=>{if(!i.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||i.isIdentifier(t)&&t.getText()==="scheduler"},$a=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),Ua=(e,t)=>{const s=dn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:"the function reference is not a static api.* / internal.* chain"}:void 0},Va=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),[n,r]=e.getArguments();if(js.has(s))return Ua(s,n);if((s==="runAfter"||s==="runAt")&&Ba(t)){const c=dn(r);return c===void 0?{kind:"schedule",reason:"the scheduled function is not a static api.* / internal.* chain"}:{kind:"schedule",target:c}}const o=$a.get(s),a=o===void 0?void 0:un(t,o.surface);return o===void 0||a===void 0?void 0:{kind:o.kind,target:a}},cs=(e,t,s)=>s===void 0?void 0:{...s,file:t,line:e.getStartLineNumber(),scope:h(e)},ja=(e,t)=>[...I(e,t,(s,n)=>cs(s,n,Va(s))),...ct(e,t,d.PropertyAccessExpression,(s,n)=>{const r=un(s,"services");return cs(s,n,r===void 0?void 0:{kind:"invoke",target:r})})],qa=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Wa=new Set(["RateLimiter"]),Ha=new Set(["extend"]),ls="lunora",Ga=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],fn=e=>{const t=[],s=[];let n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=y(r);t.push(o),r.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,presentKeys:t,trueKeys:s}},ft=e=>e&&i.isObjectLiteralExpression(e)?fn(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Ya=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Vs(t.getBody());return s?fn(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Qa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=A(n.getExpression());r!==void 0&&(qa.has(r)?s.push({callee:r,file:t,line:n.getStartLineNumber(),...ft(n.getArguments()[0])}):Ha.has(r)&&s.push({callee:r,file:t,line:n.getStartLineNumber(),...Ya(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const r=A(n.getExpression());r===void 0||!Wa.has(r)||s.push({callee:r,file:t,line:n.getStartLineNumber(),...ft(n.getArguments()[0])})}return s},Xa=(e,t)=>{for(const s of Ga){const n=S(t,s);if(!O(n))continue;const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of r.getDescendantsOfKind(d.CallExpression))A(a.getExpression())===ls&&o.push({callee:ls,file:s,line:a.getStartLineNumber(),...ft(a.getArguments()[0])});return o}return[]},Ja=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Be(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Qa(o,n))}return s.push(...Xa(e,we(t))),s},ds="ctx.containers.",Za=e=>{if(!e.startsWith(ds))return!1;const t=e.slice(ds.length);return t.length>0&&!t.includes(".")},ec=(e,t)=>je(e,t,{argIndex:0,matchReceiver:Za,methods:new Set(["get"])}),tc=new Set(["allow","deny","setAllowed"]),sc=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=D(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},nc=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!sc(e)))return{detail:"enableInternet: true",scope:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},rc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!tc.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},ic=(e,t)=>nc(e,t)??rc(e,t),oc=(e,t)=>I(e,t,ic),ac=new Set(["defineExportSink","r2Sink","webhookExportSink"]),cc=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return ac.has(s)?s:void 0},lc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const r=y(n);t.push(r);const o=n.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(r);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},dc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:r}of Be(t)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=cc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&i.isObjectLiteralExpression(l)?lc(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},uc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),fc=new Set(["dbRateLimit","rateLimit"]),gc=e=>{const t=Hs(e);if(!t)return!1;const s=D(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},pc=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const n=uc.get(s);if(n!==void 0)return{callee:s,scope:h(e),failOpen:gc(e.getArguments()[n]),file:t,limitName:fc.has(s)?Ws(e):"",line:e.getStartLineNumber()}},mc=(e,t)=>I(e,t,pc),hc=new Set(["boolean","number","object","string"]),vc=e=>{const t=e.getName();if(!hc.has(t))return;const s=e.getExpression();return $(s,["flags"])||$(s,["flags","details"])?t:void 0},Ec=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=vc(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const r=n.getLiteralValue();return r.length>0?{key:r,type:s}:void 0},xc=(e,t)=>{const s=new Map;for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getDescendantsOfKind(d.CallExpression)){const a=Ec(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,r])=>({key:n,type:r})).toSorted((n,r)=>n.key.localeCompare(r.key))},Sc=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=W(t);if(s?.kind!=="query")return;const n=wr(t,s.receiver);return n?{exportName:K(e)??e.getName(),handler:n}:void 0},us=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},yc=e=>{const t=us(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=us(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Ac=(e,t)=>{const s=[];for(const n of Ue(e.handler,"flags"))s.push({callee:yc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},bc=(e,t)=>{const s=[];for(const n of V(e)){const r=Sc(n);r&&s.push(...Ac(r,t))}return s},Nc=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...bc(r,w(t,n)))}return s},Pc=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:$(e.getExpression(),["flags"]),wc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Ic=(e,t)=>{if(!Pc(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const r=s.getLiteralValue(),o=wc(n);if(!(r.length===0||o===void 0))return{defaultValue:o,scope:h(e),file:t,key:r,line:e.getStartLineNumber()}},Cc=(e,t)=>I(e,t,Ic),Tc=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const r=n.getTypeAtLocation(e),o=r.getText(e);if(!o||o==="any"||o==="never"||Gr(o))return;const a=e.getSourceFile().getFilePath();if(Yr(r,e,a)){const c=Qr(r,e,a,0,new Set);return c===void 0&&Xr(o),c}return o},Oc=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Rc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},kc=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of r.getDescendantsOfKind(d.CallExpression))Oc(a)&&s.push({file:o,indexName:Rc(a),line:a.getStartLineNumber()})}return s},ge=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,gn=e=>{const t=e.getArguments()[0],s=ge(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=D(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?ge(n.getInitializer()):void 0},Fc=new Set(["delete","get","head","options","patch","post","put"]),Dc=new Set(["handler","stream"]),Lc=new Set(["runAction","runMutation"]),Mc=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),pe=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,pn=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(he(s)===t){const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0}}},fs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:pn(s,"ctx")},gs=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:pn(s,"request")},ps=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const r of n){const o=r.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Lc.has(a)&&pe(c,t))return a;if(Mc.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&pe(c.getExpression(),t))return`db.${a}`}},ms=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&pe(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const r=n.getNameNode();if(!(!i.isObjectBindingPattern(r)||!pe(n.getInitializer(),t))){for(const o of r.getElements())if(he(o)==="auth")return!0}}return!1},_c=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Kc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&pe(n.getExpression(),t)},zc=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],mn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:zc(s)},Bc=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const r=n.getParent();if(!i.isCallExpression(r))return[];const o=r.getExpression();if(!i.isPropertyAccessExpression(o))return[];const a=o.getExpression();return i.isIdentifier(a)?mn(t,a.getText()):[]}return[]},$c=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=mn(s,t.getText());return n.length>0?n:Bc(t,s)},hs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(r=>Kc(r,t)&&$c(r).some(o=>_c.test(o)))},Uc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Dc.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const r=n.getName();if(Fc.has(r)){const o=n.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?r.toUpperCase():void 0}s=n.getExpression()}},Vc=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=ge(e.getArguments()[0]),l=c&&fs(c,!0);if(!c||l===void 0||hs(c,gs(c,!0)))return;const u=ps(c,l);return u===void 0?void 0:{scope:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ms(c,l),sideEffect:u}}const n=Uc(e);if(n===void 0)return;const r=ge(e.getArguments()[0]),o=r&&fs(r,!1);if(!r||o===void 0||hs(r,gs(r,!1)))return;const a=ps(r,o);return a===void 0?void 0:{scope:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:ms(r,o),sideEffect:a}},jc=(e,t)=>I(e,t,Vc),qc=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Wc=new Set(["append","set"]),hn=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",vs=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>qc.has(A(n.getExpression())??"")&&Ie(n,t)),Hc=(e,t)=>{if(vs(e,t))return!0;const s=Q(e);return s!==void 0&&vs(s,t)},gt=(e,t)=>Jo(e,t)&&!Hc(e,t),Gc=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=Q(e);return t!==void 0&&i.isNewExpression(t)&&A(t.getExpression())==="Headers"},ke=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=Q(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},wt=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const r=n.getInitializer();r!==void 0&>(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:hn(n.getNameNode()),line:r.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const r=n.getNameNode();gt(r,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:y(n),line:r.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const r=ke(n.getExpression());r!==void 0&&wt(r,t,s)}},vn=(e,t)=>{const s=ke(e);if(s===void 0)return;const n=D(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const r=ke(n.getInitializer());r!==void 0&&wt(r,"response-init",t)},Yc=(e,t)=>{const s=A(e.getExpression());if(s==="Response")vn(e.getArguments()[1],t);else if(s==="Headers"){const n=ke(e.getArguments()[0]);n!==void 0&&wt(n,"headers-ctor",t)}},Qc=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),r=s.getExpression();if(n==="json"&&i.isIdentifier(r)&&r.getText()==="Response"){vn(e.getArguments()[1],t);return}if(Wc.has(n)&&Gc(r)){const o=e.getArguments()[1];o!==void 0&>(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:hn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Xc=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Yc(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Qc(s,t)},Jc=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=ge(e.getArguments()[0]);if(n===void 0)return[];const r=n.getParameters()[1];if(r===void 0)return[];const o=r.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return Xc(n,{scope:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},Zc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...Jc(n,t));return s},el=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Zc(r,w(t,n)))}return s},tl=new Set(["auth","context.auth"]),sl="userId",nl=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(y(s))}return t},rl=(e,t)=>{const s=S(t,rn);if(!O(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){if(A(r.getExpression())!=="defineIdentity")continue;const[o]=r.getArguments();return o&&i.isObjectLiteralExpression(o)?nl(o):void 0}},Es=e=>{if(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return tl.has(t.getText())||$(t,["auth"])?e:void 0},il=e=>{if(i.isPropertyAccessExpression(e)&&Es(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Es(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},xs=(e,t,s)=>{const n=il(e);return n===void 0?void 0:{declared:n===sl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:h(e)}},ol=(e,t)=>{const s=rl(e,t);return s===void 0?[]:[...ct(e,t,d.PropertyAccessExpression,(n,r)=>xs(n,r,s)),...ct(e,t,d.ElementAccessExpression,(n,r)=>xs(n,r,s))]},al=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=P(s,"key");if(!(!n||!U(n)||ee(n)))return{scope:h(e),file:t,line:e.getStartLineNumber()}},cl=(e,t)=>I(e,t,al),ll=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=ir(t.getNameNode());return s===void 0||s==="namespace"}),dl=(e,t)=>{for(const{filePath:s}of Be(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const r of n.getDescendantsOfKind(d.CallExpression)){const o=r.getExpression(),[a]=r.getArguments();if(!(!i.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!i.isObjectLiteralExpression(a)||ll(a)))return r}}},ul="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",fl=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw me(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 (${ul}). 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})},gl=new Set(["delete","get","getRaw","getWithMetadata","put"]),pl=(e,t,s=[])=>{const n=je(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:gl});return yt(n,s)},ml=new Set(["queue","send"]),Ss=new Set(["bcc","cc","to"]),hl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ml.has(t))return;const s=e.getExpression();return $(s,["mail"])||$(s,["email"])?t:void 0},vl=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ss.has(y(t))&&U(n)&&!ee(n)}if(!i.isPropertyAssignment(t)||!Ss.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&U(s)&&!ee(s)}):!1,El=(e,t)=>{const s=hl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!vl(n)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s}},xl=(e,t)=>I(e,t,El),Sl=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,yl=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?Sl(e):!0,En=(e,t=!1)=>{for(const s of e.getProperties()){if(yl(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||En(n,!0))return!0}return!1},Al=(e,t)=>{for(const s of E(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:r}of sn(n))for(const o of bt(r)){const a=o.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||En(a)))return!0}}return!1},bl=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const r=Re(n);if(r===void 0||!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!i.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Re(a);c!==void 0&&s.push({column:c,strategy:tn(a),table:r})}}return s},Nl=(e,t)=>{const s=new Map;for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of sn(r))for(const a of bt(o))for(const c of bl(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Pl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){const a=Re(o);if(a===void 0||!i.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Re(l);if(u===void 0)continue;const p=tn(l);p!=="custom"&&r.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:p,table:a})}}return r},wl=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?W(s):void 0;return n?.receiver?bt(n.receiver).flatMap(r=>Pl(r,K(e)??e.getName(),t)):[]},Il=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...wl(a,o))}return s},Cl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},Tl=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=D(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},Ol=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ai(s.getExpression())?s:void 0},Rl=e=>{const t=Ol(e),s=t===void 0?void 0:Tl(t);if(s===void 0)return[];const n=e.getNameNode(),r=i.isIdentifier(n)?K(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Cl(o)).map(o=>({exportName:r,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},kl=e=>e.getVariableDeclarations().flatMap(t=>Rl(t)),Fl=(e,t)=>{const s=S(t,oi);if(!O(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return kl(n)},Dl=new Set(["delete","get","patch"]),Ll=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Ml=new Set(["auth","identity","session","user"]),_l=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Kl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},zl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},Bl=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),$l=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Ul=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Bl(s.getExpression(),t)&&$l(s.getThenStatement())),Vl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const r=n.getName();if(!Dl.has(r))continue;const o=n.getExpression();if(!(_(o)||i.isPropertyAccessExpression(o)&&_(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return r}},jl=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Js(At(s))!==void 0)),ql=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>_l.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Wl=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Ll.has(t.getText()))return!0;return[...Ml].some(t=>Ue(e,t).length>0)?!0:jl(e)||ql(e)},Hl=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=W(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const r=gn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&Gs(n.receiver,"use","rls"),a=Wl(r),c=new Set,l=[];for(const u of r.getDescendantsOfKind(d.CallExpression)){const p=Kl(u);if(p===void 0)continue;const f=zl(u);if(f===void 0||c.has(f)||!Ul(r,f))continue;const m=Vl(r,f);m!==void 0&&(c.add(f),l.push({exportName:K(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:m,table:p,usesRls:o,visibility:n.visibility}))}return l},Gl=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Hl(a,o))}return s},xn=(e,t)=>{const s=i.isIdentifier(e)&&t!==void 0?R(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?i.isIdentifier(t.getNameNode()):i.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},Yl=e=>{const t=b(e),s=t.getParent();return(i.isPropertyAccessExpression(s)||i.isElementAccessExpression(s))&&s.getExpression()===t&&!$e(s)},Ql=e=>{const t=b(e).getParent();return i.isVariableDeclaration(t)&&i.isObjectBindingPattern(t.getNameNode())},Xl=e=>{const s=b(e).getParent();if(i.isSpreadAssignment(s)||i.isSpreadElement(s)){const n=s.getParent();return(i.isObjectLiteralExpression(n)||i.isArrayLiteralExpression(n))&&!$e(n)}return i.isTemplateSpan(s)&&!i.isTaggedTemplateExpression(s.getParent().getParent())},Fe=e=>{const t=R(e);return t===void 0||xr(t.getSourceFile())},pt=(e,t)=>{const s=b(e),n=s.getParent();if(!i.isCallExpression(n))return!1;const r=n.getArguments().indexOf(s),o=v(n.getExpression());if(r===-1||o===void 0)return!1;if(i.isIdentifier(o))return o.getText()==="structuredClone"&&Fe(o);if(xn(At(o),t))return!(i.isPropertyAccessExpression(o)&&Zs.has(o.getName()))||i.isExpressionStatement(b(i.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!i.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!i.isIdentifier(a)||!Fe(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&r>0;default:return!1}},Ce={kind:"opaque"},Jl={kind:"unreached"},Zl=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>i.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>i.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&i.isFunctionDeclaration(n)?n:void 0},mt=e=>{const t=v(e);if(i.isArrowFunction(t)||i.isFunctionExpression(t))return t;const s=i.isIdentifier(t)?R(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(i.isFunctionDeclaration(s)){const r=Zl(s);return r===void 0||St(r)?void 0:r}const n=Z(s)?v(s.getInitializer()):void 0;return i.isArrowFunction(n)||i.isFunctionExpression(n)?n:void 0},Sn=(e,t,s)=>{const n=t.getArguments(),r=n.indexOf(s),o=r===-1||n.slice(0,r+1).some(l=>i.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[r];return o?Ce:c===void 0?a.some(l=>l.isRestParameter())?Ce:Jl:c.isRestParameter()?Ce:{kind:"parameter",parameter:c}},ed=e=>{const t=b(e),s=t.getParent();if(!i.isCallExpression(s)||s.getExpression()===t)return;const n=mt(s.getExpression());return n===void 0?Ce:Sn(n,s,t)},td=new Set(["__defineGetter__","__defineSetter__","__proto__"]),sd=e=>i.isForInStatement(e)?e.getExpression():i.isConditionalExpression(e)?e.getCondition():i.isElementAccessExpression(e)?e.getArgumentExpression():void 0,yn=e=>{const t=b(e),s=t.getParent();if(i.isIfStatement(s)||i.isWhileStatement(s)||i.isDoStatement(s)||i.isSwitchStatement(s)||i.isCaseClause(s)||i.isTypeOfExpression(s)||i.isVoidExpression(s)||i.isComputedPropertyName(s))return!0;if(i.isTemplateSpan(s))return!i.isTaggedTemplateExpression(s.getParent().getParent());const n=sd(s);if(n!==void 0)return fe(n,t);if(i.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!i.isBinaryExpression(s))return!1;const r=s.getOperatorToken().getKind(),o=r>=d.FirstAssignment&&r<=d.LastAssignment,a=r===d.QuestionQuestionToken||r===d.BarBarToken||r===d.AmpersandAmpersandToken;return!o&&!a},nd=4,An=(e,t,s=0)=>{if(Er(e))return!0;if(Yl(e)){const r=b(e).getParent(),o=i.isElementAccessExpression(r)?r.getArgumentExpression():void 0,a=i.isStringLiteral(o)?o.getLiteralValue():void 0,c=i.isPropertyAccessExpression(r)?r.getName():a;return c===void 0||!td.has(c)}if(Ql(e)||Xl(e)||yn(e)||pt(e,t))return!0;const n=ed(e);return n?.kind==="unreached"||n?.kind==="parameter"&&rd(n.parameter,s+1)},ys=new WeakMap,rd=(e,t=0)=>{const s=e.getNameNode();if(!i.isIdentifier(s))return!0;const n=ys.get(e.compilerNode);if(n!==void 0)return n;if(t>nd)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||R(a)?.compilerNode!==e.compilerNode||An(a,void 0,t));return(o||t===0)&&ys.set(e.compilerNode,o),o},As=new WeakMap,id=(e,t)=>{const s=i.isFunctionExpression(e)?e.getNameNode():void 0;if(!i.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(r=>{if(r===s||!n.has(r.getText()))return!1;const o=R(r)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},od=(e,t,s)=>{const{context:n,impl:r}=e,o=As.get(r.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=i.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(f=>{const m=f.getNameNode();return i.isIdentifier(m)?[m]:[]}),l=new Map(c.map(f=>[f.getText(),f.getParentOrThrow().compilerNode])),u=f=>i.isIdentifier(a)?An(f,n):!$e(f),p=!id(r,s)&&c.every(f=>(f.getSymbol()?.getDeclarations().length??0)===1)&&r.getDescendantsOfKind(d.Identifier).every(f=>{const m=f.getText();if(m==="arguments")return!1;const x=l.get(m);return x===void 0||c.includes(f)||R(f)?.compilerNode!==x?!0:u(f)});return As.set(r.compilerNode,p),p},bs=new WeakMap,ad=e=>{let t=bs.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=ci(s);return n===void 0?[]:[[n.compilerNode,s]]})),bs.set(e.compilerNode,t)),t},cd=e=>{const t=ad(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[r,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:r,impl:s,mutatorName:K(n)??n.getName()};return a!==void 0&&od(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},ld=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),dd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),ht=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),bn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>i.isIdentifier(t.getNameNode())),ud=e=>{const t=b(e),s=t.getParent();if(i.isVariableDeclaration(s))return fe(s.getInitializer(),t)?s:void 0;const n=i.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return i.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},fd=e=>{const t=ud(e);return t===void 0?void 0:i.isIdentifier(t.getNameNode())?i.isForOfStatement(t.getParent().getParent())||Z(t)?[t]:void 0:bn(t)},de=e=>e.isUnion()?e.getUnionTypes().every(t=>de(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>de(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),De=(e,t,s)=>{const n=i.isCallExpression(e)?v(e.getExpression()):void 0;return i.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Te=e=>{const t=v(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=t.getBody();return i.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(r=>i.isFunctionLikeDeclaration(r))===t).map(n=>n.getExpression()):[s]},gd=e=>{const t=i.isCallExpression(e)?v(e.getExpression()):void 0,s=i.isPropertyAccessExpression(t)?t.getExpression():void 0;return i.isPropertyAccessExpression(t)&&i.isIdentifier(s)&&dd.get(s.getText())?.has(t.getName())===!0&&Fe(s)},pd=e=>{const t=lt(e);if(!i.isArrowFunction(t)&&!i.isFunctionExpression(t))return;const s=b(t),n=s.getParent();return i.isCallExpression(n)&&n.getArguments().includes(s)&&De(n,en)?n:void 0},md=(e,t)=>{if(!(i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=b(e),n=s.getParent();return!i.isCallExpression(n)||n.getExpression()!==s?e:De(n,ld,t)?n:void 0},hd=(e,t)=>{if(i.isAwaitExpression(e))return e;if(i.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=i.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},vd=(e,t)=>{if(i.isArrayLiteralExpression(e))return e;const n=i.isSpreadElement(e)||i.isSpreadAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isPropertyAssignment(e)&&fe(e.getInitializer(),t)?e.getParent():void 0;return i.isArrayLiteralExpression(n)||i.isObjectLiteralExpression(n)?n:void 0},Ns=e=>{const t=b(e),s=t.getParent();if(s===void 0)return;const n=i.isCallExpression(s)&&s.getArguments().includes(t)&&gd(s);return md(s,t)??hd(s,t)??vd(s,t)??(n?s:pd(t))},Ed=5e4,Nn=()=>({inProgress:new Set,verdicts:new Map});class xd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Ed&&this.cut()}memoized(t,s,n){const r=n.verdicts.get(t);if(r!==void 0)return r;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Sd=8,yd=8;class Ad{budget;scope;taint;verdicts=Nn();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!de(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],r=new Set,o=(c,l)=>{r.has(c.compilerNode)||(r.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of r)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,r){const o=t.getNameNode();if(!i.isIdentifier(o)){for(const l of i.isParameterDeclaration(t)?bn(t):[])r(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Sd?this.budget.cut():(r(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(b(l),!0,a,0))&&(t===n||!de(t.getType()))}valueCompromises(t,s,n,r){let o=t;for(let m=Ns(o);m!==void 0;m=Ns(o)){if(i.isCallExpression(m)&&this.callbackCompromises(m,n))return!0;o=b(m)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&de(o.getType());if($e(o))return!c&&(!i.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=fd(o);if(u!==void 0)return u.some(m=>n(m,!0));const p=i.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(i.isCallExpression(p)&&p.getExpression()===a)return this.methodCallCompromises(p,n);const f=this.nestedReturningFunctionOf(o);return f!==void 0?this.resultCompromises(f,n,r)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const r=b(t).getParent();if(n>=yd)return this.budget.cut();if(i.isCallExpression(r))return r.getExpression()===b(t)?this.valueCompromises(r,!1,s,n+1):!De(r,ht);const o=i.isFunctionDeclaration(t)?t:r,a=i.isFunctionDeclaration(o)||Z(o)?o.getNameNode():void 0;return o===void 0||!i.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=b(c),u=l.getParent();return!i.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(r=>Te(r)===void 0).some(r=>this.taint.isTaintedValue(r,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=De(t,ht)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const r=mt(n);return r!==void 0&&this.taint.isInImpl(r)?r.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(i.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const r=i.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&i.isCallExpression(r))return!pt(n,this.scope.context)&&this.isOpaqueCallTainted(r.getExpression(),r.getArguments(),n);if(i.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(i.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return i.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(pt(s,this.scope.context))return!1;const r=mt(t.getExpression()),o=r===void 0?void 0:Sn(r,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&r!==void 0&&this.taint.isInImpl(r)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||i.isExpressionStatement(s)||i.isForStatement(s)||i.isElementAccessExpression(s)||yn(t)||fe(lt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const r=!i.isIdentifier(v(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||r)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=lt(t);return fe(s,this.scope.impl)?void 0:s}}const bd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Nd=e=>{const t=v(e);if(!i.isIdentifier(t))return i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t);const s=R(t),n=i.isVariableDeclaration(s)?v(s.getInitializer()):void 0;return s===void 0||i.isFunctionDeclaration(s)||i.isParameterDeclaration(s)||i.isArrowFunction(n)||i.isFunctionExpression(n)},Pd=new Set(["all","allSettled","any","race"]),Ps=e=>i.isParameterDeclaration(e)?e:i.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,rt=8;class wd{budget=new xd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Nn();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Ad(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,rt)?!1:(i.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(r=>Sr(r)&&this.isIdentifierTainted(r))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const r of this.referencesByName.get(s)??[]){const o=R(r)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],r])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(r=>r.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(f=>f.getInitializer())].some(f=>f!==void 0&&this.isTaintedValue(f,!1)))return!0;const n=t.getParentOrThrow(),r=i.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(f=>f.compilerNode===t.compilerNode):-1,o=b(n),a=o.getParent();if(r===-1)return!0;if(i.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,r,t.isRestParameter());const f=v(a.getExpression());if(!i.isPropertyAccessExpression(f)||!ht.has(f.getName()))return!0;const m=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(f.getExpression(),!0)||m.some(x=>this.isTaintedValue(x,!1))}const c=i.isVariableDeclaration(a)&&Z(a)?a:void 0,l=i.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!i.isIdentifier(u))return!0;const p=this.referencesTo(l,u.getText());return p.length===0||p.some(f=>{const m=b(f),x=m.getParent();return!i.isCallExpression(x)||x.getExpression()!==m||this.isCallSiteTainted(x,r,t.isRestParameter())})}isCallSiteTainted(t,s,n){const r=t.getArguments(),o=r.findIndex(c=>i.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return r.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=v(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getExpression():void 0,a=i.isPropertyAccessExpression(n)&&i.isIdentifier(r)&&r.getText()==="Promise"&&Fe(r)&&Pd.has(n.getName())?v(t.getArguments()[0]):void 0;if(i.isArrayLiteralExpression(a)){const p=a.getElements();return p.length>0&&p.every(f=>!i.isSpreadElement(f)&&this.isRootedInContext(f,s))}const c=i.isCallExpression(a)?v(a.getExpression()):void 0,l=i.isCallExpression(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="map"?v(a.getArguments()[0]):void 0,u=l===void 0?void 0:Te(l);return u!==void 0&&u.length>0&&u.every(p=>p!==void 0&&this.isRootedInContext(p,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=R(t),r=Ps(n);if(r!==void 0)return this.isSource(r);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(i.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(i.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=i.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return i.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=v(t.getExpression()),r=i.isPropertyAccessExpression(n)?n.getName():void 0;return r!==void 0&&Zs.has(r)?!1:r!==void 0&&en.has(r)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Te(a)!==void 0)&&(r===void 0||!bd.has(r))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(r,o=[])=>{const a=At(r),c=i.isIdentifier(a)?Ps(R(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(r,s)||!this.isTaintedValue(r,!1)};return t.getArguments().every(r=>{const o=Te(r);if(o===void 0)return!Nd(r)&&n(r);const a=v(r),c=i.isArrowFunction(a)||i.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Ir(t,u=>this.callChainVerdict(u,s)),r=n.root;if(n.verdict!==void 0)return n.verdict;if(xn(r,this.scope.context))return!0;const o=i.isIdentifier(r)?R(r):void 0,a=i.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=Z(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=i.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(i.isBindingElement(l)||i.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(i.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(i.isForOfStatement(s)||i.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),r=St(t);if(n===void 0||r)return!0;if(this.isRootedInContext(n,rt))return!1;if(this.variableDepth>=rt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const ws=new WeakMap,Id=e=>{const t=ws.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new wd(e);return ws.set(e.impl.compilerNode,s),s},Cd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Td=new Set(["insert","insertManyUnsafe","patch","replace"]),Od=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();return Td.has(t)&&Vr(e.getExpression())?t:void 0},Rd=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},kd=(e,t)=>{const s=Cr(e);return s?.member===t?v(s.object):void 0},Is=(e,t)=>i.isIdentifier(e)&&R(e)?.compilerNode===t.compilerNode,Pn=(e,t,s,n=1)=>{const r=kd(e,s);if(r!==void 0)return Is(r,t);const o=i.isIdentifier(e)?R(e):void 0;if(i.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&he(o)===s&&i.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||Z(l)&&Is(v(l.getInitializer()),t))}const a=Z(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Pn(a,t,s,n-1)},vt=e=>{const t=v(e)??e;return i.isConditionalExpression(t)?[...vt(t.getWhenTrue()),...vt(t.getWhenFalse())]:[t]},Fd=(e,t,s)=>{const n=[],r=s===void 0?void 0:Id(s);for(const o of e.getProperties()){let a,c;if(i.isPropertyAssignment(o)?(a=y(o),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=y(o),c=o.getNameNode()),a===void 0||c===void 0||!Cd.has(a))continue;if(vt(c).some(u=>r===void 0?U(u)&&!jr(u):r.isTaintedValue(u,!0))){const u=t.ownerField===a&&s?.pristine===!0&&Pn(c,s.parameter,a);n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...u&&{ownerScoped:!0}})}}return n},Dd=(e,t,s)=>{const n=Od(e.getExpression()),r=n===void 0?void 0:e.getArguments()[1];if(n===void 0||r===void 0)return[];const o=Rd(r,n);if(o.length===0)return[];const a=h(e),c=cd(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Fd(u,l,c))},Ld=(e,t,s=[],n=[])=>{const r=new Map(n.map(a=>[`${a.filePath}:${a.exportName}`,a.owner])),o=I(e,t,(a,c)=>Dd(a,c,l=>r.get(`${c}:${l}`)));return yt(o,s)},Md=["providerSubscriptionId","state"],_d=["providerEventId","processedAt"],Cs=(e,t)=>t.every(s=>s in e.shape),Kd=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&Cs(t,Md)&&Cs(s,_d)},zd=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Bd=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,$d=e=>{const t=D(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Bd(t.getInitializer()):void 0},Ud=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!zd.has(s))return;const[n]=e.getArguments(),r=n&&i.isObjectLiteralExpression(n)?$d(n):void 0;return{callee:s,scope:h(e),file:t,line:e.getStartLineNumber(),...r===void 0?{}:{toleranceSeconds:r}}},Vd=(e,t)=>I(e,t,Ud),jd=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),qd=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Wd=(e,t)=>{const s=e.getArguments()[t];if(!s||!i.isObjectLiteralExpression(s))return;const n=D(s,"handler");if(n===void 0||!i.isPropertyAssignment(n))return;const r=n.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},wn=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},In=(e,t)=>e===t||e.startsWith(`${t}.`),Cn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Ts=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},Tn=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Ts(s));return i.isIdentifier(e)&&Ts(e)&&t.push(e),t},Hd=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Gd=e=>{const t=wn(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const r=n.getInitializer(),o=i.isVariableDeclarationList(r)?r.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Yd=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Gd(e),r=new Set,o=a=>Cn(a).some(c=>n.some(l=>In(c.getText(),l)))?!0:Tn(a).some(c=>r.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Hd(a))r.add(l)}return{names:r,prefixes:n}},Qd=(e,t)=>Cn(e).some(s=>t.prefixes.some(n=>In(s.getText(),n)))?!0:Tn(e).some(s=>t.names.has(s.getText())),Xd=e=>{const t=qs(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Jd=(e,t,s)=>{const n=wn(e,0);if(n===void 0)return[];const r=Yd(e,t,n),o=new Set([n,...r.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!i.isPropertyAccessExpression(l)||!js.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Qd(u,r))continue;const p=Xd(c.getArguments()[0]);p!==void 0&&a.push({dispatchKind:t,file:s,scope:h(c),line:c.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return a},Zd=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=qd(n),o=r===void 0?void 0:jd.get(r);if(o===void 0)continue;const a=Wd(n,o);a!==void 0&&s.push(...Jd(a,r==="defineWorkflow"?"workflow":"queue",t))}return s},eu=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Zd(r,w(t,n)))}return s},Os={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Rs=new Set(["account","credential","member","passkey","session","user"]),tu=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),su=e=>{const s=tu(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Rs.has(s)||Rs.has(n)},nu=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ru=(e,t)=>{const{objects:s,opaque:n}=Pt(e,t);return Ea(s).some(r=>nu(r))?!0:n?void 0:!1},iu=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!D(t,"captcha"),usesRateLimit:!!D(t,"rateLimit")}},ou=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},Oe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},au=e=>{const t=ou(e),s=t?A(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=iu(t);return{...Oe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Os?{...Oe,[Os[s]]:!0}:Oe},cu=e=>{const t={...Oe};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const r=n.getName()==="use"?s.getArguments()[0]:void 0;if(r){const o=au(r);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},lu=new Set(["insert","insertMany","insertManyUnsafe","replace"]),du=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!lu.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const r=e.getArguments()[0];return!r||!(i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r))?!1:su(r.getLiteralText())},uu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),ks=new Set(["queues","scheduler","topics","workflows"]),fu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!uu.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&ks.has(s.getName())&&qr(s.getExpression()))return!0;s=s.getExpression()}const n=Js(s);return n?.length===1&&ks.has(n[0]??"")},gu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},On=new Set(["generateObject","generateText","streamObject","streamText"]),pu=e=>{const t=A(e.getExpression());return t!==void 0&&On.has(t)},mu=e=>{const t=A(e.getExpression());if(t===void 0||!On.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!D(s,"maxOutputTokens")},hu=new Set(["log","span","trace"]),vu=new Set(["ai"]),Eu=new Set(["email","mail"]),xu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),it=(e,t)=>[...t].some(s=>Ue(e,s).length>0),Su=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),yu=new Set(["every","filter","flatMap","forEach","map","some"]),Au=new Set(["all","allSettled","race"]),bu=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(yu.has(n))return t;const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="Promise"&&Au.has(n))return t},Nu=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Su.has(t.getKind())){const s=bu(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Pu=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},wu=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Iu=e=>{let t=!1,s=!0;for(const n of[...xu].flatMap(r=>Ue(e,r))){const r=wu(n);r&&(t=!0,!Nu(r)&&!Pu(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Cu=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Fs="lunora-advisor-exempt",Tu=/^[\s*/]+/u,Ou=/[\w-]/u,Ru=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
7
|
-
`);for(const n of s.split(`
|
|
8
|
-
`)){const r=n.replace(Tu,"");if(!r.startsWith(Fs))continue;const o=r.slice(Fs.length);if(Ou.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:""}},ku=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=D(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Fu=(e,t)=>{const s=ku(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),r=s.getText(),o=n.getVariableDeclaration(r)?.getInitializer();return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:n.getFunction(r)},Du=e=>{let t=!1,s=!1,n=!1,r=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(du(l)&&(o=!0),fu(l)&&(t=!0),gu(l)&&(r=!0),pu(l)&&(s=!0),mu(l)&&(n=!0),o&&t&&r&&n)break;const{handlesErrors:a,reachesOutbound:c}=Iu(e);return{callsMail:it(e,Eu),emitsEvent:it(e,hu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||it(e,vu),throwsBareError:Cu(e),unboundedAiGeneration:n,usesInsertManyUnsafe:r,writesUserTable:o}},Lu=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=W(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const r=n.receiver?cu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Fu(e,s);return{...o?Du(o):{},...Ru(e),...r,analyzableBody:o!==void 0,exportName:K(e)??e.getName(),file:t,hasEmailArg:ru(s,n.receiver),kind:n.kind,visibility:n.visibility}},Mu=(e,t)=>{const s=[];for(const n of V(e)){const r=Lu(n,t);r&&s.push(r)}return s},_u=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Mu(r,w(t,n)))}return s},Ku=new Set(["dbRateLimit","rateLimit"]),zu=e=>i.isArrowFunction(e)?e.getBody():e,Bu=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},Rn=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},kn=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const r=n.getParent();return!(i.isPropertyAccessExpression(r)&&r.getNameNode()===n)})},$u=(e,t)=>U(e)||t!==void 0&&kn(e,t).some(s=>Rn(s)),Uu=(e,t)=>t===void 0?ee(e):kn(e,t).some(s=>!Rn(s)),Vu=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Ku.has(s))return;const n=P(Hs(e.getArguments()[2]),"key");if(!n)return;const r=zu(n),o=Bu(n);if(!(!$u(r,o)||Uu(r,o)))return{callee:s,scope:h(e),file:t,limitName:Ws(e),line:e.getStartLineNumber()}},ju=(e,t)=>I(e,t,Vu),qu=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Wu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!qu.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},Hu=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Gu=e=>{let t=v(e)??e;for(;i.isAwaitExpression(t);)t=v(t.getExpression())??t.getExpression();return t},Fn=(e,t=!1)=>{const s=Gu(e);if(i.isIdentifier(s)){if(t)return;const n=Q(s);return n===void 0?void 0:Fn(n,!0)}if(i.isCallExpression(s))return Wu(s)??Hu(s)},Yu=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const r=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=n.getExpression();r===e&&o!==void 0&&s.push(o)}return s},Qu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=W(s);if(n?.kind!=="query")return[];const r=gn(s);if(r===void 0)return[];const o=n.receiver!==void 0&&Dr(n.receiver,"output"),a=n.receiver!==void 0&&Gs(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Yu(r)){const p=Fn(u);p===void 0||c.has(p)||(c.add(p),l.push({exportName:K(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:p,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Xu=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Qu(a,o))}return s},Ju=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(y(s));return t},Zu=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?W(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=nn(o);if(a===void 0)continue;const c=Ju(P(a.options,"with"));c.length!==0&&r.push({exportName:K(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return r},ef=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...Zu(a,o))}return s},Le=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Le(e.getLeft()),s=Le(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},tf=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Le(t)!==void 0},sf=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return y(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},nf=(e,t,s)=>Si(e)?!Tr(s)&&yi(sf(t)):!0,rf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],r=new Set;for(const o of n){if(tf(o))continue;const a=Le(o);if(a===void 0)continue;const c=Ei(a);if(c===void 0||!nf(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;r.has(u)||(r.add(u),s.push({file:t,kind:c,line:l,preview:xi(a)}))}return s},of=(e,t)=>{const s=[];for(const n of E(t,{includeSkipped:!0})){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...rf(r,w(t,n)))}return s},af=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?W(s):void 0;if(!n)return[];const r=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=nn(o);if(a===void 0)continue;const c=P(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),u=!l&&U(c);!l&&!u||r.push({exportName:K(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return r},cf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=w(t,n);for(const a of V(r))s.push(...af(a,o))}return s},lf=new Set(["query","unsafe"]),df=e=>!i.isPropertyAccessExpression(e)||!lf.has(e.getName())?!1:$(e.getExpression(),["sql"]),uf=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),ff=(e,t)=>{if(!df(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!uf(s)))return{file:t,line:s.getStartLineNumber(),scope:h(e)}},gf=(e,t)=>I(e,t,ff),pf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],mf=e=>{for(const[t,s]of pf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},hf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of r.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=mf(a);c!==void 0&&s.push({file:w(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},vf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ef=(e,t,s=[])=>{const n=je(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:vf,requireUnmodifiedReach:!0});return yt(n,s)},xf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Sf=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,yf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){n=!0;continue}if(i.isPropertyAssignment(r)){const o=y(r);t.push(o),o==="expiresInSeconds"&&(s=Sf(r.getInitializer()));continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r))&&t.push(y(r))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Af=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=xf.get(t);return s===void 0?void 0:Xs(e.getExpression(),r=>r==="ctx.storage"||r.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},bf=(e,t)=>{const s=Af(e.getExpression());if(s!==void 0)return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...yf(e.getArguments()[s.optionsIndex])}},Nf=(e,t)=>I(e,t,bf),Pf=(e,t)=>{const s=Kr(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},wf=new Set(["delete","hardDelete","patch","replace","restore"]),If=new Set(["insertMany","insertManyUnsafe","patchWhere"]),Cf=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Ds=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],r=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return r.length===n.length?r:[]},Tf=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const r=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return r===void 0?[]:Ds(r,e)}return Ds(s,e)},Ls="",Of=(e,t)=>{if(If.has(e))return{method:e,tables:[t!==void 0&&i.isStringLiteral(t)?t.getLiteralText():Ls]};if(wf.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:Tf(t,e);return{method:e,tables:s.length===0?[Ls]:s}}},Rf=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(_(n))return Of(s,e.getArguments()[0]);if(Cf.has(s)&&i.isPropertyAccessExpression(n)&&_(n.getExpression()))return{method:s,tables:[n.getName()]}},kf=(e,t)=>I(e,t,(s,n)=>{const r=Rf(s);if(r===void 0)return;const o=h(s),a=s.getStartLineNumber();return r.tables.map(c=>({file:n,line:a,method:r.method,scope:o,table:c}))}),Ff=(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"}),Df=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||D(s,"args")===void 0)return!1}return Pt(e,t).opaque},Lf=(e,t)=>{const s=[],n=(r,o)=>{const a=r.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=W(a);c!==void 0&&Df(a,c.receiver)&&s.push(Ff(t,o,a.getStartLineNumber()))};for(const r of e.getVariableStatements().filter(o=>o.isExported()))for(const o of r.getDeclarations())n(o,o.getName());return s},Mf=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n);r!==void 0&&s.push(...Lf(r,w(t,n)))}return s.toSorted((n,r)=>n.cacheKey.localeCompare(r.cacheKey))},_f=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Me=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),Dn=e=>!e.isAny(),Ln=e=>{const t=e.getType();if(!Dn(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:_f.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Kf=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Mn={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."},zf=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.`}),Bf={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)."},$f=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),Uf={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)."},Vf=(e,t,s)=>{if(!t.some(r=>yr(r)))return Bf;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return $f.has(s.typeName)&&!n&&!t.some(r=>bi(r))?Uf:Mn},_n=(e,t,s,n,r)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,p=u===void 0?r:zf(u),f=c===void 0?p.remediation:`${c} ${p.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${p.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${f}`:f,title:"Procedure exists at runtime but is missing from the generated API"}},jf=(e,t,s)=>{const n=[];for(const r of V(e)){const o=i.isIdentifier(r.getNameNode())?at(r):[r.getName()],c=o.some(u=>Me(s,t,u))||!Kf(r)?void 0:Ln(r),[l=r.getName()]=o;c!==void 0&&n.push(_n(t,l,c,r.getStartLineNumber(),Vf(r,o,c)))}return n},qf=(e,t,s)=>{if(Me(s,t,"default"))return[];const n=[];for(const r of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!i.isIdentifier(o.getExpression()))){const o=Ln(r.getExpression());o!==void 0&&n.push(_n(t,"default",o,r.getStartLineNumber(),Mn))}return n},Wf=(e,t,s)=>[...jf(e,t,s),...qf(e,t,s)],Hf=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>i.isIdentifier(n.getNameNode())).filter(n=>at(n).some(r=>Me(s,t,r))).filter(n=>{const r=n.getInitializer();return r!==void 0&&i.isCallExpression(r)&&i.isPropertyAccessExpression(r.getExpression())}).map(n=>{const r=at(n).find(o=>Me(s,t,o))??n.getName();return{declaration:n,exportName:r,relativePath:t}}),Gf=({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"}),Yf=(e,t,s)=>{const n=[],r=[];for(const a of E(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=w(t,a);n.push(...Wf(c,l,s)),r.push(...Hf(c,l,s))}const[o]=r;return o!==void 0&&r.every(({declaration:a})=>!Dn(a.getType()))&&n.push(Gf(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Qf=new Set(["when","where"]),ot=new Set(["definePolicy","defineShape"]),Xf=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return ot.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const r=n.getNameNode().getText();return ot.has(r)?r:void 0}const s=t.getText();return ot.has(s)?s:void 0},Jf=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Kn=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Jf(e))return"empty-object";if(i.isParenthesizedExpression(e))return Kn(e.getExpression())}},It=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Zf=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>It(t)===e),zn=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>It(t)===e),eg=e=>{const t=Zf(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||zn(e).length>0},tg=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>It(t)===e),Et=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",sg=(e,t)=>Et(e)||Et(t),ng=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Ms=e=>!Et(e)&&(i.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),rg=(e,t,s)=>{const n=ng.get(e);if(n!==void 0)return sg(t,s)?n==="positive"?"negative":"positive":Ms(t)||Ms(s)?void 0:n},ue=e=>{if(i.isParenthesizedExpression(e))return ue(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=rg(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=ue(e.getLeft()),r=ue(e.getRight());return n===r?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},_s=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},ig=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},og=e=>i.isReturnStatement(e)?e.getExpression()??e:e,ag=e=>{const t=[];for(const s of zn(e)){const n=ue(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of tg(e)){const n=ue(s.getExpression());if(n==="indeterminate")continue;const r=n==="negative"?_s(s.getThenStatement()):_s(s.getElseStatement())??ig(s);r!==void 0&&t.push(og(r))}return t},cg=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},lg=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const r=[];for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)||!Qf.has(y(o)))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&eg(a))for(const c of ag(a)){const l=Kn(c);l!==void 0&&r.push({exportName:cg(e),file:s,form:l,key:y(o),line:c.getStartLineNumber(),owner:t})}}return r},dg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const r=Xf(n);r!==void 0&&s.push(...lg(n,r,t))}return s},ug=(e,t)=>{const s=[];for(const n of E(t)){const r=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...dg(r,w(t,n)))}return s},fg=new Set(["query","upsert","upsertNow"]),gg=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(fg.has(t))return $(e.getExpression(),["vectors"])?t:void 0},pg=(e,t)=>{const s=gg(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const r=P(n,"namespace");if(!(!r||!U(r)||ee(r)))return{scope:h(e),file:t,line:e.getStartLineNumber(),method:s}},mg=(e,t)=>I(e,t,pg),hg=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},vg=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Eg=(e,t)=>I(e,t,(s,n)=>hg(s)?{file:n,line:s.getStartLineNumber(),scope:h(s),workflow:vg(s)}:void 0),xg=".lunora-schema.json",xt=(e,t)=>{O(e)&&Xn(e,"utf8")===t||Jn(e,t,"utf8")},Sg=(e,t)=>{if(t===""){Zn(e,{force:!0});return}xt(e,t)},yg=e=>{try{const t=tr(S(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},Ag=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},bg=e=>{let t=O(e)?e:we(e);for(;t&&t!==we(t);){const s=S(t,"tsconfig.json");if(O(s))return s;t=we(t)}},Ks=e=>e.replaceAll("\\","/"),Ng=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new Y("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const r=t.columns.length>0;for(const o of e){if(o.table===void 0){if(r)throw new Y("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 Y("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})}},_e=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},zs=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Pg=8,wg=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:r,migrations:o,project:a,shapes:c,usesSandbox:l,useUmbrella:u,workflows:p}=e,f=()=>Zr(()=>{const N=ei(a,r),k=li(a,r);return{functions:N,httpRoutes:ti(a,r),mutators:k}});let{erased:m,value:{functions:x,httpRoutes:z,mutators:j}}=f();ss([...x,...j].map(N=>N.filePath)),ss(z.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const k=ki({agents:t,functions:x,httpRoutes:z,mutators:j,useUmbrella:u,workflows:p}),q=ji({agents:t,functions:x,migrations:o,mutators:j,shapes:c,useUmbrella:u,usesSandbox:l});if(N>=Pg||zs(a,s,k)&&zs(a,n,q))return{apiContent:k,erased:m,functions:x,functionsContent:q,httpRoutes:z,mutators:j};_e(a,s,k),_e(a,n,q),{erased:m,value:{functions:x,httpRoutes:z,mutators:j}}=f()}},Ig=e=>{const t=bg(e);return t?new Jt({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Jt({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Up=(e,t)=>{const s=E(t),n=S(t,"schema.ts");O(n)&&s.push(n);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const r=new Set(s.map(c=>Ks(c))),o=Ks(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!r.has(l)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const l=c.getFilePath();if(!(l===o||l.startsWith(a)||l.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Vp=e=>{const t=Ag(),s=t?Ze.now():0,n=S(e.projectRoot,e.lunoraDirectory??"lunora"),r=S(n,"schema.ts");if(!O(r))throw new Y("INTERNAL",`schema.ts not found at ${r}`);const o=e.project??Ig(n);Wr(Tc);const a=vi(o,r,e.projectRoot),{agents:c,capabilities:l,containers:u,crons:p,dataModelContent:f,dependencies:m,entryCronTriggers:x,env:z,featureUsage:j,hasFlags:N,hasNotify:k,identity:q,platformGate:H,queues:F,serverContent:te,services:oe,storageRulesMetadata:ae,topics:se,usesSandbox:ve,useUmbrella:B,workflows:L}=Ko({lunoraDirectory:n,project:o,projectRoot:e.projectRoot,schema:a,target:e.target});fl(a,a.jurisdiction===void 0?void 0:dl(o,n));const M=S(n,"_generated"),T=S(M,"dataModel.ts"),Bn=S(M,"server.ts"),$n=S(M,"api.ts"),Un=S(M,"functions.ts");_e(o,T,f),_e(o,Bn,te);const Ee=ii(o,n),ne=Ai(o,n),{apiContent:Ct,erased:Vn,functions:G,functionsContent:Tt,httpRoutes:qe,mutators:xe}=wg({agents:c,apiPath:$n,generatedFunctionsPath:Un,lunoraDirectory:n,migrations:Ee,project:o,shapes:ne,useUmbrella:B,usesSandbox:ve,workflows:L}),Ot=ar(o,n),We=cr(Ot,a,[...G,...qe].map(g=>g.filePath)),Se=Ot.length>0,X=e.lint===!1&&!Se?void 0:{inserts:ni(o,n),queries:gi(o,n),tableWrites:kf(o,n),workflowCalls:Eg(o,n)},ye=e.lint===!1||X===void 0?void 0:nr({adminRoutes:Wo(o,n),aiRawRuns:ta(o,n),aiToolSideEffects:fa(o,n),argumentDerivedFetches:ma(o,n),argumentValidators:Pa(o,n),authApiCalls:Hr(o,n),authConfigs:La(o,n),browserUrlAccesses:za(o,n),configCalls:Ja(o,n),containerKeyAccesses:ec(o,n),containerOverrides:oc(o,n),containers:u,exportSinks:dc(o,n),staleMigrationImports:hf(o,n),failOpenGuards:mc(o,n),flagReads:Nc(o,n),flagSecurityDefaults:Cc(o,n),geoIndexUsages:kc(o,n),httpActionGuards:jc(o,n),httpHeaderWrites:el(o,n),hyperdriveCalls:si(o,n),identityClaimReads:ol(o,n),imageDeliveryUrlAccesses:cl(o,n),inserts:X.inserts,kvKeyAccesses:pl(o,n,G),mailRecipientAccesses:xl(o,n),maskProcedures:ri(o,n),maskStrategies:Il(o,n),mutatorWrites:Fl(o,n),nondeterministicCalls:di(o,n),normalizeIdAuthorizations:Gl(o,n),notifyCalls:fi(o,n),notifyConfig:ui(o,n),mutators:xe,ownerFieldWrites:Ld(o,n,G,xe),unrestrictedWhereBranches:ug(o,n),paymentWebhooks:Vd(o,n),privilegedDispatches:eu(o,n),procedureProtections:_u(o,n),queries:X.queries,queues:F,r2sqlCalls:pi(o,n),ratelimitKeySelectors:ju(o,n),rawRowReturns:Xu(o,n),relationLoads:ef(o,n),rlsProcedures:mi(o,n),schema:a,secretLiterals:of(o,n),modules:We,shapes:ne,softDeleteReads:cf(o,n),sqlInterpolations:gf(o,n),storageKeyAccesses:Ef(o,n,G),storageUploads:Nf(o,n),tableWrites:X.tableWrites,vectorNamespaceAccesses:mg(o,n),workflowCalls:X.workflowCalls,workflows:L,wranglerVariables:e.wranglerVariables}),Rt=ye===void 0?[]:Wi(e.projectRoot,[...er(ye,{source:"static"}),...Yf(o,n,{byName:new Set([...L,...F,...c,...u].map(g=>g.exportName)),byPath:new Set([...G,...xe,...ne,...Ee].map(g=>`${g.filePath}:${g.exportName}`))}),...Mf(o,n),...Jr(Vn,n)]),jn=hi(o,n),kt=Nl(o,n);Ng(ne,kt,Al(o,n));const qn=N?xc(o,n):[],He=H.signals.vectorStore!==!1,ce=Pf(j,{containerCount:u.length,cronCount:p.length,dependencies:m,hasPaymentTables:Kd(a.tables),queueCount:F.length,storageColumnCount:Object.keys(Qs(a)).length,storageRuleCount:ae.rules.length,vectorIndexCount:a.vectorIndexes.length,target:Ys(e.projectRoot,e.target),vectorStoreSupported:He,workflowCount:L.length}),Ft=t?Ze.now():0,Ge=Ti(a,Ee.map(g=>g.id)),Dt=zr({advisories:Rt.filter(g=>g.name!=="procedure_type_check_unavailable"),advisorProcedures:ye?.procedureProtections??[],agents:c,capabilities:l,containers:u,env:z,flagKeys:qn,hasFlags:N,hasNotify:k,hasVectors:He,maskMetadata:kt,mutators:xe,queues:F,rlsMetadata:jn,schema:a,schemaSnapshot:Ge,shapes:ne,services:oe,storageRules:ae,studioFeatures:ce,topics:se,useUmbrella:B,workflows:L}),Lt=Oi(ne,m.has("@lunora/db"),B),Mt=Fi(u,a.jurisdiction),_t=Di(L),Kt=Li(c),zt=Mi(F),Bt=_i(p),Wn=Ki(ce.scheduler),Hn=zi(a.tables,B),Gn=or(e.projectRoot)?Bi(B):"",$t=$i(a.vectorIndexes),Ae=Vi(a,B),Ut=Ri(m.has("@lunora/seed")),be=e.apiSpec??"openapi",Ye=be==="openapi"||be==="both",Qe=be==="openrpc"||be==="both",Vt=Ni({capabilities:l,emailAgents:c.filter(g=>g.onEmail===!0).map(g=>({className:g.className,exportName:g.exportName})),hasAccess:m.has("@lunora/cloudflare-access"),hasAuth:m.has("@lunora/auth"),hasFramework:m.has("@lunora/astro")||m.has("@lunora/svelte")||m.has("@lunora/vue")||O(S(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(g=>Bs(g)),hasHyperdriveGlobal:a.tables.some(g=>$s(g)),hasKvIntrospector:ce.kv,hasNotify:k,hasQueue:F.some(g=>g.mode==="push"),hasScheduler:ce.scheduler,hasSourcedTables:a.tables.some(g=>g.externalSource!==void 0),hasStorage:ce.storage,hasVectors:He,hasWorkflow:L.length>0,identity:q,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(g=>({name:g.name,shardMode:g.shardMode})),useUmbrella:B,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(g=>g.voice===!0&&g.voiceBindingName!==void 0).map(g=>({bindingName:g.voiceBindingName,exportName:g.exportName})),wantsArchitecture:Se,wantsOpenApi:Ye,wantsOpenRpc:Qe}),jt=yg(e.projectRoot),qt=Se?We:[],Wt=Pi({functions:G,httpRoutes:qe,modules:qt,version:jt}),Ht=Ii({functions:G,modules:qt,version:jt}),Gt=`${JSON.stringify(Wt,void 0,2)}
|
|
9
|
-
`,Yt=`${JSON.stringify(Ht,void 0,2)}
|
|
10
|
-
`,Ne=Se&&X!==void 0?ao({...X,callEdges:ja(o,n),crons:p,functions:G,httpRoutes:qe,modules:We,queues:F,schema:a,services:oe,topics:se,workflows:L}):void 0,Qt=wi(Wt),Xt=Ci(Ht),Xe=S(n,xg),Yn=O(Xe),Je=[];if(!e.dryRun){O(M)||Qn(M,{recursive:!0});const g=(J,re)=>{xt(S(M,J),re),Je.push(J)},C=(J,re)=>{Sg(S(M,J),re),re!==""&&Je.push(J)};g("app.ts",Vt),g("dataModel.ts",f),g("api.ts",Ct),g("server.ts",te),g("functions.ts",Tt),g("shard.ts",Dt),g("crons.ts",Bt),g("vectors.ts",$t),g("drizzle.global.ts",Ae.global),g("drizzle.shard.ts",Ae.shard),C("containers.ts",Mt),C("workflows.ts",_t),C("agents.ts",Kt),C("queues.ts",zt),C("scheduler.ts",Wn),C("shardRegistry.ts",Hn),C("durableObjects.ts",Gn),C("seed.ts",Ut),C("collections.ts",Lt),C("openapi.json",Ye?Gt:""),C("openapi.ts",Ye?Qt:""),C("openrpc.json",Qe?Yt:""),C("openrpc.ts",Qe?Xt:""),C("architecture.json",Ne===void 0?"":`${JSON.stringify(Ne,void 0,2)}
|
|
11
|
-
`),C("architecture.ts",Ne===void 0?"":co(Ne)),(!Yn||e.updateSchemaBaseline===!0)&&xt(Xe,sr(Ge))}if(t){const g=Ze.now(),C=Math.round(g-s),J=Math.round(Ft-s),re=Math.round(g-Ft);console.error(`@lunora/codegen: codegen took ${C.toString()}ms (discovery ${J.toString()}ms, emit ${re.toString()}ms)`)}return{advisories:Rt,advisorContext:ye,agents:c,containers:u,cronTriggers:[...new Set([...Ui(p),...x])],generated:{agents:Kt,api:Ct,app:Vt,collections:Lt,containers:Mt,crons:Bt,dataModel:f,drizzleGlobal:Ae.global,drizzleShard:Ae.shard,functions:Tt,openApi:Gt,openApiModule:Qt,openRpc:Yt,openRpcModule:Xt,queues:zt,seed:Ut,server:te,shard:Dt,vectors:$t,workflows:_t},migrations:Ee,outputDirectory:M,platformDiagnostics:H.diagnostics,queues:F,schemaSnapshot:Ge,schemaSnapshotPath:Xe,workflows:L,writtenFiles:Je}};export{xg as SCHEMA_SNAPSHOT_FILENAME,Ig as createCodegenProject,bg as findTsconfig,Up as refreshCodegenProject,Vp as runCodegen};
|